ZTWHHH commited on
Commit
e45f5c7
·
verified ·
1 Parent(s): 3859e04

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. parrot/lib/python3.10/site-packages/matplotlib/_mathtext.py +0 -0
  3. parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.py +18 -0
  4. parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.pyi +16 -0
  5. parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/__init__.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.py +0 -0
  8. parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.pyi +772 -0
  9. parrot/lib/python3.10/site-packages/matplotlib/axes/_base.py +0 -0
  10. parrot/lib/python3.10/site-packages/matplotlib/axes/_base.pyi +459 -0
  11. parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.py +321 -0
  12. parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.pyi +45 -0
  13. parrot/lib/python3.10/site-packages/matplotlib/backends/__init__.py +5 -0
  14. parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.pyi +0 -0
  15. parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_pdf_ps.py +145 -0
  16. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3.py +582 -0
  17. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3agg.py +74 -0
  18. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3cairo.py +35 -0
  19. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4.py +595 -0
  20. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4cairo.py +32 -0
  21. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_mixed.py +119 -0
  22. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py +0 -0
  23. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py +1326 -0
  24. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt.py +1067 -0
  25. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5.py +28 -0
  26. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5agg.py +14 -0
  27. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5cairo.py +11 -0
  28. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qtagg.py +86 -0
  29. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py +1368 -0
  30. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_template.py +213 -0
  31. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_webagg_core.py +517 -0
  32. parrot/lib/python3.10/site-packages/matplotlib/backends/backend_wxagg.py +45 -0
  33. parrot/lib/python3.10/site-packages/matplotlib/backends/registry.py +420 -0
  34. parrot/lib/python3.10/site-packages/matplotlib/pyplot.py +0 -0
  35. parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/__init__.cpython-310.pyc +0 -0
  36. parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/_markers.cpython-310.pyc +0 -0
  37. parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/compare.cpython-310.pyc +0 -0
  38. parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/conftest.cpython-310.pyc +0 -0
  39. parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/decorators.cpython-310.pyc +0 -0
  40. parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py +211 -0
  41. parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/__init__.cpython-310.pyc +0 -0
  42. parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so +3 -0
  43. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h +24 -0
  44. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h +26 -0
  45. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h +149 -0
  46. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h +39 -0
  47. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h +21 -0
  48. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h +22 -0
  49. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_min_seqlen_native.h +20 -0
  50. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h +20 -0
.gitattributes CHANGED
@@ -914,3 +914,4 @@ videochat2/lib/python3.10/site-packages/torch/_inductor/__pycache__/lowering.cpy
914
  videochat2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
915
  videochat2/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text
916
  videochat2/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
914
  videochat2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
915
  videochat2/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs merge=lfs -text
916
  videochat2/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
917
+ parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/matplotlib/_mathtext.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _base
2
+ from ._axes import Axes # noqa: F401
3
+
4
+ # Backcompat.
5
+ Subplot = Axes
6
+
7
+
8
+ class _SubplotBaseMeta(type):
9
+ def __instancecheck__(self, obj):
10
+ return (isinstance(obj, _base._AxesBase)
11
+ and obj.get_subplotspec() is not None)
12
+
13
+
14
+ class SubplotBase(metaclass=_SubplotBaseMeta):
15
+ pass
16
+
17
+
18
+ def subplot_class_factory(cls): return cls
parrot/lib/python3.10/site-packages/matplotlib/axes/__init__.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypeVar
2
+
3
+ from ._axes import Axes as Axes
4
+
5
+
6
+ _T = TypeVar("_T")
7
+
8
+ # Backcompat.
9
+ Subplot = Axes
10
+
11
+ class _SubplotBaseMeta(type):
12
+ def __instancecheck__(self, obj) -> bool: ...
13
+
14
+ class SubplotBase(metaclass=_SubplotBaseMeta): ...
15
+
16
+ def subplot_class_factory(cls: type[_T]) -> type[_T]: ...
parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (910 Bytes). View file
 
parrot/lib/python3.10/site-packages/matplotlib/axes/__pycache__/_secondary_axes.cpython-310.pyc ADDED
Binary file (9.72 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/site-packages/matplotlib/axes/_axes.pyi ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.axes._base import _AxesBase
2
+ from matplotlib.axes._secondary_axes import SecondaryAxis
3
+
4
+ from matplotlib.artist import Artist
5
+ from matplotlib.backend_bases import RendererBase
6
+ from matplotlib.collections import (
7
+ Collection,
8
+ LineCollection,
9
+ PathCollection,
10
+ PolyCollection,
11
+ EventCollection,
12
+ QuadMesh,
13
+ )
14
+ from matplotlib.colors import Colormap, Normalize
15
+ from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
16
+ from matplotlib.contour import ContourSet, QuadContourSet
17
+ from matplotlib.image import AxesImage, PcolorImage
18
+ from matplotlib.legend import Legend
19
+ from matplotlib.legend_handler import HandlerBase
20
+ from matplotlib.lines import Line2D, AxLine
21
+ from matplotlib.mlab import GaussianKDE
22
+ from matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge
23
+ from matplotlib.quiver import Quiver, QuiverKey, Barbs
24
+ from matplotlib.text import Annotation, Text
25
+ from matplotlib.transforms import Transform, Bbox
26
+ import matplotlib.tri as mtri
27
+ import matplotlib.table as mtable
28
+ import matplotlib.stackplot as mstack
29
+ import matplotlib.streamplot as mstream
30
+
31
+ import datetime
32
+ import PIL.Image
33
+ from collections.abc import Callable, Iterable, Sequence
34
+ from typing import Any, Literal, overload
35
+ import numpy as np
36
+ from numpy.typing import ArrayLike
37
+ from matplotlib.typing import ColorType, MarkerType, LineStyleType
38
+
39
+ class Axes(_AxesBase):
40
+ def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ...
41
+ def set_title(
42
+ self,
43
+ label: str,
44
+ fontdict: dict[str, Any] | None = ...,
45
+ loc: Literal["left", "center", "right"] | None = ...,
46
+ pad: float | None = ...,
47
+ *,
48
+ y: float | None = ...,
49
+ **kwargs
50
+ ) -> Text: ...
51
+ def get_legend_handles_labels(
52
+ self, legend_handler_map: dict[type, HandlerBase] | None = ...
53
+ ) -> tuple[list[Artist], list[Any]]: ...
54
+ legend_: Legend | None
55
+
56
+ @overload
57
+ def legend(self) -> Legend: ...
58
+ @overload
59
+ def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ...
60
+ @overload
61
+ def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ...
62
+ @overload
63
+ def legend(self, labels: Iterable[str], **kwargs) -> Legend: ...
64
+ @overload
65
+ def legend(self, **kwargs) -> Legend: ...
66
+
67
+ def inset_axes(
68
+ self,
69
+ bounds: tuple[float, float, float, float],
70
+ *,
71
+ transform: Transform | None = ...,
72
+ zorder: float = ...,
73
+ **kwargs
74
+ ) -> Axes: ...
75
+ def indicate_inset(
76
+ self,
77
+ bounds: tuple[float, float, float, float],
78
+ inset_ax: Axes | None = ...,
79
+ *,
80
+ transform: Transform | None = ...,
81
+ facecolor: ColorType = ...,
82
+ edgecolor: ColorType = ...,
83
+ alpha: float = ...,
84
+ zorder: float = ...,
85
+ **kwargs
86
+ ) -> Rectangle: ...
87
+ def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> Rectangle: ...
88
+ def secondary_xaxis(
89
+ self,
90
+ location: Literal["top", "bottom"] | float,
91
+ *,
92
+ functions: tuple[
93
+ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
94
+ ]
95
+ | Transform
96
+ | None = ...,
97
+ transform: Transform | None = ...,
98
+ **kwargs
99
+ ) -> SecondaryAxis: ...
100
+ def secondary_yaxis(
101
+ self,
102
+ location: Literal["left", "right"] | float,
103
+ *,
104
+ functions: tuple[
105
+ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
106
+ ]
107
+ | Transform
108
+ | None = ...,
109
+ transform: Transform | None = ...,
110
+ **kwargs
111
+ ) -> SecondaryAxis: ...
112
+ def text(
113
+ self,
114
+ x: float,
115
+ y: float,
116
+ s: str,
117
+ fontdict: dict[str, Any] | None = ...,
118
+ **kwargs
119
+ ) -> Text: ...
120
+ def annotate(
121
+ self,
122
+ text: str,
123
+ xy: tuple[float, float],
124
+ xytext: tuple[float, float] | None = ...,
125
+ xycoords: str
126
+ | Artist
127
+ | Transform
128
+ | Callable[[RendererBase], Bbox | Transform]
129
+ | tuple[float, float] = ...,
130
+ textcoords: str
131
+ | Artist
132
+ | Transform
133
+ | Callable[[RendererBase], Bbox | Transform]
134
+ | tuple[float, float]
135
+ | None = ...,
136
+ arrowprops: dict[str, Any] | None = ...,
137
+ annotation_clip: bool | None = ...,
138
+ **kwargs
139
+ ) -> Annotation: ...
140
+ def axhline(
141
+ self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs
142
+ ) -> Line2D: ...
143
+ def axvline(
144
+ self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs
145
+ ) -> Line2D: ...
146
+
147
+ # TODO: Could separate the xy2 and slope signatures
148
+ def axline(
149
+ self,
150
+ xy1: tuple[float, float],
151
+ xy2: tuple[float, float] | None = ...,
152
+ *,
153
+ slope: float | None = ...,
154
+ **kwargs
155
+ ) -> AxLine: ...
156
+ def axhspan(
157
+ self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs
158
+ ) -> Rectangle: ...
159
+ def axvspan(
160
+ self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs
161
+ ) -> Rectangle: ...
162
+ def hlines(
163
+ self,
164
+ y: float | ArrayLike,
165
+ xmin: float | ArrayLike,
166
+ xmax: float | ArrayLike,
167
+ colors: ColorType | Sequence[ColorType] | None = ...,
168
+ linestyles: LineStyleType = ...,
169
+ label: str = ...,
170
+ *,
171
+ data=...,
172
+ **kwargs
173
+ ) -> LineCollection: ...
174
+ def vlines(
175
+ self,
176
+ x: float | ArrayLike,
177
+ ymin: float | ArrayLike,
178
+ ymax: float | ArrayLike,
179
+ colors: ColorType | Sequence[ColorType] | None = ...,
180
+ linestyles: LineStyleType = ...,
181
+ label: str = ...,
182
+ *,
183
+ data=...,
184
+ **kwargs
185
+ ) -> LineCollection: ...
186
+ def eventplot(
187
+ self,
188
+ positions: ArrayLike | Sequence[ArrayLike],
189
+ orientation: Literal["horizontal", "vertical"] = ...,
190
+ lineoffsets: float | Sequence[float] = ...,
191
+ linelengths: float | Sequence[float] = ...,
192
+ linewidths: float | Sequence[float] | None = ...,
193
+ colors: ColorType | Sequence[ColorType] | None = ...,
194
+ alpha: float | Sequence[float] | None = ...,
195
+ linestyles: LineStyleType | Sequence[LineStyleType] = ...,
196
+ *,
197
+ data=...,
198
+ **kwargs
199
+ ) -> EventCollection: ...
200
+ def plot(
201
+ self,
202
+ *args: float | ArrayLike | str,
203
+ scalex: bool = ...,
204
+ scaley: bool = ...,
205
+ data = ...,
206
+ **kwargs
207
+ ) -> list[Line2D]: ...
208
+ def plot_date(
209
+ self,
210
+ x: ArrayLike,
211
+ y: ArrayLike,
212
+ fmt: str = ...,
213
+ tz: str | datetime.tzinfo | None = ...,
214
+ xdate: bool = ...,
215
+ ydate: bool = ...,
216
+ *,
217
+ data=...,
218
+ **kwargs
219
+ ) -> list[Line2D]: ...
220
+ def loglog(self, *args, **kwargs) -> list[Line2D]: ...
221
+ def semilogx(self, *args, **kwargs) -> list[Line2D]: ...
222
+ def semilogy(self, *args, **kwargs) -> list[Line2D]: ...
223
+ def acorr(
224
+ self, x: ArrayLike, *, data=..., **kwargs
225
+ ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
226
+ def xcorr(
227
+ self,
228
+ x: ArrayLike,
229
+ y: ArrayLike,
230
+ normed: bool = ...,
231
+ detrend: Callable[[ArrayLike], ArrayLike] = ...,
232
+ usevlines: bool = ...,
233
+ maxlags: int = ...,
234
+ *,
235
+ data = ...,
236
+ **kwargs
237
+ ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
238
+ def step(
239
+ self,
240
+ x: ArrayLike,
241
+ y: ArrayLike,
242
+ *args,
243
+ where: Literal["pre", "post", "mid"] = ...,
244
+ data = ...,
245
+ **kwargs
246
+ ) -> list[Line2D]: ...
247
+ def bar(
248
+ self,
249
+ x: float | ArrayLike,
250
+ height: float | ArrayLike,
251
+ width: float | ArrayLike = ...,
252
+ bottom: float | ArrayLike | None = ...,
253
+ *,
254
+ align: Literal["center", "edge"] = ...,
255
+ data = ...,
256
+ **kwargs
257
+ ) -> BarContainer: ...
258
+ def barh(
259
+ self,
260
+ y: float | ArrayLike,
261
+ width: float | ArrayLike,
262
+ height: float | ArrayLike = ...,
263
+ left: float | ArrayLike | None = ...,
264
+ *,
265
+ align: Literal["center", "edge"] = ...,
266
+ data = ...,
267
+ **kwargs
268
+ ) -> BarContainer: ...
269
+ def bar_label(
270
+ self,
271
+ container: BarContainer,
272
+ labels: ArrayLike | None = ...,
273
+ *,
274
+ fmt: str | Callable[[float], str] = ...,
275
+ label_type: Literal["center", "edge"] = ...,
276
+ padding: float = ...,
277
+ **kwargs
278
+ ) -> list[Annotation]: ...
279
+ def broken_barh(
280
+ self,
281
+ xranges: Sequence[tuple[float, float]],
282
+ yrange: tuple[float, float],
283
+ *,
284
+ data=...,
285
+ **kwargs
286
+ ) -> PolyCollection: ...
287
+ def stem(
288
+ self,
289
+ *args: ArrayLike | str,
290
+ linefmt: str | None = ...,
291
+ markerfmt: str | None = ...,
292
+ basefmt: str | None = ...,
293
+ bottom: float = ...,
294
+ label: str | None = ...,
295
+ orientation: Literal["vertical", "horizontal"] = ...,
296
+ data=...,
297
+ ) -> StemContainer: ...
298
+
299
+ # TODO: data kwarg preprocessor?
300
+ def pie(
301
+ self,
302
+ x: ArrayLike,
303
+ explode: ArrayLike | None = ...,
304
+ labels: Sequence[str] | None = ...,
305
+ colors: ColorType | Sequence[ColorType] | None = ...,
306
+ autopct: str | Callable[[float], str] | None = ...,
307
+ pctdistance: float = ...,
308
+ shadow: bool = ...,
309
+ labeldistance: float | None = ...,
310
+ startangle: float = ...,
311
+ radius: float = ...,
312
+ counterclock: bool = ...,
313
+ wedgeprops: dict[str, Any] | None = ...,
314
+ textprops: dict[str, Any] | None = ...,
315
+ center: tuple[float, float] = ...,
316
+ frame: bool = ...,
317
+ rotatelabels: bool = ...,
318
+ *,
319
+ normalize: bool = ...,
320
+ hatch: str | Sequence[str] | None = ...,
321
+ data=...,
322
+ ) -> tuple[list[Wedge], list[Text]] | tuple[
323
+ list[Wedge], list[Text], list[Text]
324
+ ]: ...
325
+ def errorbar(
326
+ self,
327
+ x: float | ArrayLike,
328
+ y: float | ArrayLike,
329
+ yerr: float | ArrayLike | None = ...,
330
+ xerr: float | ArrayLike | None = ...,
331
+ fmt: str = ...,
332
+ ecolor: ColorType | None = ...,
333
+ elinewidth: float | None = ...,
334
+ capsize: float | None = ...,
335
+ barsabove: bool = ...,
336
+ lolims: bool | ArrayLike = ...,
337
+ uplims: bool | ArrayLike = ...,
338
+ xlolims: bool | ArrayLike = ...,
339
+ xuplims: bool | ArrayLike = ...,
340
+ errorevery: int | tuple[int, int] = ...,
341
+ capthick: float | None = ...,
342
+ *,
343
+ data=...,
344
+ **kwargs
345
+ ) -> ErrorbarContainer: ...
346
+ def boxplot(
347
+ self,
348
+ x: ArrayLike | Sequence[ArrayLike],
349
+ notch: bool | None = ...,
350
+ sym: str | None = ...,
351
+ vert: bool | None = ...,
352
+ whis: float | tuple[float, float] | None = ...,
353
+ positions: ArrayLike | None = ...,
354
+ widths: float | ArrayLike | None = ...,
355
+ patch_artist: bool | None = ...,
356
+ bootstrap: int | None = ...,
357
+ usermedians: ArrayLike | None = ...,
358
+ conf_intervals: ArrayLike | None = ...,
359
+ meanline: bool | None = ...,
360
+ showmeans: bool | None = ...,
361
+ showcaps: bool | None = ...,
362
+ showbox: bool | None = ...,
363
+ showfliers: bool | None = ...,
364
+ boxprops: dict[str, Any] | None = ...,
365
+ tick_labels: Sequence[str] | None = ...,
366
+ flierprops: dict[str, Any] | None = ...,
367
+ medianprops: dict[str, Any] | None = ...,
368
+ meanprops: dict[str, Any] | None = ...,
369
+ capprops: dict[str, Any] | None = ...,
370
+ whiskerprops: dict[str, Any] | None = ...,
371
+ manage_ticks: bool = ...,
372
+ autorange: bool = ...,
373
+ zorder: float | None = ...,
374
+ capwidths: float | ArrayLike | None = ...,
375
+ label: Sequence[str] | None = ...,
376
+ *,
377
+ data=...,
378
+ ) -> dict[str, Any]: ...
379
+ def bxp(
380
+ self,
381
+ bxpstats: Sequence[dict[str, Any]],
382
+ positions: ArrayLike | None = ...,
383
+ widths: float | ArrayLike | None = ...,
384
+ vert: bool = ...,
385
+ patch_artist: bool = ...,
386
+ shownotches: bool = ...,
387
+ showmeans: bool = ...,
388
+ showcaps: bool = ...,
389
+ showbox: bool = ...,
390
+ showfliers: bool = ...,
391
+ boxprops: dict[str, Any] | None = ...,
392
+ whiskerprops: dict[str, Any] | None = ...,
393
+ flierprops: dict[str, Any] | None = ...,
394
+ medianprops: dict[str, Any] | None = ...,
395
+ capprops: dict[str, Any] | None = ...,
396
+ meanprops: dict[str, Any] | None = ...,
397
+ meanline: bool = ...,
398
+ manage_ticks: bool = ...,
399
+ zorder: float | None = ...,
400
+ capwidths: float | ArrayLike | None = ...,
401
+ label: Sequence[str] | None = ...,
402
+ ) -> dict[str, Any]: ...
403
+ def scatter(
404
+ self,
405
+ x: float | ArrayLike,
406
+ y: float | ArrayLike,
407
+ s: float | ArrayLike | None = ...,
408
+ c: ArrayLike | Sequence[ColorType] | ColorType | None = ...,
409
+ marker: MarkerType | None = ...,
410
+ cmap: str | Colormap | None = ...,
411
+ norm: str | Normalize | None = ...,
412
+ vmin: float | None = ...,
413
+ vmax: float | None = ...,
414
+ alpha: float | None = ...,
415
+ linewidths: float | Sequence[float] | None = ...,
416
+ *,
417
+ edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ...,
418
+ plotnonfinite: bool = ...,
419
+ data=...,
420
+ **kwargs
421
+ ) -> PathCollection: ...
422
+ def hexbin(
423
+ self,
424
+ x: ArrayLike,
425
+ y: ArrayLike,
426
+ C: ArrayLike | None = ...,
427
+ gridsize: int | tuple[int, int] = ...,
428
+ bins: Literal["log"] | int | Sequence[float] | None = ...,
429
+ xscale: Literal["linear", "log"] = ...,
430
+ yscale: Literal["linear", "log"] = ...,
431
+ extent: tuple[float, float, float, float] | None = ...,
432
+ cmap: str | Colormap | None = ...,
433
+ norm: str | Normalize | None = ...,
434
+ vmin: float | None = ...,
435
+ vmax: float | None = ...,
436
+ alpha: float | None = ...,
437
+ linewidths: float | None = ...,
438
+ edgecolors: Literal["face", "none"] | ColorType = ...,
439
+ reduce_C_function: Callable[[np.ndarray | list[float]], float] = ...,
440
+ mincnt: int | None = ...,
441
+ marginals: bool = ...,
442
+ *,
443
+ data=...,
444
+ **kwargs
445
+ ) -> PolyCollection: ...
446
+ def arrow(
447
+ self, x: float, y: float, dx: float, dy: float, **kwargs
448
+ ) -> FancyArrow: ...
449
+ def quiverkey(
450
+ self, Q: Quiver, X: float, Y: float, U: float, label: str, **kwargs
451
+ ) -> QuiverKey: ...
452
+ def quiver(self, *args, data=..., **kwargs) -> Quiver: ...
453
+ def barbs(self, *args, data=..., **kwargs) -> Barbs: ...
454
+ def fill(self, *args, data=..., **kwargs) -> list[Polygon]: ...
455
+ def fill_between(
456
+ self,
457
+ x: ArrayLike,
458
+ y1: ArrayLike | float,
459
+ y2: ArrayLike | float = ...,
460
+ where: Sequence[bool] | None = ...,
461
+ interpolate: bool = ...,
462
+ step: Literal["pre", "post", "mid"] | None = ...,
463
+ *,
464
+ data=...,
465
+ **kwargs
466
+ ) -> PolyCollection: ...
467
+ def fill_betweenx(
468
+ self,
469
+ y: ArrayLike,
470
+ x1: ArrayLike | float,
471
+ x2: ArrayLike | float = ...,
472
+ where: Sequence[bool] | None = ...,
473
+ step: Literal["pre", "post", "mid"] | None = ...,
474
+ interpolate: bool = ...,
475
+ *,
476
+ data=...,
477
+ **kwargs
478
+ ) -> PolyCollection: ...
479
+ def imshow(
480
+ self,
481
+ X: ArrayLike | PIL.Image.Image,
482
+ cmap: str | Colormap | None = ...,
483
+ norm: str | Normalize | None = ...,
484
+ *,
485
+ aspect: Literal["equal", "auto"] | float | None = ...,
486
+ interpolation: str | None = ...,
487
+ alpha: float | ArrayLike | None = ...,
488
+ vmin: float | None = ...,
489
+ vmax: float | None = ...,
490
+ origin: Literal["upper", "lower"] | None = ...,
491
+ extent: tuple[float, float, float, float] | None = ...,
492
+ interpolation_stage: Literal["data", "rgba"] | None = ...,
493
+ filternorm: bool = ...,
494
+ filterrad: float = ...,
495
+ resample: bool | None = ...,
496
+ url: str | None = ...,
497
+ data=...,
498
+ **kwargs
499
+ ) -> AxesImage: ...
500
+ def pcolor(
501
+ self,
502
+ *args: ArrayLike,
503
+ shading: Literal["flat", "nearest", "auto"] | None = ...,
504
+ alpha: float | None = ...,
505
+ norm: str | Normalize | None = ...,
506
+ cmap: str | Colormap | None = ...,
507
+ vmin: float | None = ...,
508
+ vmax: float | None = ...,
509
+ data=...,
510
+ **kwargs
511
+ ) -> Collection: ...
512
+ def pcolormesh(
513
+ self,
514
+ *args: ArrayLike,
515
+ alpha: float | None = ...,
516
+ norm: str | Normalize | None = ...,
517
+ cmap: str | Colormap | None = ...,
518
+ vmin: float | None = ...,
519
+ vmax: float | None = ...,
520
+ shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ...,
521
+ antialiased: bool = ...,
522
+ data=...,
523
+ **kwargs
524
+ ) -> QuadMesh: ...
525
+ def pcolorfast(
526
+ self,
527
+ *args: ArrayLike | tuple[float, float],
528
+ alpha: float | None = ...,
529
+ norm: str | Normalize | None = ...,
530
+ cmap: str | Colormap | None = ...,
531
+ vmin: float | None = ...,
532
+ vmax: float | None = ...,
533
+ data=...,
534
+ **kwargs
535
+ ) -> AxesImage | PcolorImage | QuadMesh: ...
536
+ def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ...
537
+ def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ...
538
+ def clabel(
539
+ self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs
540
+ ) -> list[Text]: ...
541
+ def hist(
542
+ self,
543
+ x: ArrayLike | Sequence[ArrayLike],
544
+ bins: int | Sequence[float] | str | None = ...,
545
+ range: tuple[float, float] | None = ...,
546
+ density: bool = ...,
547
+ weights: ArrayLike | None = ...,
548
+ cumulative: bool | float = ...,
549
+ bottom: ArrayLike | float | None = ...,
550
+ histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ...,
551
+ align: Literal["left", "mid", "right"] = ...,
552
+ orientation: Literal["vertical", "horizontal"] = ...,
553
+ rwidth: float | None = ...,
554
+ log: bool = ...,
555
+ color: ColorType | Sequence[ColorType] | None = ...,
556
+ label: str | Sequence[str] | None = ...,
557
+ stacked: bool = ...,
558
+ *,
559
+ data=...,
560
+ **kwargs
561
+ ) -> tuple[
562
+ np.ndarray | list[np.ndarray],
563
+ np.ndarray,
564
+ BarContainer | Polygon | list[BarContainer | Polygon],
565
+ ]: ...
566
+ def stairs(
567
+ self,
568
+ values: ArrayLike,
569
+ edges: ArrayLike | None = ...,
570
+ *,
571
+ orientation: Literal["vertical", "horizontal"] = ...,
572
+ baseline: float | ArrayLike | None = ...,
573
+ fill: bool = ...,
574
+ data=...,
575
+ **kwargs
576
+ ) -> StepPatch: ...
577
+ def hist2d(
578
+ self,
579
+ x: ArrayLike,
580
+ y: ArrayLike,
581
+ bins: None
582
+ | int
583
+ | tuple[int, int]
584
+ | ArrayLike
585
+ | tuple[ArrayLike, ArrayLike] = ...,
586
+ range: ArrayLike | None = ...,
587
+ density: bool = ...,
588
+ weights: ArrayLike | None = ...,
589
+ cmin: float | None = ...,
590
+ cmax: float | None = ...,
591
+ *,
592
+ data=...,
593
+ **kwargs
594
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ...
595
+ def ecdf(
596
+ self,
597
+ x: ArrayLike,
598
+ weights: ArrayLike | None = ...,
599
+ *,
600
+ complementary: bool=...,
601
+ orientation: Literal["vertical", "horizonatal"]=...,
602
+ compress: bool=...,
603
+ data=...,
604
+ **kwargs
605
+ ) -> Line2D: ...
606
+ def psd(
607
+ self,
608
+ x: ArrayLike,
609
+ NFFT: int | None = ...,
610
+ Fs: float | None = ...,
611
+ Fc: int | None = ...,
612
+ detrend: Literal["none", "mean", "linear"]
613
+ | Callable[[ArrayLike], ArrayLike]
614
+ | None = ...,
615
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
616
+ noverlap: int | None = ...,
617
+ pad_to: int | None = ...,
618
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
619
+ scale_by_freq: bool | None = ...,
620
+ return_line: bool | None = ...,
621
+ *,
622
+ data=...,
623
+ **kwargs
624
+ ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
625
+ def csd(
626
+ self,
627
+ x: ArrayLike,
628
+ y: ArrayLike,
629
+ NFFT: int | None = ...,
630
+ Fs: float | None = ...,
631
+ Fc: int | None = ...,
632
+ detrend: Literal["none", "mean", "linear"]
633
+ | Callable[[ArrayLike], ArrayLike]
634
+ | None = ...,
635
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
636
+ noverlap: int | None = ...,
637
+ pad_to: int | None = ...,
638
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
639
+ scale_by_freq: bool | None = ...,
640
+ return_line: bool | None = ...,
641
+ *,
642
+ data=...,
643
+ **kwargs
644
+ ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
645
+ def magnitude_spectrum(
646
+ self,
647
+ x: ArrayLike,
648
+ Fs: float | None = ...,
649
+ Fc: int | None = ...,
650
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
651
+ pad_to: int | None = ...,
652
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
653
+ scale: Literal["default", "linear", "dB"] | None = ...,
654
+ *,
655
+ data=...,
656
+ **kwargs
657
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
658
+ def angle_spectrum(
659
+ self,
660
+ x: ArrayLike,
661
+ Fs: float | None = ...,
662
+ Fc: int | None = ...,
663
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
664
+ pad_to: int | None = ...,
665
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
666
+ *,
667
+ data=...,
668
+ **kwargs
669
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
670
+ def phase_spectrum(
671
+ self,
672
+ x: ArrayLike,
673
+ Fs: float | None = ...,
674
+ Fc: int | None = ...,
675
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
676
+ pad_to: int | None = ...,
677
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
678
+ *,
679
+ data=...,
680
+ **kwargs
681
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
682
+ def cohere(
683
+ self,
684
+ x: ArrayLike,
685
+ y: ArrayLike,
686
+ NFFT: int = ...,
687
+ Fs: float = ...,
688
+ Fc: int = ...,
689
+ detrend: Literal["none", "mean", "linear"]
690
+ | Callable[[ArrayLike], ArrayLike] = ...,
691
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ...,
692
+ noverlap: int = ...,
693
+ pad_to: int | None = ...,
694
+ sides: Literal["default", "onesided", "twosided"] = ...,
695
+ scale_by_freq: bool | None = ...,
696
+ *,
697
+ data=...,
698
+ **kwargs
699
+ ) -> tuple[np.ndarray, np.ndarray]: ...
700
+ def specgram(
701
+ self,
702
+ x: ArrayLike,
703
+ NFFT: int | None = ...,
704
+ Fs: float | None = ...,
705
+ Fc: int | None = ...,
706
+ detrend: Literal["none", "mean", "linear"]
707
+ | Callable[[ArrayLike], ArrayLike]
708
+ | None = ...,
709
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
710
+ noverlap: int | None = ...,
711
+ cmap: str | Colormap | None = ...,
712
+ xextent: tuple[float, float] | None = ...,
713
+ pad_to: int | None = ...,
714
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
715
+ scale_by_freq: bool | None = ...,
716
+ mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ...,
717
+ scale: Literal["default", "linear", "dB"] | None = ...,
718
+ vmin: float | None = ...,
719
+ vmax: float | None = ...,
720
+ *,
721
+ data=...,
722
+ **kwargs
723
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ...
724
+ def spy(
725
+ self,
726
+ Z: ArrayLike,
727
+ precision: float | Literal["present"] = ...,
728
+ marker: str | None = ...,
729
+ markersize: float | None = ...,
730
+ aspect: Literal["equal", "auto"] | float | None = ...,
731
+ origin: Literal["upper", "lower"] = ...,
732
+ **kwargs
733
+ ) -> AxesImage: ...
734
+ def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ...
735
+ def violinplot(
736
+ self,
737
+ dataset: ArrayLike | Sequence[ArrayLike],
738
+ positions: ArrayLike | None = ...,
739
+ vert: bool = ...,
740
+ widths: float | ArrayLike = ...,
741
+ showmeans: bool = ...,
742
+ showextrema: bool = ...,
743
+ showmedians: bool = ...,
744
+ quantiles: Sequence[float | Sequence[float]] | None = ...,
745
+ points: int = ...,
746
+ bw_method: Literal["scott", "silverman"]
747
+ | float
748
+ | Callable[[GaussianKDE], float]
749
+ | None = ...,
750
+ side: Literal["both", "low", "high"] = ...,
751
+ *,
752
+ data=...,
753
+ ) -> dict[str, Collection]: ...
754
+ def violin(
755
+ self,
756
+ vpstats: Sequence[dict[str, Any]],
757
+ positions: ArrayLike | None = ...,
758
+ vert: bool = ...,
759
+ widths: float | ArrayLike = ...,
760
+ showmeans: bool = ...,
761
+ showextrema: bool = ...,
762
+ showmedians: bool = ...,
763
+ side: Literal["both", "low", "high"] = ...,
764
+ ) -> dict[str, Collection]: ...
765
+
766
+ table = mtable.table
767
+ stackplot = mstack.stackplot
768
+ streamplot = mstream.streamplot
769
+ tricontour = mtri.tricontour
770
+ tricontourf = mtri.tricontourf
771
+ tripcolor = mtri.tripcolor
772
+ triplot = mtri.triplot
parrot/lib/python3.10/site-packages/matplotlib/axes/_base.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/site-packages/matplotlib/axes/_base.pyi ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.artist as martist
2
+
3
+ import datetime
4
+ from collections.abc import Callable, Iterable, Iterator, Sequence
5
+ from matplotlib import cbook
6
+ from matplotlib.artist import Artist
7
+ from matplotlib.axes import Axes
8
+ from matplotlib.axis import XAxis, YAxis, Tick
9
+ from matplotlib.backend_bases import RendererBase, MouseButton, MouseEvent
10
+ from matplotlib.cbook import CallbackRegistry
11
+ from matplotlib.container import Container
12
+ from matplotlib.collections import Collection
13
+ from matplotlib.cm import ScalarMappable
14
+ from matplotlib.legend import Legend
15
+ from matplotlib.lines import Line2D
16
+ from matplotlib.gridspec import SubplotSpec, GridSpec
17
+ from matplotlib.figure import Figure
18
+ from matplotlib.image import AxesImage
19
+ from matplotlib.patches import Patch
20
+ from matplotlib.scale import ScaleBase
21
+ from matplotlib.spines import Spines
22
+ from matplotlib.table import Table
23
+ from matplotlib.text import Text
24
+ from matplotlib.transforms import Transform, Bbox
25
+
26
+ from cycler import Cycler
27
+
28
+ import numpy as np
29
+ from numpy.typing import ArrayLike
30
+ from typing import Any, Literal, TypeVar, overload
31
+ from matplotlib.typing import ColorType
32
+
33
+ _T = TypeVar("_T", bound=Artist)
34
+
35
+ class _axis_method_wrapper:
36
+ attr_name: str
37
+ method_name: str
38
+ __doc__: str
39
+ def __init__(
40
+ self, attr_name: str, method_name: str, *, doc_sub: dict[str, str] | None = ...
41
+ ) -> None: ...
42
+ def __set_name__(self, owner: Any, name: str) -> None: ...
43
+
44
+ class _AxesBase(martist.Artist):
45
+ name: str
46
+ patch: Patch
47
+ spines: Spines
48
+ fmt_xdata: Callable[[float], str] | None
49
+ fmt_ydata: Callable[[float], str] | None
50
+ xaxis: XAxis
51
+ yaxis: YAxis
52
+ bbox: Bbox
53
+ dataLim: Bbox
54
+ transAxes: Transform
55
+ transScale: Transform
56
+ transLimits: Transform
57
+ transData: Transform
58
+ ignore_existing_data_limits: bool
59
+ axison: bool
60
+ containers: list[Container]
61
+ callbacks: CallbackRegistry
62
+ child_axes: list[_AxesBase]
63
+ legend_: Legend | None
64
+ title: Text
65
+ _projection_init: Any
66
+
67
+ def __init__(
68
+ self,
69
+ fig: Figure,
70
+ *args: tuple[float, float, float, float] | Bbox | int,
71
+ facecolor: ColorType | None = ...,
72
+ frameon: bool = ...,
73
+ sharex: _AxesBase | None = ...,
74
+ sharey: _AxesBase | None = ...,
75
+ label: Any = ...,
76
+ xscale: str | ScaleBase | None = ...,
77
+ yscale: str | ScaleBase | None = ...,
78
+ box_aspect: float | None = ...,
79
+ forward_navigation_events: bool | Literal["auto"] = ...,
80
+ **kwargs
81
+ ) -> None: ...
82
+ def get_subplotspec(self) -> SubplotSpec | None: ...
83
+ def set_subplotspec(self, subplotspec: SubplotSpec) -> None: ...
84
+ def get_gridspec(self) -> GridSpec | None: ...
85
+ def set_figure(self, fig: Figure) -> None: ...
86
+ @property
87
+ def viewLim(self) -> Bbox: ...
88
+ def get_xaxis_transform(
89
+ self, which: Literal["grid", "tick1", "tick2"] = ...
90
+ ) -> Transform: ...
91
+ def get_xaxis_text1_transform(
92
+ self, pad_points: float
93
+ ) -> tuple[
94
+ Transform,
95
+ Literal["center", "top", "bottom", "baseline", "center_baseline"],
96
+ Literal["center", "left", "right"],
97
+ ]: ...
98
+ def get_xaxis_text2_transform(
99
+ self, pad_points
100
+ ) -> tuple[
101
+ Transform,
102
+ Literal["center", "top", "bottom", "baseline", "center_baseline"],
103
+ Literal["center", "left", "right"],
104
+ ]: ...
105
+ def get_yaxis_transform(
106
+ self, which: Literal["grid", "tick1", "tick2"] = ...
107
+ ) -> Transform: ...
108
+ def get_yaxis_text1_transform(
109
+ self, pad_points
110
+ ) -> tuple[
111
+ Transform,
112
+ Literal["center", "top", "bottom", "baseline", "center_baseline"],
113
+ Literal["center", "left", "right"],
114
+ ]: ...
115
+ def get_yaxis_text2_transform(
116
+ self, pad_points
117
+ ) -> tuple[
118
+ Transform,
119
+ Literal["center", "top", "bottom", "baseline", "center_baseline"],
120
+ Literal["center", "left", "right"],
121
+ ]: ...
122
+ def get_position(self, original: bool = ...) -> Bbox: ...
123
+ def set_position(
124
+ self,
125
+ pos: Bbox | tuple[float, float, float, float],
126
+ which: Literal["both", "active", "original"] = ...,
127
+ ) -> None: ...
128
+ def reset_position(self) -> None: ...
129
+ def set_axes_locator(
130
+ self, locator: Callable[[_AxesBase, RendererBase], Bbox]
131
+ ) -> None: ...
132
+ def get_axes_locator(self) -> Callable[[_AxesBase, RendererBase], Bbox]: ...
133
+ def sharex(self, other: _AxesBase) -> None: ...
134
+ def sharey(self, other: _AxesBase) -> None: ...
135
+ def clear(self) -> None: ...
136
+ def cla(self) -> None: ...
137
+
138
+ class ArtistList(Sequence[_T]):
139
+ def __init__(
140
+ self,
141
+ axes: _AxesBase,
142
+ prop_name: str,
143
+ valid_types: type | Iterable[type] | None = ...,
144
+ invalid_types: type | Iterable[type] | None = ...,
145
+ ) -> None: ...
146
+ def __len__(self) -> int: ...
147
+ def __iter__(self) -> Iterator[_T]: ...
148
+ @overload
149
+ def __getitem__(self, key: int) -> _T: ...
150
+ @overload
151
+ def __getitem__(self, key: slice) -> list[_T]: ...
152
+
153
+ @overload
154
+ def __add__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...
155
+ @overload
156
+ def __add__(self, other: list[Any]) -> list[Any]: ...
157
+ @overload
158
+ def __add__(self, other: tuple[Any]) -> tuple[Any]: ...
159
+
160
+ @overload
161
+ def __radd__(self, other: _AxesBase.ArtistList[_T]) -> list[_T]: ...
162
+ @overload
163
+ def __radd__(self, other: list[Any]) -> list[Any]: ...
164
+ @overload
165
+ def __radd__(self, other: tuple[Any]) -> tuple[Any]: ...
166
+
167
+ @property
168
+ def artists(self) -> _AxesBase.ArtistList[Artist]: ...
169
+ @property
170
+ def collections(self) -> _AxesBase.ArtistList[Collection]: ...
171
+ @property
172
+ def images(self) -> _AxesBase.ArtistList[AxesImage]: ...
173
+ @property
174
+ def lines(self) -> _AxesBase.ArtistList[Line2D]: ...
175
+ @property
176
+ def patches(self) -> _AxesBase.ArtistList[Patch]: ...
177
+ @property
178
+ def tables(self) -> _AxesBase.ArtistList[Table]: ...
179
+ @property
180
+ def texts(self) -> _AxesBase.ArtistList[Text]: ...
181
+ def get_facecolor(self) -> ColorType: ...
182
+ def set_facecolor(self, color: ColorType | None) -> None: ...
183
+ @overload
184
+ def set_prop_cycle(self, cycler: Cycler) -> None: ...
185
+ @overload
186
+ def set_prop_cycle(self, label: str, values: Iterable[Any]) -> None: ...
187
+ @overload
188
+ def set_prop_cycle(self, **kwargs: Iterable[Any]) -> None: ...
189
+ def get_aspect(self) -> float | Literal["auto"]: ...
190
+ def set_aspect(
191
+ self,
192
+ aspect: float | Literal["auto", "equal"],
193
+ adjustable: Literal["box", "datalim"] | None = ...,
194
+ anchor: str | tuple[float, float] | None = ...,
195
+ share: bool = ...,
196
+ ) -> None: ...
197
+ def get_adjustable(self) -> Literal["box", "datalim"]: ...
198
+ def set_adjustable(
199
+ self, adjustable: Literal["box", "datalim"], share: bool = ...
200
+ ) -> None: ...
201
+ def get_box_aspect(self) -> float | None: ...
202
+ def set_box_aspect(self, aspect: float | None = ...) -> None: ...
203
+ def get_anchor(self) -> str | tuple[float, float]: ...
204
+ def set_anchor(
205
+ self, anchor: str | tuple[float, float], share: bool = ...
206
+ ) -> None: ...
207
+ def get_data_ratio(self) -> float: ...
208
+ def apply_aspect(self, position: Bbox | None = ...) -> None: ...
209
+ @overload
210
+ def axis(
211
+ self,
212
+ arg: tuple[float, float, float, float] | bool | str | None = ...,
213
+ /,
214
+ *,
215
+ emit: bool = ...
216
+ ) -> tuple[float, float, float, float]: ...
217
+ @overload
218
+ def axis(
219
+ self,
220
+ *,
221
+ emit: bool = ...,
222
+ xmin: float | None = ...,
223
+ xmax: float | None = ...,
224
+ ymin: float | None = ...,
225
+ ymax: float | None = ...
226
+ ) -> tuple[float, float, float, float]: ...
227
+ def get_legend(self) -> Legend: ...
228
+ def get_images(self) -> list[AxesImage]: ...
229
+ def get_lines(self) -> list[Line2D]: ...
230
+ def get_xaxis(self) -> XAxis: ...
231
+ def get_yaxis(self) -> YAxis: ...
232
+ def has_data(self) -> bool: ...
233
+ def add_artist(self, a: Artist) -> Artist: ...
234
+ def add_child_axes(self, ax: _AxesBase) -> _AxesBase: ...
235
+ def add_collection(
236
+ self, collection: Collection, autolim: bool = ...
237
+ ) -> Collection: ...
238
+ def add_image(self, image: AxesImage) -> AxesImage: ...
239
+ def add_line(self, line: Line2D) -> Line2D: ...
240
+ def add_patch(self, p: Patch) -> Patch: ...
241
+ def add_table(self, tab: Table) -> Table: ...
242
+ def add_container(self, container: Container) -> Container: ...
243
+ def relim(self, visible_only: bool = ...) -> None: ...
244
+ def update_datalim(
245
+ self, xys: ArrayLike, updatex: bool = ..., updatey: bool = ...
246
+ ) -> None: ...
247
+ def in_axes(self, mouseevent: MouseEvent) -> bool: ...
248
+ def get_autoscale_on(self) -> bool: ...
249
+ def set_autoscale_on(self, b: bool) -> None: ...
250
+ @property
251
+ def use_sticky_edges(self) -> bool: ...
252
+ @use_sticky_edges.setter
253
+ def use_sticky_edges(self, b: bool) -> None: ...
254
+ def get_xmargin(self) -> float: ...
255
+ def get_ymargin(self) -> float: ...
256
+ def set_xmargin(self, m: float) -> None: ...
257
+ def set_ymargin(self, m: float) -> None: ...
258
+
259
+ # Probably could be made better with overloads
260
+ def margins(
261
+ self,
262
+ *margins: float,
263
+ x: float | None = ...,
264
+ y: float | None = ...,
265
+ tight: bool | None = ...
266
+ ) -> tuple[float, float] | None: ...
267
+ def set_rasterization_zorder(self, z: float | None) -> None: ...
268
+ def get_rasterization_zorder(self) -> float | None: ...
269
+ def autoscale(
270
+ self,
271
+ enable: bool = ...,
272
+ axis: Literal["both", "x", "y"] = ...,
273
+ tight: bool | None = ...,
274
+ ) -> None: ...
275
+ def autoscale_view(
276
+ self, tight: bool | None = ..., scalex: bool = ..., scaley: bool = ...
277
+ ) -> None: ...
278
+ def draw_artist(self, a: Artist) -> None: ...
279
+ def redraw_in_frame(self) -> None: ...
280
+ def get_frame_on(self) -> bool: ...
281
+ def set_frame_on(self, b: bool) -> None: ...
282
+ def get_axisbelow(self) -> bool | Literal["line"]: ...
283
+ def set_axisbelow(self, b: bool | Literal["line"]) -> None: ...
284
+ def grid(
285
+ self,
286
+ visible: bool | None = ...,
287
+ which: Literal["major", "minor", "both"] = ...,
288
+ axis: Literal["both", "x", "y"] = ...,
289
+ **kwargs
290
+ ) -> None: ...
291
+ def ticklabel_format(
292
+ self,
293
+ *,
294
+ axis: Literal["both", "x", "y"] = ...,
295
+ style: Literal["", "sci", "scientific", "plain"] | None = ...,
296
+ scilimits: tuple[int, int] | None = ...,
297
+ useOffset: bool | float | None = ...,
298
+ useLocale: bool | None = ...,
299
+ useMathText: bool | None = ...
300
+ ) -> None: ...
301
+ def locator_params(
302
+ self, axis: Literal["both", "x", "y"] = ..., tight: bool | None = ..., **kwargs
303
+ ) -> None: ...
304
+ def tick_params(self, axis: Literal["both", "x", "y"] = ..., **kwargs) -> None: ...
305
+ def set_axis_off(self) -> None: ...
306
+ def set_axis_on(self) -> None: ...
307
+ def get_xlabel(self) -> str: ...
308
+ def set_xlabel(
309
+ self,
310
+ xlabel: str,
311
+ fontdict: dict[str, Any] | None = ...,
312
+ labelpad: float | None = ...,
313
+ *,
314
+ loc: Literal["left", "center", "right"] | None = ...,
315
+ **kwargs
316
+ ) -> Text: ...
317
+ def invert_xaxis(self) -> None: ...
318
+ def get_xbound(self) -> tuple[float, float]: ...
319
+ def set_xbound(
320
+ self, lower: float | None = ..., upper: float | None = ...
321
+ ) -> None: ...
322
+ def get_xlim(self) -> tuple[float, float]: ...
323
+ def set_xlim(
324
+ self,
325
+ left: float | tuple[float, float] | None = ...,
326
+ right: float | None = ...,
327
+ *,
328
+ emit: bool = ...,
329
+ auto: bool | None = ...,
330
+ xmin: float | None = ...,
331
+ xmax: float | None = ...
332
+ ) -> tuple[float, float]: ...
333
+ def get_ylabel(self) -> str: ...
334
+ def set_ylabel(
335
+ self,
336
+ ylabel: str,
337
+ fontdict: dict[str, Any] | None = ...,
338
+ labelpad: float | None = ...,
339
+ *,
340
+ loc: Literal["bottom", "center", "top"] | None = ...,
341
+ **kwargs
342
+ ) -> Text: ...
343
+ def invert_yaxis(self) -> None: ...
344
+ def get_ybound(self) -> tuple[float, float]: ...
345
+ def set_ybound(
346
+ self, lower: float | None = ..., upper: float | None = ...
347
+ ) -> None: ...
348
+ def get_ylim(self) -> tuple[float, float]: ...
349
+ def set_ylim(
350
+ self,
351
+ bottom: float | tuple[float, float] | None = ...,
352
+ top: float | None = ...,
353
+ *,
354
+ emit: bool = ...,
355
+ auto: bool | None = ...,
356
+ ymin: float | None = ...,
357
+ ymax: float | None = ...
358
+ ) -> tuple[float, float]: ...
359
+ def format_xdata(self, x: float) -> str: ...
360
+ def format_ydata(self, y: float) -> str: ...
361
+ def format_coord(self, x: float, y: float) -> str: ...
362
+ def minorticks_on(self) -> None: ...
363
+ def minorticks_off(self) -> None: ...
364
+ def can_zoom(self) -> bool: ...
365
+ def can_pan(self) -> bool: ...
366
+ def get_navigate(self) -> bool: ...
367
+ def set_navigate(self, b: bool) -> None: ...
368
+ def get_forward_navigation_events(self) -> bool | Literal["auto"]: ...
369
+ def set_forward_navigation_events(self, forward: bool | Literal["auto"]) -> None: ...
370
+ def get_navigate_mode(self) -> Literal["PAN", "ZOOM"] | None: ...
371
+ def set_navigate_mode(self, b: Literal["PAN", "ZOOM"] | None) -> None: ...
372
+ def start_pan(self, x: float, y: float, button: MouseButton) -> None: ...
373
+ def end_pan(self) -> None: ...
374
+ def drag_pan(
375
+ self, button: MouseButton, key: str | None, x: float, y: float
376
+ ) -> None: ...
377
+ def get_children(self) -> list[Artist]: ...
378
+ def contains_point(self, point: tuple[int, int]) -> bool: ...
379
+ def get_default_bbox_extra_artists(self) -> list[Artist]: ...
380
+ def get_tightbbox(
381
+ self,
382
+ renderer: RendererBase | None = ...,
383
+ *,
384
+ call_axes_locator: bool = ...,
385
+ bbox_extra_artists: Sequence[Artist] | None = ...,
386
+ for_layout_only: bool = ...
387
+ ) -> Bbox | None: ...
388
+ def twinx(self) -> Axes: ...
389
+ def twiny(self) -> Axes: ...
390
+ def get_shared_x_axes(self) -> cbook.GrouperView: ...
391
+ def get_shared_y_axes(self) -> cbook.GrouperView: ...
392
+ def label_outer(self, remove_inner_ticks: bool = ...) -> None: ...
393
+
394
+ # The methods underneath this line are added via the `_axis_method_wrapper` class
395
+ # Initially they are set to an object, but that object uses `__set_name__` to override
396
+ # itself with a method modified from the Axis methods for the x or y Axis.
397
+ # As such, they are typed according to the resultant method rather than as that object.
398
+
399
+ def get_xgridlines(self) -> list[Line2D]: ...
400
+ def get_xticklines(self, minor: bool = ...) -> list[Line2D]: ...
401
+ def get_ygridlines(self) -> list[Line2D]: ...
402
+ def get_yticklines(self, minor: bool = ...) -> list[Line2D]: ...
403
+ def _sci(self, im: ScalarMappable) -> None: ...
404
+ def get_autoscalex_on(self) -> bool: ...
405
+ def get_autoscaley_on(self) -> bool: ...
406
+ def set_autoscalex_on(self, b: bool) -> None: ...
407
+ def set_autoscaley_on(self, b: bool) -> None: ...
408
+ def xaxis_inverted(self) -> bool: ...
409
+ def get_xscale(self) -> str: ...
410
+ def set_xscale(self, value: str | ScaleBase, **kwargs) -> None: ...
411
+ def get_xticks(self, *, minor: bool = ...) -> np.ndarray: ...
412
+ def set_xticks(
413
+ self,
414
+ ticks: ArrayLike,
415
+ labels: Iterable[str] | None = ...,
416
+ *,
417
+ minor: bool = ...,
418
+ **kwargs
419
+ ) -> list[Tick]: ...
420
+ def get_xmajorticklabels(self) -> list[Text]: ...
421
+ def get_xminorticklabels(self) -> list[Text]: ...
422
+ def get_xticklabels(
423
+ self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
424
+ ) -> list[Text]: ...
425
+ def set_xticklabels(
426
+ self,
427
+ labels: Iterable[str | Text],
428
+ *,
429
+ minor: bool = ...,
430
+ fontdict: dict[str, Any] | None = ...,
431
+ **kwargs
432
+ ) -> list[Text]: ...
433
+ def yaxis_inverted(self) -> bool: ...
434
+ def get_yscale(self) -> str: ...
435
+ def set_yscale(self, value: str | ScaleBase, **kwargs) -> None: ...
436
+ def get_yticks(self, *, minor: bool = ...) -> np.ndarray: ...
437
+ def set_yticks(
438
+ self,
439
+ ticks: ArrayLike,
440
+ labels: Iterable[str] | None = ...,
441
+ *,
442
+ minor: bool = ...,
443
+ **kwargs
444
+ ) -> list[Tick]: ...
445
+ def get_ymajorticklabels(self) -> list[Text]: ...
446
+ def get_yminorticklabels(self) -> list[Text]: ...
447
+ def get_yticklabels(
448
+ self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
449
+ ) -> list[Text]: ...
450
+ def set_yticklabels(
451
+ self,
452
+ labels: Iterable[str | Text],
453
+ *,
454
+ minor: bool = ...,
455
+ fontdict: dict[str, Any] | None = ...,
456
+ **kwargs
457
+ ) -> list[Text]: ...
458
+ def xaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
459
+ def yaxis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers
2
+
3
+ import numpy as np
4
+
5
+ from matplotlib import _api, _docstring, transforms
6
+ import matplotlib.ticker as mticker
7
+ from matplotlib.axes._base import _AxesBase, _TransformedBoundsLocator
8
+ from matplotlib.axis import Axis
9
+ from matplotlib.transforms import Transform
10
+
11
+
12
+ class SecondaryAxis(_AxesBase):
13
+ """
14
+ General class to hold a Secondary_X/Yaxis.
15
+ """
16
+
17
+ def __init__(self, parent, orientation, location, functions, transform=None,
18
+ **kwargs):
19
+ """
20
+ See `.secondary_xaxis` and `.secondary_yaxis` for the doc string.
21
+ While there is no need for this to be private, it should really be
22
+ called by those higher level functions.
23
+ """
24
+ _api.check_in_list(["x", "y"], orientation=orientation)
25
+ self._functions = functions
26
+ self._parent = parent
27
+ self._orientation = orientation
28
+ self._ticks_set = False
29
+
30
+ if self._orientation == 'x':
31
+ super().__init__(self._parent.figure, [0, 1., 1, 0.0001], **kwargs)
32
+ self._axis = self.xaxis
33
+ self._locstrings = ['top', 'bottom']
34
+ self._otherstrings = ['left', 'right']
35
+ else: # 'y'
36
+ super().__init__(self._parent.figure, [0, 1., 0.0001, 1], **kwargs)
37
+ self._axis = self.yaxis
38
+ self._locstrings = ['right', 'left']
39
+ self._otherstrings = ['top', 'bottom']
40
+ self._parentscale = None
41
+ # this gets positioned w/o constrained_layout so exclude:
42
+
43
+ self.set_location(location, transform)
44
+ self.set_functions(functions)
45
+
46
+ # styling:
47
+ otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis
48
+ otheraxis.set_major_locator(mticker.NullLocator())
49
+ otheraxis.set_ticks_position('none')
50
+
51
+ self.spines[self._otherstrings].set_visible(False)
52
+ self.spines[self._locstrings].set_visible(True)
53
+
54
+ if self._pos < 0.5:
55
+ # flip the location strings...
56
+ self._locstrings = self._locstrings[::-1]
57
+ self.set_alignment(self._locstrings[0])
58
+
59
+ def set_alignment(self, align):
60
+ """
61
+ Set if axes spine and labels are drawn at top or bottom (or left/right)
62
+ of the Axes.
63
+
64
+ Parameters
65
+ ----------
66
+ align : {'top', 'bottom', 'left', 'right'}
67
+ Either 'top' or 'bottom' for orientation='x' or
68
+ 'left' or 'right' for orientation='y' axis.
69
+ """
70
+ _api.check_in_list(self._locstrings, align=align)
71
+ if align == self._locstrings[1]: # Need to change the orientation.
72
+ self._locstrings = self._locstrings[::-1]
73
+ self.spines[self._locstrings[0]].set_visible(True)
74
+ self.spines[self._locstrings[1]].set_visible(False)
75
+ self._axis.set_ticks_position(align)
76
+ self._axis.set_label_position(align)
77
+
78
+ def set_location(self, location, transform=None):
79
+ """
80
+ Set the vertical or horizontal location of the axes in
81
+ parent-normalized coordinates.
82
+
83
+ Parameters
84
+ ----------
85
+ location : {'top', 'bottom', 'left', 'right'} or float
86
+ The position to put the secondary axis. Strings can be 'top' or
87
+ 'bottom' for orientation='x' and 'right' or 'left' for
88
+ orientation='y'. A float indicates the relative position on the
89
+ parent Axes to put the new Axes, 0.0 being the bottom (or left)
90
+ and 1.0 being the top (or right).
91
+
92
+ transform : `.Transform`, optional
93
+ Transform for the location to use. Defaults to
94
+ the parent's ``transAxes``, so locations are normally relative to
95
+ the parent axes.
96
+
97
+ .. versionadded:: 3.9
98
+ """
99
+
100
+ _api.check_isinstance((transforms.Transform, None), transform=transform)
101
+
102
+ # This puts the rectangle into figure-relative coordinates.
103
+ if isinstance(location, str):
104
+ _api.check_in_list(self._locstrings, location=location)
105
+ self._pos = 1. if location in ('top', 'right') else 0.
106
+ elif isinstance(location, numbers.Real):
107
+ self._pos = location
108
+ else:
109
+ raise ValueError(
110
+ f"location must be {self._locstrings[0]!r}, "
111
+ f"{self._locstrings[1]!r}, or a float, not {location!r}")
112
+
113
+ self._loc = location
114
+
115
+ if self._orientation == 'x':
116
+ # An x-secondary axes is like an inset axes from x = 0 to x = 1 and
117
+ # from y = pos to y = pos + eps, in the parent's transAxes coords.
118
+ bounds = [0, self._pos, 1., 1e-10]
119
+
120
+ # If a transformation is provided, use its y component rather than
121
+ # the parent's transAxes. This can be used to place axes in the data
122
+ # coords, for instance.
123
+ if transform is not None:
124
+ transform = transforms.blended_transform_factory(
125
+ self._parent.transAxes, transform)
126
+ else: # 'y'
127
+ bounds = [self._pos, 0, 1e-10, 1]
128
+ if transform is not None:
129
+ transform = transforms.blended_transform_factory(
130
+ transform, self._parent.transAxes) # Use provided x axis
131
+
132
+ # If no transform is provided, use the parent's transAxes
133
+ if transform is None:
134
+ transform = self._parent.transAxes
135
+
136
+ # this locator lets the axes move in the parent axes coordinates.
137
+ # so it never needs to know where the parent is explicitly in
138
+ # figure coordinates.
139
+ # it gets called in ax.apply_aspect() (of all places)
140
+ self.set_axes_locator(_TransformedBoundsLocator(bounds, transform))
141
+
142
+ def apply_aspect(self, position=None):
143
+ # docstring inherited.
144
+ self._set_lims()
145
+ super().apply_aspect(position)
146
+
147
+ @_docstring.copy(Axis.set_ticks)
148
+ def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
149
+ ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs)
150
+ self.stale = True
151
+ self._ticks_set = True
152
+ return ret
153
+
154
+ def set_functions(self, functions):
155
+ """
156
+ Set how the secondary axis converts limits from the parent Axes.
157
+
158
+ Parameters
159
+ ----------
160
+ functions : 2-tuple of func, or `Transform` with an inverse.
161
+ Transform between the parent axis values and the secondary axis
162
+ values.
163
+
164
+ If supplied as a 2-tuple of functions, the first function is
165
+ the forward transform function and the second is the inverse
166
+ transform.
167
+
168
+ If a transform is supplied, then the transform must have an
169
+ inverse.
170
+ """
171
+
172
+ if (isinstance(functions, tuple) and len(functions) == 2 and
173
+ callable(functions[0]) and callable(functions[1])):
174
+ # make an arbitrary convert from a two-tuple of functions
175
+ # forward and inverse.
176
+ self._functions = functions
177
+ elif isinstance(functions, Transform):
178
+ self._functions = (
179
+ functions.transform,
180
+ lambda x: functions.inverted().transform(x)
181
+ )
182
+ elif functions is None:
183
+ self._functions = (lambda x: x, lambda x: x)
184
+ else:
185
+ raise ValueError('functions argument of secondary Axes '
186
+ 'must be a two-tuple of callable functions '
187
+ 'with the first function being the transform '
188
+ 'and the second being the inverse')
189
+ self._set_scale()
190
+
191
+ def draw(self, renderer):
192
+ """
193
+ Draw the secondary Axes.
194
+
195
+ Consults the parent Axes for its limits and converts them
196
+ using the converter specified by
197
+ `~.axes._secondary_axes.set_functions` (or *functions*
198
+ parameter when Axes initialized.)
199
+ """
200
+ self._set_lims()
201
+ # this sets the scale in case the parent has set its scale.
202
+ self._set_scale()
203
+ super().draw(renderer)
204
+
205
+ def _set_scale(self):
206
+ """
207
+ Check if parent has set its scale
208
+ """
209
+
210
+ if self._orientation == 'x':
211
+ pscale = self._parent.xaxis.get_scale()
212
+ set_scale = self.set_xscale
213
+ else: # 'y'
214
+ pscale = self._parent.yaxis.get_scale()
215
+ set_scale = self.set_yscale
216
+ if pscale == self._parentscale:
217
+ return
218
+
219
+ if self._ticks_set:
220
+ ticks = self._axis.get_ticklocs()
221
+
222
+ # need to invert the roles here for the ticks to line up.
223
+ set_scale('functionlog' if pscale == 'log' else 'function',
224
+ functions=self._functions[::-1])
225
+
226
+ # OK, set_scale sets the locators, but if we've called
227
+ # axsecond.set_ticks, we want to keep those.
228
+ if self._ticks_set:
229
+ self._axis.set_major_locator(mticker.FixedLocator(ticks))
230
+
231
+ # If the parent scale doesn't change, we can skip this next time.
232
+ self._parentscale = pscale
233
+
234
+ def _set_lims(self):
235
+ """
236
+ Set the limits based on parent limits and the convert method
237
+ between the parent and this secondary Axes.
238
+ """
239
+ if self._orientation == 'x':
240
+ lims = self._parent.get_xlim()
241
+ set_lim = self.set_xlim
242
+ else: # 'y'
243
+ lims = self._parent.get_ylim()
244
+ set_lim = self.set_ylim
245
+ order = lims[0] < lims[1]
246
+ lims = self._functions[0](np.array(lims))
247
+ neworder = lims[0] < lims[1]
248
+ if neworder != order:
249
+ # Flip because the transform will take care of the flipping.
250
+ lims = lims[::-1]
251
+ set_lim(lims)
252
+
253
+ def set_aspect(self, *args, **kwargs):
254
+ """
255
+ Secondary Axes cannot set the aspect ratio, so calling this just
256
+ sets a warning.
257
+ """
258
+ _api.warn_external("Secondary Axes can't set the aspect ratio")
259
+
260
+ def set_color(self, color):
261
+ """
262
+ Change the color of the secondary Axes and all decorators.
263
+
264
+ Parameters
265
+ ----------
266
+ color : :mpltype:`color`
267
+ """
268
+ axis = self._axis_map[self._orientation]
269
+ axis.set_tick_params(colors=color)
270
+ for spine in self.spines.values():
271
+ if spine.axis is axis:
272
+ spine.set_color(color)
273
+ axis.label.set_color(color)
274
+
275
+
276
+ _secax_docstring = '''
277
+ Warnings
278
+ --------
279
+ This method is experimental as of 3.1, and the API may change.
280
+
281
+ Parameters
282
+ ----------
283
+ location : {'top', 'bottom', 'left', 'right'} or float
284
+ The position to put the secondary axis. Strings can be 'top' or
285
+ 'bottom' for orientation='x' and 'right' or 'left' for
286
+ orientation='y'. A float indicates the relative position on the
287
+ parent Axes to put the new Axes, 0.0 being the bottom (or left)
288
+ and 1.0 being the top (or right).
289
+
290
+ functions : 2-tuple of func, or Transform with an inverse
291
+
292
+ If a 2-tuple of functions, the user specifies the transform
293
+ function and its inverse. i.e.
294
+ ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an
295
+ reciprocal transform with a factor of 2. Both functions must accept
296
+ numpy arrays as input.
297
+
298
+ The user can also directly supply a subclass of
299
+ `.transforms.Transform` so long as it has an inverse.
300
+
301
+ See :doc:`/gallery/subplots_axes_and_figures/secondary_axis`
302
+ for examples of making these conversions.
303
+
304
+ transform : `.Transform`, optional
305
+ If specified, *location* will be
306
+ placed relative to this transform (in the direction of the axis)
307
+ rather than the parent's axis. i.e. a secondary x-axis will
308
+ use the provided y transform and the x transform of the parent.
309
+
310
+ .. versionadded:: 3.9
311
+
312
+ Returns
313
+ -------
314
+ ax : axes._secondary_axes.SecondaryAxis
315
+
316
+ Other Parameters
317
+ ----------------
318
+ **kwargs : `~matplotlib.axes.Axes` properties.
319
+ Other miscellaneous Axes parameters.
320
+ '''
321
+ _docstring.interpd.update(_secax_docstring=_secax_docstring)
parrot/lib/python3.10/site-packages/matplotlib/axes/_secondary_axes.pyi ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.axes._base import _AxesBase
2
+ from matplotlib.axis import Tick
3
+
4
+ from matplotlib.transforms import Transform
5
+
6
+ from collections.abc import Callable, Iterable
7
+ from typing import Literal
8
+ from numpy.typing import ArrayLike
9
+ from matplotlib.typing import ColorType
10
+
11
+ class SecondaryAxis(_AxesBase):
12
+ def __init__(
13
+ self,
14
+ parent: _AxesBase,
15
+ orientation: Literal["x", "y"],
16
+ location: Literal["top", "bottom", "right", "left"] | float,
17
+ functions: tuple[
18
+ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
19
+ ]
20
+ | Transform,
21
+ transform: Transform | None = ...,
22
+ **kwargs
23
+ ) -> None: ...
24
+ def set_alignment(
25
+ self, align: Literal["top", "bottom", "right", "left"]
26
+ ) -> None: ...
27
+ def set_location(
28
+ self,
29
+ location: Literal["top", "bottom", "right", "left"] | float,
30
+ transform: Transform | None = ...
31
+ ) -> None: ...
32
+ def set_ticks(
33
+ self,
34
+ ticks: ArrayLike,
35
+ labels: Iterable[str] | None = ...,
36
+ *,
37
+ minor: bool = ...,
38
+ **kwargs
39
+ ) -> list[Tick]: ...
40
+ def set_functions(
41
+ self,
42
+ functions: tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] | Transform,
43
+ ) -> None: ...
44
+ def set_aspect(self, *args, **kwargs) -> None: ...
45
+ def set_color(self, color: ColorType) -> None: ...
parrot/lib/python3.10/site-packages/matplotlib/backends/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .registry import BackendFilter, backend_registry # noqa: F401
2
+
3
+ # NOTE: plt.switch_backend() (called at import time) will add a "backend"
4
+ # attribute here for backcompat.
5
+ _QT_FORCE_QT5_BINDING = False
parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_agg.pyi ADDED
File without changes
parrot/lib/python3.10/site-packages/matplotlib/backends/_backend_pdf_ps.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common functionality between the PDF and PS backends.
3
+ """
4
+
5
+ from io import BytesIO
6
+ import functools
7
+
8
+ from fontTools import subset
9
+
10
+ import matplotlib as mpl
11
+ from .. import font_manager, ft2font
12
+ from .._afm import AFM
13
+ from ..backend_bases import RendererBase
14
+
15
+
16
+ @functools.lru_cache(50)
17
+ def _cached_get_afm_from_fname(fname):
18
+ with open(fname, "rb") as fh:
19
+ return AFM(fh)
20
+
21
+
22
+ def get_glyphs_subset(fontfile, characters):
23
+ """
24
+ Subset a TTF font
25
+
26
+ Reads the named fontfile and restricts the font to the characters.
27
+ Returns a serialization of the subset font as file-like object.
28
+
29
+ Parameters
30
+ ----------
31
+ fontfile : str
32
+ Path to the font file
33
+ characters : str
34
+ Continuous set of characters to include in subset
35
+ """
36
+
37
+ options = subset.Options(glyph_names=True, recommended_glyphs=True)
38
+
39
+ # Prevent subsetting extra tables.
40
+ options.drop_tables += [
41
+ 'FFTM', # FontForge Timestamp.
42
+ 'PfEd', # FontForge personal table.
43
+ 'BDF', # X11 BDF header.
44
+ 'meta', # Metadata stores design/supported languages (meaningless for subsets).
45
+ ]
46
+
47
+ # if fontfile is a ttc, specify font number
48
+ if fontfile.endswith(".ttc"):
49
+ options.font_number = 0
50
+
51
+ with subset.load_font(fontfile, options) as font:
52
+ subsetter = subset.Subsetter(options=options)
53
+ subsetter.populate(text=characters)
54
+ subsetter.subset(font)
55
+ fh = BytesIO()
56
+ font.save(fh, reorderTables=False)
57
+ return fh
58
+
59
+
60
+ class CharacterTracker:
61
+ """
62
+ Helper for font subsetting by the pdf and ps backends.
63
+
64
+ Maintains a mapping of font paths to the set of character codepoints that
65
+ are being used from that font.
66
+ """
67
+
68
+ def __init__(self):
69
+ self.used = {}
70
+
71
+ def track(self, font, s):
72
+ """Record that string *s* is being typeset using font *font*."""
73
+ char_to_font = font._get_fontmap(s)
74
+ for _c, _f in char_to_font.items():
75
+ self.used.setdefault(_f.fname, set()).add(ord(_c))
76
+
77
+ def track_glyph(self, font, glyph):
78
+ """Record that codepoint *glyph* is being typeset using font *font*."""
79
+ self.used.setdefault(font.fname, set()).add(glyph)
80
+
81
+
82
+ class RendererPDFPSBase(RendererBase):
83
+ # The following attributes must be defined by the subclasses:
84
+ # - _afm_font_dir
85
+ # - _use_afm_rc_name
86
+
87
+ def __init__(self, width, height):
88
+ super().__init__()
89
+ self.width = width
90
+ self.height = height
91
+
92
+ def flipy(self):
93
+ # docstring inherited
94
+ return False # y increases from bottom to top.
95
+
96
+ def option_scale_image(self):
97
+ # docstring inherited
98
+ return True # PDF and PS support arbitrary image scaling.
99
+
100
+ def option_image_nocomposite(self):
101
+ # docstring inherited
102
+ # Decide whether to composite image based on rcParam value.
103
+ return not mpl.rcParams["image.composite_image"]
104
+
105
+ def get_canvas_width_height(self):
106
+ # docstring inherited
107
+ return self.width * 72.0, self.height * 72.0
108
+
109
+ def get_text_width_height_descent(self, s, prop, ismath):
110
+ # docstring inherited
111
+ if ismath == "TeX":
112
+ return super().get_text_width_height_descent(s, prop, ismath)
113
+ elif ismath:
114
+ parse = self._text2path.mathtext_parser.parse(s, 72, prop)
115
+ return parse.width, parse.height, parse.depth
116
+ elif mpl.rcParams[self._use_afm_rc_name]:
117
+ font = self._get_font_afm(prop)
118
+ l, b, w, h, d = font.get_str_bbox_and_descent(s)
119
+ scale = prop.get_size_in_points() / 1000
120
+ w *= scale
121
+ h *= scale
122
+ d *= scale
123
+ return w, h, d
124
+ else:
125
+ font = self._get_font_ttf(prop)
126
+ font.set_text(s, 0.0, flags=ft2font.LOAD_NO_HINTING)
127
+ w, h = font.get_width_height()
128
+ d = font.get_descent()
129
+ scale = 1 / 64
130
+ w *= scale
131
+ h *= scale
132
+ d *= scale
133
+ return w, h, d
134
+
135
+ def _get_font_afm(self, prop):
136
+ fname = font_manager.findfont(
137
+ prop, fontext="afm", directory=self._afm_font_dir)
138
+ return _cached_get_afm_from_fname(fname)
139
+
140
+ def _get_font_ttf(self, prop):
141
+ fnames = font_manager.fontManager._find_fonts_by_props(prop)
142
+ font = font_manager.get_font(fnames)
143
+ font.clear()
144
+ font.set_size(prop.get_size_in_points(), 72)
145
+ return font
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import matplotlib as mpl
7
+ from matplotlib import _api, backend_tools, cbook
8
+ from matplotlib.backend_bases import (
9
+ ToolContainerBase, CloseEvent, KeyEvent, LocationEvent, MouseEvent,
10
+ ResizeEvent)
11
+
12
+ try:
13
+ import gi
14
+ except ImportError as err:
15
+ raise ImportError("The GTK3 backends require PyGObject") from err
16
+
17
+ try:
18
+ # :raises ValueError: If module/version is already loaded, already
19
+ # required, or unavailable.
20
+ gi.require_version("Gtk", "3.0")
21
+ except ValueError as e:
22
+ # in this case we want to re-raise as ImportError so the
23
+ # auto-backend selection logic correctly skips.
24
+ raise ImportError(e) from e
25
+
26
+ from gi.repository import Gio, GLib, GObject, Gtk, Gdk
27
+ from . import _backend_gtk
28
+ from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
29
+ _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
30
+ TimerGTK as TimerGTK3,
31
+ )
32
+
33
+
34
+ _log = logging.getLogger(__name__)
35
+
36
+
37
+ @functools.cache
38
+ def _mpl_to_gtk_cursor(mpl_cursor):
39
+ return Gdk.Cursor.new_from_name(
40
+ Gdk.Display.get_default(),
41
+ _backend_gtk.mpl_to_gtk_cursor_name(mpl_cursor))
42
+
43
+
44
+ class FigureCanvasGTK3(_FigureCanvasGTK, Gtk.DrawingArea):
45
+ required_interactive_framework = "gtk3"
46
+ manager_class = _api.classproperty(lambda cls: FigureManagerGTK3)
47
+ # Setting this as a static constant prevents
48
+ # this resulting expression from leaking
49
+ event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK
50
+ | Gdk.EventMask.BUTTON_RELEASE_MASK
51
+ | Gdk.EventMask.EXPOSURE_MASK
52
+ | Gdk.EventMask.KEY_PRESS_MASK
53
+ | Gdk.EventMask.KEY_RELEASE_MASK
54
+ | Gdk.EventMask.ENTER_NOTIFY_MASK
55
+ | Gdk.EventMask.LEAVE_NOTIFY_MASK
56
+ | Gdk.EventMask.POINTER_MOTION_MASK
57
+ | Gdk.EventMask.SCROLL_MASK)
58
+
59
+ def __init__(self, figure=None):
60
+ super().__init__(figure=figure)
61
+
62
+ self._idle_draw_id = 0
63
+ self._rubberband_rect = None
64
+
65
+ self.connect('scroll_event', self.scroll_event)
66
+ self.connect('button_press_event', self.button_press_event)
67
+ self.connect('button_release_event', self.button_release_event)
68
+ self.connect('configure_event', self.configure_event)
69
+ self.connect('screen-changed', self._update_device_pixel_ratio)
70
+ self.connect('notify::scale-factor', self._update_device_pixel_ratio)
71
+ self.connect('draw', self.on_draw_event)
72
+ self.connect('draw', self._post_draw)
73
+ self.connect('key_press_event', self.key_press_event)
74
+ self.connect('key_release_event', self.key_release_event)
75
+ self.connect('motion_notify_event', self.motion_notify_event)
76
+ self.connect('enter_notify_event', self.enter_notify_event)
77
+ self.connect('leave_notify_event', self.leave_notify_event)
78
+ self.connect('size_allocate', self.size_allocate)
79
+
80
+ self.set_events(self.__class__.event_mask)
81
+
82
+ self.set_can_focus(True)
83
+
84
+ css = Gtk.CssProvider()
85
+ css.load_from_data(b".matplotlib-canvas { background-color: white; }")
86
+ style_ctx = self.get_style_context()
87
+ style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
88
+ style_ctx.add_class("matplotlib-canvas")
89
+
90
+ def destroy(self):
91
+ CloseEvent("close_event", self)._process()
92
+
93
+ def set_cursor(self, cursor):
94
+ # docstring inherited
95
+ window = self.get_property("window")
96
+ if window is not None:
97
+ window.set_cursor(_mpl_to_gtk_cursor(cursor))
98
+ context = GLib.MainContext.default()
99
+ context.iteration(True)
100
+
101
+ def _mpl_coords(self, event=None):
102
+ """
103
+ Convert the position of a GTK event, or of the current cursor position
104
+ if *event* is None, to Matplotlib coordinates.
105
+
106
+ GTK use logical pixels, but the figure is scaled to physical pixels for
107
+ rendering. Transform to physical pixels so that all of the down-stream
108
+ transforms work as expected.
109
+
110
+ Also, the origin is different and needs to be corrected.
111
+ """
112
+ if event is None:
113
+ window = self.get_window()
114
+ t, x, y, state = window.get_device_position(
115
+ window.get_display().get_device_manager().get_client_pointer())
116
+ else:
117
+ x, y = event.x, event.y
118
+ x = x * self.device_pixel_ratio
119
+ # flip y so y=0 is bottom of canvas
120
+ y = self.figure.bbox.height - y * self.device_pixel_ratio
121
+ return x, y
122
+
123
+ def scroll_event(self, widget, event):
124
+ step = 1 if event.direction == Gdk.ScrollDirection.UP else -1
125
+ MouseEvent("scroll_event", self,
126
+ *self._mpl_coords(event), step=step,
127
+ modifiers=self._mpl_modifiers(event.state),
128
+ guiEvent=event)._process()
129
+ return False # finish event propagation?
130
+
131
+ def button_press_event(self, widget, event):
132
+ MouseEvent("button_press_event", self,
133
+ *self._mpl_coords(event), event.button,
134
+ modifiers=self._mpl_modifiers(event.state),
135
+ guiEvent=event)._process()
136
+ return False # finish event propagation?
137
+
138
+ def button_release_event(self, widget, event):
139
+ MouseEvent("button_release_event", self,
140
+ *self._mpl_coords(event), event.button,
141
+ modifiers=self._mpl_modifiers(event.state),
142
+ guiEvent=event)._process()
143
+ return False # finish event propagation?
144
+
145
+ def key_press_event(self, widget, event):
146
+ KeyEvent("key_press_event", self,
147
+ self._get_key(event), *self._mpl_coords(),
148
+ guiEvent=event)._process()
149
+ return True # stop event propagation
150
+
151
+ def key_release_event(self, widget, event):
152
+ KeyEvent("key_release_event", self,
153
+ self._get_key(event), *self._mpl_coords(),
154
+ guiEvent=event)._process()
155
+ return True # stop event propagation
156
+
157
+ def motion_notify_event(self, widget, event):
158
+ MouseEvent("motion_notify_event", self, *self._mpl_coords(event),
159
+ modifiers=self._mpl_modifiers(event.state),
160
+ guiEvent=event)._process()
161
+ return False # finish event propagation?
162
+
163
+ def enter_notify_event(self, widget, event):
164
+ gtk_mods = Gdk.Keymap.get_for_display(
165
+ self.get_display()).get_modifier_state()
166
+ LocationEvent("figure_enter_event", self, *self._mpl_coords(event),
167
+ modifiers=self._mpl_modifiers(gtk_mods),
168
+ guiEvent=event)._process()
169
+
170
+ def leave_notify_event(self, widget, event):
171
+ gtk_mods = Gdk.Keymap.get_for_display(
172
+ self.get_display()).get_modifier_state()
173
+ LocationEvent("figure_leave_event", self, *self._mpl_coords(event),
174
+ modifiers=self._mpl_modifiers(gtk_mods),
175
+ guiEvent=event)._process()
176
+
177
+ def size_allocate(self, widget, allocation):
178
+ dpival = self.figure.dpi
179
+ winch = allocation.width * self.device_pixel_ratio / dpival
180
+ hinch = allocation.height * self.device_pixel_ratio / dpival
181
+ self.figure.set_size_inches(winch, hinch, forward=False)
182
+ ResizeEvent("resize_event", self)._process()
183
+ self.draw_idle()
184
+
185
+ @staticmethod
186
+ def _mpl_modifiers(event_state, *, exclude=None):
187
+ modifiers = [
188
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
189
+ ("alt", Gdk.ModifierType.MOD1_MASK, "alt"),
190
+ ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
191
+ ("super", Gdk.ModifierType.MOD4_MASK, "super"),
192
+ ]
193
+ return [name for name, mask, key in modifiers
194
+ if exclude != key and event_state & mask]
195
+
196
+ def _get_key(self, event):
197
+ unikey = chr(Gdk.keyval_to_unicode(event.keyval))
198
+ key = cbook._unikey_or_keysym_to_mplkey(
199
+ unikey, Gdk.keyval_name(event.keyval))
200
+ mods = self._mpl_modifiers(event.state, exclude=key)
201
+ if "shift" in mods and unikey.isprintable():
202
+ mods.remove("shift")
203
+ return "+".join([*mods, key])
204
+
205
+ def _update_device_pixel_ratio(self, *args, **kwargs):
206
+ # We need to be careful in cases with mixed resolution displays if
207
+ # device_pixel_ratio changes.
208
+ if self._set_device_pixel_ratio(self.get_scale_factor()):
209
+ # The easiest way to resize the canvas is to emit a resize event
210
+ # since we implement all the logic for resizing the canvas for that
211
+ # event.
212
+ self.queue_resize()
213
+ self.queue_draw()
214
+
215
+ def configure_event(self, widget, event):
216
+ if widget.get_property("window") is None:
217
+ return
218
+ w = event.width * self.device_pixel_ratio
219
+ h = event.height * self.device_pixel_ratio
220
+ if w < 3 or h < 3:
221
+ return # empty fig
222
+ # resize the figure (in inches)
223
+ dpi = self.figure.dpi
224
+ self.figure.set_size_inches(w / dpi, h / dpi, forward=False)
225
+ return False # finish event propagation?
226
+
227
+ def _draw_rubberband(self, rect):
228
+ self._rubberband_rect = rect
229
+ # TODO: Only update the rubberband area.
230
+ self.queue_draw()
231
+
232
+ def _post_draw(self, widget, ctx):
233
+ if self._rubberband_rect is None:
234
+ return
235
+
236
+ x0, y0, w, h = (dim / self.device_pixel_ratio
237
+ for dim in self._rubberband_rect)
238
+ x1 = x0 + w
239
+ y1 = y0 + h
240
+
241
+ # Draw the lines from x0, y0 towards x1, y1 so that the
242
+ # dashes don't "jump" when moving the zoom box.
243
+ ctx.move_to(x0, y0)
244
+ ctx.line_to(x0, y1)
245
+ ctx.move_to(x0, y0)
246
+ ctx.line_to(x1, y0)
247
+ ctx.move_to(x0, y1)
248
+ ctx.line_to(x1, y1)
249
+ ctx.move_to(x1, y0)
250
+ ctx.line_to(x1, y1)
251
+
252
+ ctx.set_antialias(1)
253
+ ctx.set_line_width(1)
254
+ ctx.set_dash((3, 3), 0)
255
+ ctx.set_source_rgb(0, 0, 0)
256
+ ctx.stroke_preserve()
257
+
258
+ ctx.set_dash((3, 3), 3)
259
+ ctx.set_source_rgb(1, 1, 1)
260
+ ctx.stroke()
261
+
262
+ def on_draw_event(self, widget, ctx):
263
+ # to be overwritten by GTK3Agg or GTK3Cairo
264
+ pass
265
+
266
+ def draw(self):
267
+ # docstring inherited
268
+ if self.is_drawable():
269
+ self.queue_draw()
270
+
271
+ def draw_idle(self):
272
+ # docstring inherited
273
+ if self._idle_draw_id != 0:
274
+ return
275
+ def idle_draw(*args):
276
+ try:
277
+ self.draw()
278
+ finally:
279
+ self._idle_draw_id = 0
280
+ return False
281
+ self._idle_draw_id = GLib.idle_add(idle_draw)
282
+
283
+ def flush_events(self):
284
+ # docstring inherited
285
+ context = GLib.MainContext.default()
286
+ while context.pending():
287
+ context.iteration(True)
288
+
289
+
290
+ class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar):
291
+ def __init__(self, canvas):
292
+ GObject.GObject.__init__(self)
293
+
294
+ self.set_style(Gtk.ToolbarStyle.ICONS)
295
+
296
+ self._gtk_ids = {}
297
+ for text, tooltip_text, image_file, callback in self.toolitems:
298
+ if text is None:
299
+ self.insert(Gtk.SeparatorToolItem(), -1)
300
+ continue
301
+ image = Gtk.Image.new_from_gicon(
302
+ Gio.Icon.new_for_string(
303
+ str(cbook._get_data_path('images',
304
+ f'{image_file}-symbolic.svg'))),
305
+ Gtk.IconSize.LARGE_TOOLBAR)
306
+ self._gtk_ids[text] = button = (
307
+ Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else
308
+ Gtk.ToolButton())
309
+ button.set_label(text)
310
+ button.set_icon_widget(image)
311
+ # Save the handler id, so that we can block it as needed.
312
+ button._signal_handler = button.connect(
313
+ 'clicked', getattr(self, callback))
314
+ button.set_tooltip_text(tooltip_text)
315
+ self.insert(button, -1)
316
+
317
+ # This filler item ensures the toolbar is always at least two text
318
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
319
+ # over images because those use two-line messages which resize the
320
+ # toolbar.
321
+ toolitem = Gtk.ToolItem()
322
+ self.insert(toolitem, -1)
323
+ label = Gtk.Label()
324
+ label.set_markup(
325
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
326
+ toolitem.set_expand(True) # Push real message to the right.
327
+ toolitem.add(label)
328
+
329
+ toolitem = Gtk.ToolItem()
330
+ self.insert(toolitem, -1)
331
+ self.message = Gtk.Label()
332
+ self.message.set_justify(Gtk.Justification.RIGHT)
333
+ toolitem.add(self.message)
334
+
335
+ self.show_all()
336
+
337
+ _NavigationToolbar2GTK.__init__(self, canvas)
338
+
339
+ def save_figure(self, *args):
340
+ dialog = Gtk.FileChooserDialog(
341
+ title="Save the figure",
342
+ parent=self.canvas.get_toplevel(),
343
+ action=Gtk.FileChooserAction.SAVE,
344
+ buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
345
+ Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
346
+ )
347
+ for name, fmts \
348
+ in self.canvas.get_supported_filetypes_grouped().items():
349
+ ff = Gtk.FileFilter()
350
+ ff.set_name(name)
351
+ for fmt in fmts:
352
+ ff.add_pattern(f'*.{fmt}')
353
+ dialog.add_filter(ff)
354
+ if self.canvas.get_default_filetype() in fmts:
355
+ dialog.set_filter(ff)
356
+
357
+ @functools.partial(dialog.connect, "notify::filter")
358
+ def on_notify_filter(*args):
359
+ name = dialog.get_filter().get_name()
360
+ fmt = self.canvas.get_supported_filetypes_grouped()[name][0]
361
+ dialog.set_current_name(
362
+ str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}')))
363
+
364
+ dialog.set_current_folder(mpl.rcParams["savefig.directory"])
365
+ dialog.set_current_name(self.canvas.get_default_filename())
366
+ dialog.set_do_overwrite_confirmation(True)
367
+
368
+ response = dialog.run()
369
+ fname = dialog.get_filename()
370
+ ff = dialog.get_filter() # Doesn't autoadjust to filename :/
371
+ fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0]
372
+ dialog.destroy()
373
+ if response != Gtk.ResponseType.OK:
374
+ return
375
+ # Save dir for next time, unless empty str (which means use cwd).
376
+ if mpl.rcParams['savefig.directory']:
377
+ mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
378
+ try:
379
+ self.canvas.figure.savefig(fname, format=fmt)
380
+ except Exception as e:
381
+ dialog = Gtk.MessageDialog(
382
+ parent=self.canvas.get_toplevel(), message_format=str(e),
383
+ type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
384
+ dialog.run()
385
+ dialog.destroy()
386
+
387
+
388
+ class ToolbarGTK3(ToolContainerBase, Gtk.Box):
389
+ _icon_extension = '-symbolic.svg'
390
+
391
+ def __init__(self, toolmanager):
392
+ ToolContainerBase.__init__(self, toolmanager)
393
+ Gtk.Box.__init__(self)
394
+ self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
395
+ self._message = Gtk.Label()
396
+ self._message.set_justify(Gtk.Justification.RIGHT)
397
+ self.pack_end(self._message, False, False, 0)
398
+ self.show_all()
399
+ self._groups = {}
400
+ self._toolitems = {}
401
+
402
+ def add_toolitem(self, name, group, position, image_file, description,
403
+ toggle):
404
+ if toggle:
405
+ button = Gtk.ToggleToolButton()
406
+ else:
407
+ button = Gtk.ToolButton()
408
+ button.set_label(name)
409
+
410
+ if image_file is not None:
411
+ image = Gtk.Image.new_from_gicon(
412
+ Gio.Icon.new_for_string(image_file),
413
+ Gtk.IconSize.LARGE_TOOLBAR)
414
+ button.set_icon_widget(image)
415
+
416
+ if position is None:
417
+ position = -1
418
+
419
+ self._add_button(button, group, position)
420
+ signal = button.connect('clicked', self._call_tool, name)
421
+ button.set_tooltip_text(description)
422
+ button.show_all()
423
+ self._toolitems.setdefault(name, [])
424
+ self._toolitems[name].append((button, signal))
425
+
426
+ def _add_button(self, button, group, position):
427
+ if group not in self._groups:
428
+ if self._groups:
429
+ self._add_separator()
430
+ toolbar = Gtk.Toolbar()
431
+ toolbar.set_style(Gtk.ToolbarStyle.ICONS)
432
+ self.pack_start(toolbar, False, False, 0)
433
+ toolbar.show_all()
434
+ self._groups[group] = toolbar
435
+ self._groups[group].insert(button, position)
436
+
437
+ def _call_tool(self, btn, name):
438
+ self.trigger_tool(name)
439
+
440
+ def toggle_toolitem(self, name, toggled):
441
+ if name not in self._toolitems:
442
+ return
443
+ for toolitem, signal in self._toolitems[name]:
444
+ toolitem.handler_block(signal)
445
+ toolitem.set_active(toggled)
446
+ toolitem.handler_unblock(signal)
447
+
448
+ def remove_toolitem(self, name):
449
+ for toolitem, _signal in self._toolitems.pop(name, []):
450
+ for group in self._groups:
451
+ if toolitem in self._groups[group]:
452
+ self._groups[group].remove(toolitem)
453
+
454
+ def _add_separator(self):
455
+ sep = Gtk.Separator()
456
+ sep.set_property("orientation", Gtk.Orientation.VERTICAL)
457
+ self.pack_start(sep, False, True, 0)
458
+ sep.show_all()
459
+
460
+ def set_message(self, s):
461
+ self._message.set_label(s)
462
+
463
+
464
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
465
+ class SaveFigureGTK3(backend_tools.SaveFigureBase):
466
+ def trigger(self, *args, **kwargs):
467
+ NavigationToolbar2GTK3.save_figure(
468
+ self._make_classic_style_pseudo_toolbar())
469
+
470
+
471
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
472
+ class HelpGTK3(backend_tools.ToolHelpBase):
473
+ def _normalize_shortcut(self, key):
474
+ """
475
+ Convert Matplotlib key presses to GTK+ accelerator identifiers.
476
+
477
+ Related to `FigureCanvasGTK3._get_key`.
478
+ """
479
+ special = {
480
+ 'backspace': 'BackSpace',
481
+ 'pagedown': 'Page_Down',
482
+ 'pageup': 'Page_Up',
483
+ 'scroll_lock': 'Scroll_Lock',
484
+ }
485
+
486
+ parts = key.split('+')
487
+ mods = ['<' + mod + '>' for mod in parts[:-1]]
488
+ key = parts[-1]
489
+
490
+ if key in special:
491
+ key = special[key]
492
+ elif len(key) > 1:
493
+ key = key.capitalize()
494
+ elif key.isupper():
495
+ mods += ['<shift>']
496
+
497
+ return ''.join(mods) + key
498
+
499
+ def _is_valid_shortcut(self, key):
500
+ """
501
+ Check for a valid shortcut to be displayed.
502
+
503
+ - GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`).
504
+ - The shortcut window only shows keyboard shortcuts, not mouse buttons.
505
+ """
506
+ return 'cmd+' not in key and not key.startswith('MouseButton.')
507
+
508
+ def _show_shortcuts_window(self):
509
+ section = Gtk.ShortcutsSection()
510
+
511
+ for name, tool in sorted(self.toolmanager.tools.items()):
512
+ if not tool.description:
513
+ continue
514
+
515
+ # Putting everything in a separate group allows GTK to
516
+ # automatically split them into separate columns/pages, which is
517
+ # useful because we have lots of shortcuts, some with many keys
518
+ # that are very wide.
519
+ group = Gtk.ShortcutsGroup()
520
+ section.add(group)
521
+ # A hack to remove the title since we have no group naming.
522
+ group.forall(lambda widget, data: widget.set_visible(False), None)
523
+
524
+ shortcut = Gtk.ShortcutsShortcut(
525
+ accelerator=' '.join(
526
+ self._normalize_shortcut(key)
527
+ for key in self.toolmanager.get_tool_keymap(name)
528
+ if self._is_valid_shortcut(key)),
529
+ title=tool.name,
530
+ subtitle=tool.description)
531
+ group.add(shortcut)
532
+
533
+ window = Gtk.ShortcutsWindow(
534
+ title='Help',
535
+ modal=True,
536
+ transient_for=self._figure.canvas.get_toplevel())
537
+ section.show() # Must be done explicitly before add!
538
+ window.add(section)
539
+
540
+ window.show_all()
541
+
542
+ def _show_shortcuts_dialog(self):
543
+ dialog = Gtk.MessageDialog(
544
+ self._figure.canvas.get_toplevel(),
545
+ 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(),
546
+ title="Help")
547
+ dialog.run()
548
+ dialog.destroy()
549
+
550
+ def trigger(self, *args):
551
+ if Gtk.check_version(3, 20, 0) is None:
552
+ self._show_shortcuts_window()
553
+ else:
554
+ self._show_shortcuts_dialog()
555
+
556
+
557
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
558
+ class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase):
559
+ def trigger(self, *args, **kwargs):
560
+ clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
561
+ window = self.canvas.get_window()
562
+ x, y, width, height = window.get_geometry()
563
+ pb = Gdk.pixbuf_get_from_window(window, x, y, width, height)
564
+ clipboard.set_image(pb)
565
+
566
+
567
+ Toolbar = ToolbarGTK3
568
+ backend_tools._register_tool_class(
569
+ FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK)
570
+ backend_tools._register_tool_class(
571
+ FigureCanvasGTK3, _backend_gtk.RubberbandGTK)
572
+
573
+
574
+ class FigureManagerGTK3(_FigureManagerGTK):
575
+ _toolbar2_class = NavigationToolbar2GTK3
576
+ _toolmanager_toolbar_class = ToolbarGTK3
577
+
578
+
579
+ @_BackendGTK.export
580
+ class _BackendGTK3(_BackendGTK):
581
+ FigureCanvas = FigureCanvasGTK3
582
+ FigureManager = FigureManagerGTK3
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3agg.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from .. import cbook, transforms
4
+ from . import backend_agg, backend_gtk3
5
+ from .backend_gtk3 import GLib, Gtk, _BackendGTK3
6
+
7
+ import cairo # Presence of cairo is already checked by _backend_gtk.
8
+
9
+
10
+ class FigureCanvasGTK3Agg(backend_agg.FigureCanvasAgg,
11
+ backend_gtk3.FigureCanvasGTK3):
12
+ def __init__(self, figure):
13
+ super().__init__(figure=figure)
14
+ self._bbox_queue = []
15
+
16
+ def on_draw_event(self, widget, ctx):
17
+ if self._idle_draw_id:
18
+ GLib.source_remove(self._idle_draw_id)
19
+ self._idle_draw_id = 0
20
+ self.draw()
21
+
22
+ scale = self.device_pixel_ratio
23
+ allocation = self.get_allocation()
24
+ w = allocation.width * scale
25
+ h = allocation.height * scale
26
+
27
+ if not len(self._bbox_queue):
28
+ Gtk.render_background(
29
+ self.get_style_context(), ctx,
30
+ allocation.x, allocation.y,
31
+ allocation.width, allocation.height)
32
+ bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]
33
+ else:
34
+ bbox_queue = self._bbox_queue
35
+
36
+ for bbox in bbox_queue:
37
+ x = int(bbox.x0)
38
+ y = h - int(bbox.y1)
39
+ width = int(bbox.x1) - int(bbox.x0)
40
+ height = int(bbox.y1) - int(bbox.y0)
41
+
42
+ buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(
43
+ np.asarray(self.copy_from_bbox(bbox)))
44
+ image = cairo.ImageSurface.create_for_data(
45
+ buf.ravel().data, cairo.FORMAT_ARGB32, width, height)
46
+ image.set_device_scale(scale, scale)
47
+ ctx.set_source_surface(image, x / scale, y / scale)
48
+ ctx.paint()
49
+
50
+ if len(self._bbox_queue):
51
+ self._bbox_queue = []
52
+
53
+ return False
54
+
55
+ def blit(self, bbox=None):
56
+ # If bbox is None, blit the entire canvas to gtk. Otherwise
57
+ # blit only the area defined by the bbox.
58
+ if bbox is None:
59
+ bbox = self.figure.bbox
60
+
61
+ scale = self.device_pixel_ratio
62
+ allocation = self.get_allocation()
63
+ x = int(bbox.x0 / scale)
64
+ y = allocation.height - int(bbox.y1 / scale)
65
+ width = (int(bbox.x1) - int(bbox.x0)) // scale
66
+ height = (int(bbox.y1) - int(bbox.y0)) // scale
67
+
68
+ self._bbox_queue.append(bbox)
69
+ self.queue_draw_area(x, y, width, height)
70
+
71
+
72
+ @_BackendGTK3.export
73
+ class _BackendGTK3Cairo(_BackendGTK3):
74
+ FigureCanvas = FigureCanvasGTK3Agg
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk3cairo.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+
3
+ from .backend_cairo import FigureCanvasCairo
4
+ from .backend_gtk3 import GLib, Gtk, FigureCanvasGTK3, _BackendGTK3
5
+
6
+
7
+ class FigureCanvasGTK3Cairo(FigureCanvasCairo, FigureCanvasGTK3):
8
+ def on_draw_event(self, widget, ctx):
9
+ if self._idle_draw_id:
10
+ GLib.source_remove(self._idle_draw_id)
11
+ self._idle_draw_id = 0
12
+ self.draw()
13
+
14
+ with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
15
+ else nullcontext()):
16
+ allocation = self.get_allocation()
17
+ # Render the background before scaling, as the allocated size here is in
18
+ # logical pixels.
19
+ Gtk.render_background(
20
+ self.get_style_context(), ctx,
21
+ 0, 0, allocation.width, allocation.height)
22
+ scale = self.device_pixel_ratio
23
+ # Scale physical drawing to logical size.
24
+ ctx.scale(1 / scale, 1 / scale)
25
+ self._renderer.set_context(ctx)
26
+ # Set renderer to physical size so it renders in full resolution.
27
+ self._renderer.width = allocation.width * scale
28
+ self._renderer.height = allocation.height * scale
29
+ self._renderer.dpi = self.figure.dpi
30
+ self.figure.draw(self._renderer)
31
+
32
+
33
+ @_BackendGTK3.export
34
+ class _BackendGTK3Cairo(_BackendGTK3):
35
+ FigureCanvas = FigureCanvasGTK3Cairo
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import io
3
+ import os
4
+
5
+ import matplotlib as mpl
6
+ from matplotlib import _api, backend_tools, cbook
7
+ from matplotlib.backend_bases import (
8
+ ToolContainerBase, KeyEvent, LocationEvent, MouseEvent, ResizeEvent,
9
+ CloseEvent)
10
+
11
+ try:
12
+ import gi
13
+ except ImportError as err:
14
+ raise ImportError("The GTK4 backends require PyGObject") from err
15
+
16
+ try:
17
+ # :raises ValueError: If module/version is already loaded, already
18
+ # required, or unavailable.
19
+ gi.require_version("Gtk", "4.0")
20
+ except ValueError as e:
21
+ # in this case we want to re-raise as ImportError so the
22
+ # auto-backend selection logic correctly skips.
23
+ raise ImportError(e) from e
24
+
25
+ from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf
26
+ from . import _backend_gtk
27
+ from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
28
+ _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
29
+ TimerGTK as TimerGTK4,
30
+ )
31
+
32
+
33
+ class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea):
34
+ required_interactive_framework = "gtk4"
35
+ supports_blit = False
36
+ manager_class = _api.classproperty(lambda cls: FigureManagerGTK4)
37
+
38
+ def __init__(self, figure=None):
39
+ super().__init__(figure=figure)
40
+
41
+ self.set_hexpand(True)
42
+ self.set_vexpand(True)
43
+
44
+ self._idle_draw_id = 0
45
+ self._rubberband_rect = None
46
+
47
+ self.set_draw_func(self._draw_func)
48
+ self.connect('resize', self.resize_event)
49
+ self.connect('notify::scale-factor', self._update_device_pixel_ratio)
50
+
51
+ click = Gtk.GestureClick()
52
+ click.set_button(0) # All buttons.
53
+ click.connect('pressed', self.button_press_event)
54
+ click.connect('released', self.button_release_event)
55
+ self.add_controller(click)
56
+
57
+ key = Gtk.EventControllerKey()
58
+ key.connect('key-pressed', self.key_press_event)
59
+ key.connect('key-released', self.key_release_event)
60
+ self.add_controller(key)
61
+
62
+ motion = Gtk.EventControllerMotion()
63
+ motion.connect('motion', self.motion_notify_event)
64
+ motion.connect('enter', self.enter_notify_event)
65
+ motion.connect('leave', self.leave_notify_event)
66
+ self.add_controller(motion)
67
+
68
+ scroll = Gtk.EventControllerScroll.new(
69
+ Gtk.EventControllerScrollFlags.VERTICAL)
70
+ scroll.connect('scroll', self.scroll_event)
71
+ self.add_controller(scroll)
72
+
73
+ self.set_focusable(True)
74
+
75
+ css = Gtk.CssProvider()
76
+ style = '.matplotlib-canvas { background-color: white; }'
77
+ if Gtk.check_version(4, 9, 3) is None:
78
+ css.load_from_data(style, -1)
79
+ else:
80
+ css.load_from_data(style.encode('utf-8'))
81
+ style_ctx = self.get_style_context()
82
+ style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
83
+ style_ctx.add_class("matplotlib-canvas")
84
+
85
+ def destroy(self):
86
+ CloseEvent("close_event", self)._process()
87
+
88
+ def set_cursor(self, cursor):
89
+ # docstring inherited
90
+ self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor))
91
+
92
+ def _mpl_coords(self, xy=None):
93
+ """
94
+ Convert the *xy* position of a GTK event, or of the current cursor
95
+ position if *xy* is None, to Matplotlib coordinates.
96
+
97
+ GTK use logical pixels, but the figure is scaled to physical pixels for
98
+ rendering. Transform to physical pixels so that all of the down-stream
99
+ transforms work as expected.
100
+
101
+ Also, the origin is different and needs to be corrected.
102
+ """
103
+ if xy is None:
104
+ surface = self.get_native().get_surface()
105
+ is_over, x, y, mask = surface.get_device_position(
106
+ self.get_display().get_default_seat().get_pointer())
107
+ else:
108
+ x, y = xy
109
+ x = x * self.device_pixel_ratio
110
+ # flip y so y=0 is bottom of canvas
111
+ y = self.figure.bbox.height - y * self.device_pixel_ratio
112
+ return x, y
113
+
114
+ def scroll_event(self, controller, dx, dy):
115
+ MouseEvent(
116
+ "scroll_event", self, *self._mpl_coords(), step=dy,
117
+ modifiers=self._mpl_modifiers(controller),
118
+ )._process()
119
+ return True
120
+
121
+ def button_press_event(self, controller, n_press, x, y):
122
+ MouseEvent(
123
+ "button_press_event", self, *self._mpl_coords((x, y)),
124
+ controller.get_current_button(),
125
+ modifiers=self._mpl_modifiers(controller),
126
+ )._process()
127
+ self.grab_focus()
128
+
129
+ def button_release_event(self, controller, n_press, x, y):
130
+ MouseEvent(
131
+ "button_release_event", self, *self._mpl_coords((x, y)),
132
+ controller.get_current_button(),
133
+ modifiers=self._mpl_modifiers(controller),
134
+ )._process()
135
+
136
+ def key_press_event(self, controller, keyval, keycode, state):
137
+ KeyEvent(
138
+ "key_press_event", self, self._get_key(keyval, keycode, state),
139
+ *self._mpl_coords(),
140
+ )._process()
141
+ return True
142
+
143
+ def key_release_event(self, controller, keyval, keycode, state):
144
+ KeyEvent(
145
+ "key_release_event", self, self._get_key(keyval, keycode, state),
146
+ *self._mpl_coords(),
147
+ )._process()
148
+ return True
149
+
150
+ def motion_notify_event(self, controller, x, y):
151
+ MouseEvent(
152
+ "motion_notify_event", self, *self._mpl_coords((x, y)),
153
+ modifiers=self._mpl_modifiers(controller),
154
+ )._process()
155
+
156
+ def enter_notify_event(self, controller, x, y):
157
+ LocationEvent(
158
+ "figure_enter_event", self, *self._mpl_coords((x, y)),
159
+ modifiers=self._mpl_modifiers(),
160
+ )._process()
161
+
162
+ def leave_notify_event(self, controller):
163
+ LocationEvent(
164
+ "figure_leave_event", self, *self._mpl_coords(),
165
+ modifiers=self._mpl_modifiers(),
166
+ )._process()
167
+
168
+ def resize_event(self, area, width, height):
169
+ self._update_device_pixel_ratio()
170
+ dpi = self.figure.dpi
171
+ winch = width * self.device_pixel_ratio / dpi
172
+ hinch = height * self.device_pixel_ratio / dpi
173
+ self.figure.set_size_inches(winch, hinch, forward=False)
174
+ ResizeEvent("resize_event", self)._process()
175
+ self.draw_idle()
176
+
177
+ def _mpl_modifiers(self, controller=None):
178
+ if controller is None:
179
+ surface = self.get_native().get_surface()
180
+ is_over, x, y, event_state = surface.get_device_position(
181
+ self.get_display().get_default_seat().get_pointer())
182
+ else:
183
+ event_state = controller.get_current_event_state()
184
+ mod_table = [
185
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK),
186
+ ("alt", Gdk.ModifierType.ALT_MASK),
187
+ ("shift", Gdk.ModifierType.SHIFT_MASK),
188
+ ("super", Gdk.ModifierType.SUPER_MASK),
189
+ ]
190
+ return [name for name, mask in mod_table if event_state & mask]
191
+
192
+ def _get_key(self, keyval, keycode, state):
193
+ unikey = chr(Gdk.keyval_to_unicode(keyval))
194
+ key = cbook._unikey_or_keysym_to_mplkey(
195
+ unikey,
196
+ Gdk.keyval_name(keyval))
197
+ modifiers = [
198
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
199
+ ("alt", Gdk.ModifierType.ALT_MASK, "alt"),
200
+ ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
201
+ ("super", Gdk.ModifierType.SUPER_MASK, "super"),
202
+ ]
203
+ mods = [
204
+ mod for mod, mask, mod_key in modifiers
205
+ if (mod_key != key and state & mask
206
+ and not (mod == "shift" and unikey.isprintable()))]
207
+ return "+".join([*mods, key])
208
+
209
+ def _update_device_pixel_ratio(self, *args, **kwargs):
210
+ # We need to be careful in cases with mixed resolution displays if
211
+ # device_pixel_ratio changes.
212
+ if self._set_device_pixel_ratio(self.get_scale_factor()):
213
+ self.draw()
214
+
215
+ def _draw_rubberband(self, rect):
216
+ self._rubberband_rect = rect
217
+ # TODO: Only update the rubberband area.
218
+ self.queue_draw()
219
+
220
+ def _draw_func(self, drawing_area, ctx, width, height):
221
+ self.on_draw_event(self, ctx)
222
+ self._post_draw(self, ctx)
223
+
224
+ def _post_draw(self, widget, ctx):
225
+ if self._rubberband_rect is None:
226
+ return
227
+
228
+ lw = 1
229
+ dash = 3
230
+ x0, y0, w, h = (dim / self.device_pixel_ratio
231
+ for dim in self._rubberband_rect)
232
+ x1 = x0 + w
233
+ y1 = y0 + h
234
+
235
+ # Draw the lines from x0, y0 towards x1, y1 so that the
236
+ # dashes don't "jump" when moving the zoom box.
237
+ ctx.move_to(x0, y0)
238
+ ctx.line_to(x0, y1)
239
+ ctx.move_to(x0, y0)
240
+ ctx.line_to(x1, y0)
241
+ ctx.move_to(x0, y1)
242
+ ctx.line_to(x1, y1)
243
+ ctx.move_to(x1, y0)
244
+ ctx.line_to(x1, y1)
245
+
246
+ ctx.set_antialias(1)
247
+ ctx.set_line_width(lw)
248
+ ctx.set_dash((dash, dash), 0)
249
+ ctx.set_source_rgb(0, 0, 0)
250
+ ctx.stroke_preserve()
251
+
252
+ ctx.set_dash((dash, dash), dash)
253
+ ctx.set_source_rgb(1, 1, 1)
254
+ ctx.stroke()
255
+
256
+ def on_draw_event(self, widget, ctx):
257
+ # to be overwritten by GTK4Agg or GTK4Cairo
258
+ pass
259
+
260
+ def draw(self):
261
+ # docstring inherited
262
+ if self.is_drawable():
263
+ self.queue_draw()
264
+
265
+ def draw_idle(self):
266
+ # docstring inherited
267
+ if self._idle_draw_id != 0:
268
+ return
269
+ def idle_draw(*args):
270
+ try:
271
+ self.draw()
272
+ finally:
273
+ self._idle_draw_id = 0
274
+ return False
275
+ self._idle_draw_id = GLib.idle_add(idle_draw)
276
+
277
+ def flush_events(self):
278
+ # docstring inherited
279
+ context = GLib.MainContext.default()
280
+ while context.pending():
281
+ context.iteration(True)
282
+
283
+
284
+ class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box):
285
+ def __init__(self, canvas):
286
+ Gtk.Box.__init__(self)
287
+
288
+ self.add_css_class('toolbar')
289
+
290
+ self._gtk_ids = {}
291
+ for text, tooltip_text, image_file, callback in self.toolitems:
292
+ if text is None:
293
+ self.append(Gtk.Separator())
294
+ continue
295
+ image = Gtk.Image.new_from_gicon(
296
+ Gio.Icon.new_for_string(
297
+ str(cbook._get_data_path('images',
298
+ f'{image_file}-symbolic.svg'))))
299
+ self._gtk_ids[text] = button = (
300
+ Gtk.ToggleButton() if callback in ['zoom', 'pan'] else
301
+ Gtk.Button())
302
+ button.set_child(image)
303
+ button.add_css_class('flat')
304
+ button.add_css_class('image-button')
305
+ # Save the handler id, so that we can block it as needed.
306
+ button._signal_handler = button.connect(
307
+ 'clicked', getattr(self, callback))
308
+ button.set_tooltip_text(tooltip_text)
309
+ self.append(button)
310
+
311
+ # This filler item ensures the toolbar is always at least two text
312
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
313
+ # over images because those use two-line messages which resize the
314
+ # toolbar.
315
+ label = Gtk.Label()
316
+ label.set_markup(
317
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
318
+ label.set_hexpand(True) # Push real message to the right.
319
+ self.append(label)
320
+
321
+ self.message = Gtk.Label()
322
+ self.message.set_justify(Gtk.Justification.RIGHT)
323
+ self.append(self.message)
324
+
325
+ _NavigationToolbar2GTK.__init__(self, canvas)
326
+
327
+ def save_figure(self, *args):
328
+ dialog = Gtk.FileChooserNative(
329
+ title='Save the figure',
330
+ transient_for=self.canvas.get_root(),
331
+ action=Gtk.FileChooserAction.SAVE,
332
+ modal=True)
333
+ self._save_dialog = dialog # Must keep a reference.
334
+
335
+ ff = Gtk.FileFilter()
336
+ ff.set_name('All files')
337
+ ff.add_pattern('*')
338
+ dialog.add_filter(ff)
339
+ dialog.set_filter(ff)
340
+
341
+ formats = []
342
+ default_format = None
343
+ for i, (name, fmts) in enumerate(
344
+ self.canvas.get_supported_filetypes_grouped().items()):
345
+ ff = Gtk.FileFilter()
346
+ ff.set_name(name)
347
+ for fmt in fmts:
348
+ ff.add_pattern(f'*.{fmt}')
349
+ dialog.add_filter(ff)
350
+ formats.append(name)
351
+ if self.canvas.get_default_filetype() in fmts:
352
+ default_format = i
353
+ # Setting the choice doesn't always work, so make sure the default
354
+ # format is first.
355
+ formats = [formats[default_format], *formats[:default_format],
356
+ *formats[default_format+1:]]
357
+ dialog.add_choice('format', 'File format', formats, formats)
358
+ dialog.set_choice('format', formats[0])
359
+
360
+ dialog.set_current_folder(Gio.File.new_for_path(
361
+ os.path.expanduser(mpl.rcParams['savefig.directory'])))
362
+ dialog.set_current_name(self.canvas.get_default_filename())
363
+
364
+ @functools.partial(dialog.connect, 'response')
365
+ def on_response(dialog, response):
366
+ file = dialog.get_file()
367
+ fmt = dialog.get_choice('format')
368
+ fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0]
369
+ dialog.destroy()
370
+ self._save_dialog = None
371
+ if response != Gtk.ResponseType.ACCEPT:
372
+ return
373
+ # Save dir for next time, unless empty str (which means use cwd).
374
+ if mpl.rcParams['savefig.directory']:
375
+ parent = file.get_parent()
376
+ mpl.rcParams['savefig.directory'] = parent.get_path()
377
+ try:
378
+ self.canvas.figure.savefig(file.get_path(), format=fmt)
379
+ except Exception as e:
380
+ msg = Gtk.MessageDialog(
381
+ transient_for=self.canvas.get_root(),
382
+ message_type=Gtk.MessageType.ERROR,
383
+ buttons=Gtk.ButtonsType.OK, modal=True,
384
+ text=str(e))
385
+ msg.show()
386
+
387
+ dialog.show()
388
+
389
+
390
+ class ToolbarGTK4(ToolContainerBase, Gtk.Box):
391
+ _icon_extension = '-symbolic.svg'
392
+
393
+ def __init__(self, toolmanager):
394
+ ToolContainerBase.__init__(self, toolmanager)
395
+ Gtk.Box.__init__(self)
396
+ self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
397
+
398
+ # Tool items are created later, but must appear before the message.
399
+ self._tool_box = Gtk.Box()
400
+ self.append(self._tool_box)
401
+ self._groups = {}
402
+ self._toolitems = {}
403
+
404
+ # This filler item ensures the toolbar is always at least two text
405
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
406
+ # over images because those use two-line messages which resize the
407
+ # toolbar.
408
+ label = Gtk.Label()
409
+ label.set_markup(
410
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
411
+ label.set_hexpand(True) # Push real message to the right.
412
+ self.append(label)
413
+
414
+ self._message = Gtk.Label()
415
+ self._message.set_justify(Gtk.Justification.RIGHT)
416
+ self.append(self._message)
417
+
418
+ def add_toolitem(self, name, group, position, image_file, description,
419
+ toggle):
420
+ if toggle:
421
+ button = Gtk.ToggleButton()
422
+ else:
423
+ button = Gtk.Button()
424
+ button.set_label(name)
425
+ button.add_css_class('flat')
426
+
427
+ if image_file is not None:
428
+ image = Gtk.Image.new_from_gicon(
429
+ Gio.Icon.new_for_string(image_file))
430
+ button.set_child(image)
431
+ button.add_css_class('image-button')
432
+
433
+ if position is None:
434
+ position = -1
435
+
436
+ self._add_button(button, group, position)
437
+ signal = button.connect('clicked', self._call_tool, name)
438
+ button.set_tooltip_text(description)
439
+ self._toolitems.setdefault(name, [])
440
+ self._toolitems[name].append((button, signal))
441
+
442
+ def _find_child_at_position(self, group, position):
443
+ children = [None]
444
+ child = self._groups[group].get_first_child()
445
+ while child is not None:
446
+ children.append(child)
447
+ child = child.get_next_sibling()
448
+ return children[position]
449
+
450
+ def _add_button(self, button, group, position):
451
+ if group not in self._groups:
452
+ if self._groups:
453
+ self._add_separator()
454
+ group_box = Gtk.Box()
455
+ self._tool_box.append(group_box)
456
+ self._groups[group] = group_box
457
+ self._groups[group].insert_child_after(
458
+ button, self._find_child_at_position(group, position))
459
+
460
+ def _call_tool(self, btn, name):
461
+ self.trigger_tool(name)
462
+
463
+ def toggle_toolitem(self, name, toggled):
464
+ if name not in self._toolitems:
465
+ return
466
+ for toolitem, signal in self._toolitems[name]:
467
+ toolitem.handler_block(signal)
468
+ toolitem.set_active(toggled)
469
+ toolitem.handler_unblock(signal)
470
+
471
+ def remove_toolitem(self, name):
472
+ for toolitem, _signal in self._toolitems.pop(name, []):
473
+ for group in self._groups:
474
+ if toolitem in self._groups[group]:
475
+ self._groups[group].remove(toolitem)
476
+
477
+ def _add_separator(self):
478
+ sep = Gtk.Separator()
479
+ sep.set_property("orientation", Gtk.Orientation.VERTICAL)
480
+ self._tool_box.append(sep)
481
+
482
+ def set_message(self, s):
483
+ self._message.set_label(s)
484
+
485
+
486
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
487
+ class SaveFigureGTK4(backend_tools.SaveFigureBase):
488
+ def trigger(self, *args, **kwargs):
489
+ NavigationToolbar2GTK4.save_figure(
490
+ self._make_classic_style_pseudo_toolbar())
491
+
492
+
493
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
494
+ class HelpGTK4(backend_tools.ToolHelpBase):
495
+ def _normalize_shortcut(self, key):
496
+ """
497
+ Convert Matplotlib key presses to GTK+ accelerator identifiers.
498
+
499
+ Related to `FigureCanvasGTK4._get_key`.
500
+ """
501
+ special = {
502
+ 'backspace': 'BackSpace',
503
+ 'pagedown': 'Page_Down',
504
+ 'pageup': 'Page_Up',
505
+ 'scroll_lock': 'Scroll_Lock',
506
+ }
507
+
508
+ parts = key.split('+')
509
+ mods = ['<' + mod + '>' for mod in parts[:-1]]
510
+ key = parts[-1]
511
+
512
+ if key in special:
513
+ key = special[key]
514
+ elif len(key) > 1:
515
+ key = key.capitalize()
516
+ elif key.isupper():
517
+ mods += ['<shift>']
518
+
519
+ return ''.join(mods) + key
520
+
521
+ def _is_valid_shortcut(self, key):
522
+ """
523
+ Check for a valid shortcut to be displayed.
524
+
525
+ - GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`).
526
+ - The shortcut window only shows keyboard shortcuts, not mouse buttons.
527
+ """
528
+ return 'cmd+' not in key and not key.startswith('MouseButton.')
529
+
530
+ def trigger(self, *args):
531
+ section = Gtk.ShortcutsSection()
532
+
533
+ for name, tool in sorted(self.toolmanager.tools.items()):
534
+ if not tool.description:
535
+ continue
536
+
537
+ # Putting everything in a separate group allows GTK to
538
+ # automatically split them into separate columns/pages, which is
539
+ # useful because we have lots of shortcuts, some with many keys
540
+ # that are very wide.
541
+ group = Gtk.ShortcutsGroup()
542
+ section.append(group)
543
+ # A hack to remove the title since we have no group naming.
544
+ child = group.get_first_child()
545
+ while child is not None:
546
+ child.set_visible(False)
547
+ child = child.get_next_sibling()
548
+
549
+ shortcut = Gtk.ShortcutsShortcut(
550
+ accelerator=' '.join(
551
+ self._normalize_shortcut(key)
552
+ for key in self.toolmanager.get_tool_keymap(name)
553
+ if self._is_valid_shortcut(key)),
554
+ title=tool.name,
555
+ subtitle=tool.description)
556
+ group.append(shortcut)
557
+
558
+ window = Gtk.ShortcutsWindow(
559
+ title='Help',
560
+ modal=True,
561
+ transient_for=self._figure.canvas.get_root())
562
+ window.set_child(section)
563
+
564
+ window.show()
565
+
566
+
567
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
568
+ class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase):
569
+ def trigger(self, *args, **kwargs):
570
+ with io.BytesIO() as f:
571
+ self.canvas.print_rgba(f)
572
+ w, h = self.canvas.get_width_height()
573
+ pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),
574
+ GdkPixbuf.Colorspace.RGB, True,
575
+ 8, w, h, w*4)
576
+ clipboard = self.canvas.get_clipboard()
577
+ clipboard.set(pb)
578
+
579
+
580
+ backend_tools._register_tool_class(
581
+ FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK)
582
+ backend_tools._register_tool_class(
583
+ FigureCanvasGTK4, _backend_gtk.RubberbandGTK)
584
+ Toolbar = ToolbarGTK4
585
+
586
+
587
+ class FigureManagerGTK4(_FigureManagerGTK):
588
+ _toolbar2_class = NavigationToolbar2GTK4
589
+ _toolmanager_toolbar_class = ToolbarGTK4
590
+
591
+
592
+ @_BackendGTK.export
593
+ class _BackendGTK4(_BackendGTK):
594
+ FigureCanvas = FigureCanvasGTK4
595
+ FigureManager = FigureManagerGTK4
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_gtk4cairo.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+
3
+ from .backend_cairo import FigureCanvasCairo
4
+ from .backend_gtk4 import GLib, Gtk, FigureCanvasGTK4, _BackendGTK4
5
+
6
+
7
+ class FigureCanvasGTK4Cairo(FigureCanvasCairo, FigureCanvasGTK4):
8
+ def _set_device_pixel_ratio(self, ratio):
9
+ # Cairo in GTK4 always uses logical pixels, so we don't need to do anything for
10
+ # changes to the device pixel ratio.
11
+ return False
12
+
13
+ def on_draw_event(self, widget, ctx):
14
+ if self._idle_draw_id:
15
+ GLib.source_remove(self._idle_draw_id)
16
+ self._idle_draw_id = 0
17
+ self.draw()
18
+
19
+ with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
20
+ else nullcontext()):
21
+ self._renderer.set_context(ctx)
22
+ allocation = self.get_allocation()
23
+ Gtk.render_background(
24
+ self.get_style_context(), ctx,
25
+ allocation.x, allocation.y,
26
+ allocation.width, allocation.height)
27
+ self.figure.draw(self._renderer)
28
+
29
+
30
+ @_BackendGTK4.export
31
+ class _BackendGTK4Cairo(_BackendGTK4):
32
+ FigureCanvas = FigureCanvasGTK4Cairo
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_mixed.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from matplotlib import cbook
4
+ from .backend_agg import RendererAgg
5
+ from matplotlib._tight_bbox import process_figure_for_rasterizing
6
+
7
+
8
+ class MixedModeRenderer:
9
+ """
10
+ A helper class to implement a renderer that switches between
11
+ vector and raster drawing. An example may be a PDF writer, where
12
+ most things are drawn with PDF vector commands, but some very
13
+ complex objects, such as quad meshes, are rasterised and then
14
+ output as images.
15
+ """
16
+ def __init__(self, figure, width, height, dpi, vector_renderer,
17
+ raster_renderer_class=None,
18
+ bbox_inches_restore=None):
19
+ """
20
+ Parameters
21
+ ----------
22
+ figure : `~matplotlib.figure.Figure`
23
+ The figure instance.
24
+ width : scalar
25
+ The width of the canvas in logical units
26
+ height : scalar
27
+ The height of the canvas in logical units
28
+ dpi : float
29
+ The dpi of the canvas
30
+ vector_renderer : `~matplotlib.backend_bases.RendererBase`
31
+ An instance of a subclass of
32
+ `~matplotlib.backend_bases.RendererBase` that will be used for the
33
+ vector drawing.
34
+ raster_renderer_class : `~matplotlib.backend_bases.RendererBase`
35
+ The renderer class to use for the raster drawing. If not provided,
36
+ this will use the Agg backend (which is currently the only viable
37
+ option anyway.)
38
+
39
+ """
40
+ if raster_renderer_class is None:
41
+ raster_renderer_class = RendererAgg
42
+
43
+ self._raster_renderer_class = raster_renderer_class
44
+ self._width = width
45
+ self._height = height
46
+ self.dpi = dpi
47
+
48
+ self._vector_renderer = vector_renderer
49
+
50
+ self._raster_renderer = None
51
+
52
+ # A reference to the figure is needed as we need to change
53
+ # the figure dpi before and after the rasterization. Although
54
+ # this looks ugly, I couldn't find a better solution. -JJL
55
+ self.figure = figure
56
+ self._figdpi = figure.dpi
57
+
58
+ self._bbox_inches_restore = bbox_inches_restore
59
+
60
+ self._renderer = vector_renderer
61
+
62
+ def __getattr__(self, attr):
63
+ # Proxy everything that hasn't been overridden to the base
64
+ # renderer. Things that *are* overridden can call methods
65
+ # on self._renderer directly, but must not cache/store
66
+ # methods (because things like RendererAgg change their
67
+ # methods on the fly in order to optimise proxying down
68
+ # to the underlying C implementation).
69
+ return getattr(self._renderer, attr)
70
+
71
+ def start_rasterizing(self):
72
+ """
73
+ Enter "raster" mode. All subsequent drawing commands (until
74
+ `stop_rasterizing` is called) will be drawn with the raster backend.
75
+ """
76
+ # change the dpi of the figure temporarily.
77
+ self.figure.dpi = self.dpi
78
+ if self._bbox_inches_restore: # when tight bbox is used
79
+ r = process_figure_for_rasterizing(self.figure,
80
+ self._bbox_inches_restore)
81
+ self._bbox_inches_restore = r
82
+
83
+ self._raster_renderer = self._raster_renderer_class(
84
+ self._width*self.dpi, self._height*self.dpi, self.dpi)
85
+ self._renderer = self._raster_renderer
86
+
87
+ def stop_rasterizing(self):
88
+ """
89
+ Exit "raster" mode. All of the drawing that was done since
90
+ the last `start_rasterizing` call will be copied to the
91
+ vector backend by calling draw_image.
92
+ """
93
+
94
+ self._renderer = self._vector_renderer
95
+
96
+ height = self._height * self.dpi
97
+ img = np.asarray(self._raster_renderer.buffer_rgba())
98
+ slice_y, slice_x = cbook._get_nonzero_slices(img[..., 3])
99
+ cropped_img = img[slice_y, slice_x]
100
+ if cropped_img.size:
101
+ gc = self._renderer.new_gc()
102
+ # TODO: If the mixedmode resolution differs from the figure's
103
+ # dpi, the image must be scaled (dpi->_figdpi). Not all
104
+ # backends support this.
105
+ self._renderer.draw_image(
106
+ gc,
107
+ slice_x.start * self._figdpi / self.dpi,
108
+ (height - slice_y.stop) * self._figdpi / self.dpi,
109
+ cropped_img[::-1])
110
+ self._raster_renderer = None
111
+
112
+ # restore the figure dpi.
113
+ self.figure.dpi = self._figdpi
114
+
115
+ if self._bbox_inches_restore: # when tight bbox is used
116
+ r = process_figure_for_rasterizing(self.figure,
117
+ self._bbox_inches_restore,
118
+ self._figdpi)
119
+ self._bbox_inches_restore = r
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_pdf.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py ADDED
@@ -0,0 +1,1326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A PostScript backend, which can produce both PostScript .ps and .eps.
3
+ """
4
+
5
+ import codecs
6
+ import datetime
7
+ from enum import Enum
8
+ import functools
9
+ from io import StringIO
10
+ import itertools
11
+ import logging
12
+ import math
13
+ import os
14
+ import pathlib
15
+ import shutil
16
+ from tempfile import TemporaryDirectory
17
+ import time
18
+
19
+ import numpy as np
20
+
21
+ import matplotlib as mpl
22
+ from matplotlib import _api, cbook, _path, _text_helpers
23
+ from matplotlib._afm import AFM
24
+ from matplotlib.backend_bases import (
25
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
26
+ from matplotlib.cbook import is_writable_file_like, file_requires_unicode
27
+ from matplotlib.font_manager import get_font
28
+ from matplotlib.ft2font import LOAD_NO_SCALE, FT2Font
29
+ from matplotlib._ttconv import convert_ttf_to_ps
30
+ from matplotlib._mathtext_data import uni2type1
31
+ from matplotlib.path import Path
32
+ from matplotlib.texmanager import TexManager
33
+ from matplotlib.transforms import Affine2D
34
+ from matplotlib.backends.backend_mixed import MixedModeRenderer
35
+ from . import _backend_pdf_ps
36
+
37
+
38
+ _log = logging.getLogger(__name__)
39
+ debugPS = False
40
+
41
+
42
+ @_api.caching_module_getattr
43
+ class __getattr__:
44
+ # module-level deprecations
45
+ psDefs = _api.deprecated("3.8", obj_type="")(property(lambda self: _psDefs))
46
+
47
+
48
+ papersize = {'letter': (8.5, 11),
49
+ 'legal': (8.5, 14),
50
+ 'ledger': (11, 17),
51
+ 'a0': (33.11, 46.81),
52
+ 'a1': (23.39, 33.11),
53
+ 'a2': (16.54, 23.39),
54
+ 'a3': (11.69, 16.54),
55
+ 'a4': (8.27, 11.69),
56
+ 'a5': (5.83, 8.27),
57
+ 'a6': (4.13, 5.83),
58
+ 'a7': (2.91, 4.13),
59
+ 'a8': (2.05, 2.91),
60
+ 'a9': (1.46, 2.05),
61
+ 'a10': (1.02, 1.46),
62
+ 'b0': (40.55, 57.32),
63
+ 'b1': (28.66, 40.55),
64
+ 'b2': (20.27, 28.66),
65
+ 'b3': (14.33, 20.27),
66
+ 'b4': (10.11, 14.33),
67
+ 'b5': (7.16, 10.11),
68
+ 'b6': (5.04, 7.16),
69
+ 'b7': (3.58, 5.04),
70
+ 'b8': (2.51, 3.58),
71
+ 'b9': (1.76, 2.51),
72
+ 'b10': (1.26, 1.76)}
73
+
74
+
75
+ def _get_papertype(w, h):
76
+ for key, (pw, ph) in sorted(papersize.items(), reverse=True):
77
+ if key.startswith('l'):
78
+ continue
79
+ if w < pw and h < ph:
80
+ return key
81
+ return 'a0'
82
+
83
+
84
+ def _nums_to_str(*args, sep=" "):
85
+ return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
86
+
87
+
88
+ def _move_path_to_path_or_stream(src, dst):
89
+ """
90
+ Move the contents of file at *src* to path-or-filelike *dst*.
91
+
92
+ If *dst* is a path, the metadata of *src* are *not* copied.
93
+ """
94
+ if is_writable_file_like(dst):
95
+ fh = (open(src, encoding='latin-1')
96
+ if file_requires_unicode(dst)
97
+ else open(src, 'rb'))
98
+ with fh:
99
+ shutil.copyfileobj(fh, dst)
100
+ else:
101
+ shutil.move(src, dst, copy_function=shutil.copyfile)
102
+
103
+
104
+ def _font_to_ps_type3(font_path, chars):
105
+ """
106
+ Subset *chars* from the font at *font_path* into a Type 3 font.
107
+
108
+ Parameters
109
+ ----------
110
+ font_path : path-like
111
+ Path to the font to be subsetted.
112
+ chars : str
113
+ The characters to include in the subsetted font.
114
+
115
+ Returns
116
+ -------
117
+ str
118
+ The string representation of a Type 3 font, which can be included
119
+ verbatim into a PostScript file.
120
+ """
121
+ font = get_font(font_path, hinting_factor=1)
122
+ glyph_ids = [font.get_char_index(c) for c in chars]
123
+
124
+ preamble = """\
125
+ %!PS-Adobe-3.0 Resource-Font
126
+ %%Creator: Converted from TrueType to Type 3 by Matplotlib.
127
+ 10 dict begin
128
+ /FontName /{font_name} def
129
+ /PaintType 0 def
130
+ /FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
131
+ /FontBBox [{bbox}] def
132
+ /FontType 3 def
133
+ /Encoding [{encoding}] def
134
+ /CharStrings {num_glyphs} dict dup begin
135
+ /.notdef 0 def
136
+ """.format(font_name=font.postscript_name,
137
+ inv_units_per_em=1 / font.units_per_EM,
138
+ bbox=" ".join(map(str, font.bbox)),
139
+ encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"
140
+ for glyph_id in glyph_ids),
141
+ num_glyphs=len(glyph_ids) + 1)
142
+ postamble = """
143
+ end readonly def
144
+
145
+ /BuildGlyph {
146
+ exch begin
147
+ CharStrings exch
148
+ 2 copy known not {pop /.notdef} if
149
+ true 3 1 roll get exec
150
+ end
151
+ } _d
152
+
153
+ /BuildChar {
154
+ 1 index /Encoding get exch get
155
+ 1 index /BuildGlyph get exec
156
+ } _d
157
+
158
+ FontName currentdict end definefont pop
159
+ """
160
+
161
+ entries = []
162
+ for glyph_id in glyph_ids:
163
+ g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
164
+ v, c = font.get_path()
165
+ entries.append(
166
+ "/%(name)s{%(bbox)s sc\n" % {
167
+ "name": font.get_glyph_name(glyph_id),
168
+ "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
169
+ }
170
+ + _path.convert_to_string(
171
+ # Convert back to TrueType's internal units (1/64's).
172
+ # (Other dimensions are already in these units.)
173
+ Path(v * 64, c), None, None, False, None, 0,
174
+ # No code for quad Beziers triggers auto-conversion to cubics.
175
+ # Drop intermediate closepolys (relying on the outline
176
+ # decomposer always explicitly moving to the closing point
177
+ # first).
178
+ [b"m", b"l", b"", b"c", b""], True).decode("ascii")
179
+ + "ce} _d"
180
+ )
181
+
182
+ return preamble + "\n".join(entries) + postamble
183
+
184
+
185
+ def _font_to_ps_type42(font_path, chars, fh):
186
+ """
187
+ Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
188
+
189
+ Parameters
190
+ ----------
191
+ font_path : path-like
192
+ Path to the font to be subsetted.
193
+ chars : str
194
+ The characters to include in the subsetted font.
195
+ fh : file-like
196
+ Where to write the font.
197
+ """
198
+ subset_str = ''.join(chr(c) for c in chars)
199
+ _log.debug("SUBSET %s characters: %s", font_path, subset_str)
200
+ try:
201
+ fontdata = _backend_pdf_ps.get_glyphs_subset(font_path, subset_str)
202
+ _log.debug("SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
203
+ fontdata.getbuffer().nbytes)
204
+
205
+ # Give ttconv a subsetted font along with updated glyph_ids.
206
+ font = FT2Font(fontdata)
207
+ glyph_ids = [font.get_char_index(c) for c in chars]
208
+ with TemporaryDirectory() as tmpdir:
209
+ tmpfile = os.path.join(tmpdir, "tmp.ttf")
210
+
211
+ with open(tmpfile, 'wb') as tmp:
212
+ tmp.write(fontdata.getvalue())
213
+
214
+ # TODO: allow convert_ttf_to_ps to input file objects (BytesIO)
215
+ convert_ttf_to_ps(os.fsencode(tmpfile), fh, 42, glyph_ids)
216
+ except RuntimeError:
217
+ _log.warning(
218
+ "The PostScript backend does not currently "
219
+ "support the selected font.")
220
+ raise
221
+
222
+
223
+ def _log_if_debug_on(meth):
224
+ """
225
+ Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
226
+ if the global flag `debugPS` is set.
227
+ """
228
+ @functools.wraps(meth)
229
+ def wrapper(self, *args, **kwargs):
230
+ if debugPS:
231
+ self._pswriter.write(f"% {meth.__name__}\n")
232
+ return meth(self, *args, **kwargs)
233
+
234
+ return wrapper
235
+
236
+
237
+ class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
238
+ """
239
+ The renderer handles all the drawing primitives using a graphics
240
+ context instance that controls the colors/styles.
241
+ """
242
+
243
+ _afm_font_dir = cbook._get_data_path("fonts/afm")
244
+ _use_afm_rc_name = "ps.useafm"
245
+
246
+ def __init__(self, width, height, pswriter, imagedpi=72):
247
+ # Although postscript itself is dpi independent, we need to inform the
248
+ # image code about a requested dpi to generate high resolution images
249
+ # and them scale them before embedding them.
250
+ super().__init__(width, height)
251
+ self._pswriter = pswriter
252
+ if mpl.rcParams['text.usetex']:
253
+ self.textcnt = 0
254
+ self.psfrag = []
255
+ self.imagedpi = imagedpi
256
+
257
+ # current renderer state (None=uninitialised)
258
+ self.color = None
259
+ self.linewidth = None
260
+ self.linejoin = None
261
+ self.linecap = None
262
+ self.linedash = None
263
+ self.fontname = None
264
+ self.fontsize = None
265
+ self._hatches = {}
266
+ self.image_magnification = imagedpi / 72
267
+ self._clip_paths = {}
268
+ self._path_collection_id = 0
269
+
270
+ self._character_tracker = _backend_pdf_ps.CharacterTracker()
271
+ self._logwarn_once = functools.cache(_log.warning)
272
+
273
+ def _is_transparent(self, rgb_or_rgba):
274
+ if rgb_or_rgba is None:
275
+ return True # Consistent with rgbFace semantics.
276
+ elif len(rgb_or_rgba) == 4:
277
+ if rgb_or_rgba[3] == 0:
278
+ return True
279
+ if rgb_or_rgba[3] != 1:
280
+ self._logwarn_once(
281
+ "The PostScript backend does not support transparency; "
282
+ "partially transparent artists will be rendered opaque.")
283
+ return False
284
+ else: # len() == 3.
285
+ return False
286
+
287
+ def set_color(self, r, g, b, store=True):
288
+ if (r, g, b) != self.color:
289
+ self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
290
+ if r == g == b else
291
+ f"{_nums_to_str(r, g, b)} setrgbcolor\n")
292
+ if store:
293
+ self.color = (r, g, b)
294
+
295
+ def set_linewidth(self, linewidth, store=True):
296
+ linewidth = float(linewidth)
297
+ if linewidth != self.linewidth:
298
+ self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
299
+ if store:
300
+ self.linewidth = linewidth
301
+
302
+ @staticmethod
303
+ def _linejoin_cmd(linejoin):
304
+ # Support for directly passing integer values is for backcompat.
305
+ linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
306
+ linejoin]
307
+ return f"{linejoin:d} setlinejoin\n"
308
+
309
+ def set_linejoin(self, linejoin, store=True):
310
+ if linejoin != self.linejoin:
311
+ self._pswriter.write(self._linejoin_cmd(linejoin))
312
+ if store:
313
+ self.linejoin = linejoin
314
+
315
+ @staticmethod
316
+ def _linecap_cmd(linecap):
317
+ # Support for directly passing integer values is for backcompat.
318
+ linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
319
+ linecap]
320
+ return f"{linecap:d} setlinecap\n"
321
+
322
+ def set_linecap(self, linecap, store=True):
323
+ if linecap != self.linecap:
324
+ self._pswriter.write(self._linecap_cmd(linecap))
325
+ if store:
326
+ self.linecap = linecap
327
+
328
+ def set_linedash(self, offset, seq, store=True):
329
+ if self.linedash is not None:
330
+ oldo, oldseq = self.linedash
331
+ if np.array_equal(seq, oldseq) and oldo == offset:
332
+ return
333
+
334
+ self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
335
+ if seq is not None and len(seq) else
336
+ "[] 0 setdash\n")
337
+ if store:
338
+ self.linedash = (offset, seq)
339
+
340
+ def set_font(self, fontname, fontsize, store=True):
341
+ if (fontname, fontsize) != (self.fontname, self.fontsize):
342
+ self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
343
+ if store:
344
+ self.fontname = fontname
345
+ self.fontsize = fontsize
346
+
347
+ def create_hatch(self, hatch):
348
+ sidelen = 72
349
+ if hatch in self._hatches:
350
+ return self._hatches[hatch]
351
+ name = 'H%d' % len(self._hatches)
352
+ linewidth = mpl.rcParams['hatch.linewidth']
353
+ pageheight = self.height * 72
354
+ self._pswriter.write(f"""\
355
+ << /PatternType 1
356
+ /PaintType 2
357
+ /TilingType 2
358
+ /BBox[0 0 {sidelen:d} {sidelen:d}]
359
+ /XStep {sidelen:d}
360
+ /YStep {sidelen:d}
361
+
362
+ /PaintProc {{
363
+ pop
364
+ {linewidth:g} setlinewidth
365
+ {self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
366
+ gsave
367
+ fill
368
+ grestore
369
+ stroke
370
+ }} bind
371
+ >>
372
+ matrix
373
+ 0 {pageheight:g} translate
374
+ makepattern
375
+ /{name} exch def
376
+ """)
377
+ self._hatches[hatch] = name
378
+ return name
379
+
380
+ def get_image_magnification(self):
381
+ """
382
+ Get the factor by which to magnify images passed to draw_image.
383
+ Allows a backend to have images at a different resolution to other
384
+ artists.
385
+ """
386
+ return self.image_magnification
387
+
388
+ def _convert_path(self, path, transform, clip=False, simplify=None):
389
+ if clip:
390
+ clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
391
+ else:
392
+ clip = None
393
+ return _path.convert_to_string(
394
+ path, transform, clip, simplify, None,
395
+ 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
396
+
397
+ def _get_clip_cmd(self, gc):
398
+ clip = []
399
+ rect = gc.get_clip_rectangle()
400
+ if rect is not None:
401
+ clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
402
+ path, trf = gc.get_clip_path()
403
+ if path is not None:
404
+ key = (path, id(trf))
405
+ custom_clip_cmd = self._clip_paths.get(key)
406
+ if custom_clip_cmd is None:
407
+ custom_clip_cmd = "c%d" % len(self._clip_paths)
408
+ self._pswriter.write(f"""\
409
+ /{custom_clip_cmd} {{
410
+ {self._convert_path(path, trf, simplify=False)}
411
+ clip
412
+ newpath
413
+ }} bind def
414
+ """)
415
+ self._clip_paths[key] = custom_clip_cmd
416
+ clip.append(f"{custom_clip_cmd}\n")
417
+ return "".join(clip)
418
+
419
+ @_log_if_debug_on
420
+ def draw_image(self, gc, x, y, im, transform=None):
421
+ # docstring inherited
422
+
423
+ h, w = im.shape[:2]
424
+ imagecmd = "false 3 colorimage"
425
+ data = im[::-1, :, :3] # Vertically flipped rgb values.
426
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
427
+
428
+ if transform is None:
429
+ matrix = "1 0 0 1 0 0"
430
+ xscale = w / self.image_magnification
431
+ yscale = h / self.image_magnification
432
+ else:
433
+ matrix = " ".join(map(str, transform.frozen().to_values()))
434
+ xscale = 1.0
435
+ yscale = 1.0
436
+
437
+ self._pswriter.write(f"""\
438
+ gsave
439
+ {self._get_clip_cmd(gc)}
440
+ {x:g} {y:g} translate
441
+ [{matrix}] concat
442
+ {xscale:g} {yscale:g} scale
443
+ /DataString {w:d} string def
444
+ {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
445
+ {{
446
+ currentfile DataString readhexstring pop
447
+ }} bind {imagecmd}
448
+ {hexdata}
449
+ grestore
450
+ """)
451
+
452
+ @_log_if_debug_on
453
+ def draw_path(self, gc, path, transform, rgbFace=None):
454
+ # docstring inherited
455
+ clip = rgbFace is None and gc.get_hatch_path() is None
456
+ simplify = path.should_simplify and clip
457
+ ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
458
+ self._draw_ps(ps, gc, rgbFace)
459
+
460
+ @_log_if_debug_on
461
+ def draw_markers(
462
+ self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
463
+ # docstring inherited
464
+
465
+ ps_color = (
466
+ None
467
+ if self._is_transparent(rgbFace)
468
+ else f'{_nums_to_str(rgbFace[0])} setgray'
469
+ if rgbFace[0] == rgbFace[1] == rgbFace[2]
470
+ else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
471
+
472
+ # construct the generic marker command:
473
+
474
+ # don't want the translate to be global
475
+ ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
476
+
477
+ lw = gc.get_linewidth()
478
+ alpha = (gc.get_alpha()
479
+ if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
480
+ else gc.get_rgb()[3])
481
+ stroke = lw > 0 and alpha > 0
482
+ if stroke:
483
+ ps_cmd.append('%.1f setlinewidth' % lw)
484
+ ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
485
+ ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
486
+
487
+ ps_cmd.append(self._convert_path(marker_path, marker_trans,
488
+ simplify=False))
489
+
490
+ if rgbFace:
491
+ if stroke:
492
+ ps_cmd.append('gsave')
493
+ if ps_color:
494
+ ps_cmd.extend([ps_color, 'fill'])
495
+ if stroke:
496
+ ps_cmd.append('grestore')
497
+
498
+ if stroke:
499
+ ps_cmd.append('stroke')
500
+ ps_cmd.extend(['grestore', '} bind def'])
501
+
502
+ for vertices, code in path.iter_segments(
503
+ trans,
504
+ clip=(0, 0, self.width*72, self.height*72),
505
+ simplify=False):
506
+ if len(vertices):
507
+ x, y = vertices[-2:]
508
+ ps_cmd.append(f"{x:g} {y:g} o")
509
+
510
+ ps = '\n'.join(ps_cmd)
511
+ self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
512
+
513
+ @_log_if_debug_on
514
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
515
+ offsets, offset_trans, facecolors, edgecolors,
516
+ linewidths, linestyles, antialiaseds, urls,
517
+ offset_position):
518
+ # Is the optimization worth it? Rough calculation:
519
+ # cost of emitting a path in-line is
520
+ # (len_path + 2) * uses_per_path
521
+ # cost of definition+use is
522
+ # (len_path + 3) + 3 * uses_per_path
523
+ len_path = len(paths[0].vertices) if len(paths) > 0 else 0
524
+ uses_per_path = self._iter_collection_uses_per_path(
525
+ paths, all_transforms, offsets, facecolors, edgecolors)
526
+ should_do_optimization = \
527
+ len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
528
+ if not should_do_optimization:
529
+ return RendererBase.draw_path_collection(
530
+ self, gc, master_transform, paths, all_transforms,
531
+ offsets, offset_trans, facecolors, edgecolors,
532
+ linewidths, linestyles, antialiaseds, urls,
533
+ offset_position)
534
+
535
+ path_codes = []
536
+ for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
537
+ master_transform, paths, all_transforms)):
538
+ name = 'p%d_%d' % (self._path_collection_id, i)
539
+ path_bytes = self._convert_path(path, transform, simplify=False)
540
+ self._pswriter.write(f"""\
541
+ /{name} {{
542
+ newpath
543
+ translate
544
+ {path_bytes}
545
+ }} bind def
546
+ """)
547
+ path_codes.append(name)
548
+
549
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
550
+ gc, path_codes, offsets, offset_trans,
551
+ facecolors, edgecolors, linewidths, linestyles,
552
+ antialiaseds, urls, offset_position):
553
+ ps = f"{xo:g} {yo:g} {path_id}"
554
+ self._draw_ps(ps, gc0, rgbFace)
555
+
556
+ self._path_collection_id += 1
557
+
558
+ @_log_if_debug_on
559
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
560
+ # docstring inherited
561
+ if self._is_transparent(gc.get_rgb()):
562
+ return # Special handling for fully transparent.
563
+
564
+ if not hasattr(self, "psfrag"):
565
+ self._logwarn_once(
566
+ "The PS backend determines usetex status solely based on "
567
+ "rcParams['text.usetex'] and does not support having "
568
+ "usetex=True only for some elements; this element will thus "
569
+ "be rendered as if usetex=False.")
570
+ self.draw_text(gc, x, y, s, prop, angle, False, mtext)
571
+ return
572
+
573
+ w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
574
+ fontsize = prop.get_size_in_points()
575
+ thetext = 'psmarker%d' % self.textcnt
576
+ color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
577
+ fontcmd = {'sans-serif': r'{\sffamily %s}',
578
+ 'monospace': r'{\ttfamily %s}'}.get(
579
+ mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
580
+ s = fontcmd % s
581
+ tex = r'\color[rgb]{%s} %s' % (color, s)
582
+
583
+ # Stick to bottom-left alignment, so subtract descent from the text-normal
584
+ # direction since text is normally positioned by its baseline.
585
+ rangle = np.radians(angle + 90)
586
+ pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
587
+ self.psfrag.append(
588
+ r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
589
+ thetext, angle, fontsize, fontsize*1.25, tex))
590
+
591
+ self._pswriter.write(f"""\
592
+ gsave
593
+ {pos} moveto
594
+ ({thetext})
595
+ show
596
+ grestore
597
+ """)
598
+ self.textcnt += 1
599
+
600
+ @_log_if_debug_on
601
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
602
+ # docstring inherited
603
+
604
+ if self._is_transparent(gc.get_rgb()):
605
+ return # Special handling for fully transparent.
606
+
607
+ if ismath == 'TeX':
608
+ return self.draw_tex(gc, x, y, s, prop, angle)
609
+
610
+ if ismath:
611
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
612
+
613
+ stream = [] # list of (ps_name, x, char_name)
614
+
615
+ if mpl.rcParams['ps.useafm']:
616
+ font = self._get_font_afm(prop)
617
+ ps_name = (font.postscript_name.encode("ascii", "replace")
618
+ .decode("ascii"))
619
+ scale = 0.001 * prop.get_size_in_points()
620
+ thisx = 0
621
+ last_name = None # kerns returns 0 for None.
622
+ for c in s:
623
+ name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
624
+ try:
625
+ width = font.get_width_from_char_name(name)
626
+ except KeyError:
627
+ name = 'question'
628
+ width = font.get_width_char('?')
629
+ kern = font.get_kern_dist_from_name(last_name, name)
630
+ last_name = name
631
+ thisx += kern * scale
632
+ stream.append((ps_name, thisx, name))
633
+ thisx += width * scale
634
+
635
+ else:
636
+ font = self._get_font_ttf(prop)
637
+ self._character_tracker.track(font, s)
638
+ for item in _text_helpers.layout(s, font):
639
+ ps_name = (item.ft_object.postscript_name
640
+ .encode("ascii", "replace").decode("ascii"))
641
+ glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
642
+ stream.append((ps_name, item.x, glyph_name))
643
+ self.set_color(*gc.get_rgb())
644
+
645
+ for ps_name, group in itertools. \
646
+ groupby(stream, lambda entry: entry[0]):
647
+ self.set_font(ps_name, prop.get_size_in_points(), False)
648
+ thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
649
+ for _, x, name in group)
650
+ self._pswriter.write(f"""\
651
+ gsave
652
+ {self._get_clip_cmd(gc)}
653
+ {x:g} {y:g} translate
654
+ {angle:g} rotate
655
+ {thetext}
656
+ grestore
657
+ """)
658
+
659
+ @_log_if_debug_on
660
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
661
+ """Draw the math text using matplotlib.mathtext."""
662
+ width, height, descent, glyphs, rects = \
663
+ self._text2path.mathtext_parser.parse(s, 72, prop)
664
+ self.set_color(*gc.get_rgb())
665
+ self._pswriter.write(
666
+ f"gsave\n"
667
+ f"{x:g} {y:g} translate\n"
668
+ f"{angle:g} rotate\n")
669
+ lastfont = None
670
+ for font, fontsize, num, ox, oy in glyphs:
671
+ self._character_tracker.track_glyph(font, num)
672
+ if (font.postscript_name, fontsize) != lastfont:
673
+ lastfont = font.postscript_name, fontsize
674
+ self._pswriter.write(
675
+ f"/{font.postscript_name} {fontsize} selectfont\n")
676
+ glyph_name = (
677
+ font.get_name_char(chr(num)) if isinstance(font, AFM) else
678
+ font.get_glyph_name(font.get_char_index(num)))
679
+ self._pswriter.write(
680
+ f"{ox:g} {oy:g} moveto\n"
681
+ f"/{glyph_name} glyphshow\n")
682
+ for ox, oy, w, h in rects:
683
+ self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
684
+ self._pswriter.write("grestore\n")
685
+
686
+ @_log_if_debug_on
687
+ def draw_gouraud_triangles(self, gc, points, colors, trans):
688
+ assert len(points) == len(colors)
689
+ if len(points) == 0:
690
+ return
691
+ assert points.ndim == 3
692
+ assert points.shape[1] == 3
693
+ assert points.shape[2] == 2
694
+ assert colors.ndim == 3
695
+ assert colors.shape[1] == 3
696
+ assert colors.shape[2] == 4
697
+
698
+ shape = points.shape
699
+ flat_points = points.reshape((shape[0] * shape[1], 2))
700
+ flat_points = trans.transform(flat_points)
701
+ flat_colors = colors.reshape((shape[0] * shape[1], 4))
702
+ points_min = np.min(flat_points, axis=0) - (1 << 12)
703
+ points_max = np.max(flat_points, axis=0) + (1 << 12)
704
+ factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
705
+
706
+ xmin, ymin = points_min
707
+ xmax, ymax = points_max
708
+
709
+ data = np.empty(
710
+ shape[0] * shape[1],
711
+ dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
712
+ data['flags'] = 0
713
+ data['points'] = (flat_points - points_min) * factor
714
+ data['colors'] = flat_colors[:, :3] * 255.0
715
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
716
+
717
+ self._pswriter.write(f"""\
718
+ gsave
719
+ << /ShadingType 4
720
+ /ColorSpace [/DeviceRGB]
721
+ /BitsPerCoordinate 32
722
+ /BitsPerComponent 8
723
+ /BitsPerFlag 8
724
+ /AntiAlias true
725
+ /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
726
+ /DataSource <
727
+ {hexdata}
728
+ >
729
+ >>
730
+ shfill
731
+ grestore
732
+ """)
733
+
734
+ def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
735
+ """
736
+ Emit the PostScript snippet *ps* with all the attributes from *gc*
737
+ applied. *ps* must consist of PostScript commands to construct a path.
738
+
739
+ The *fill* and/or *stroke* kwargs can be set to False if the *ps*
740
+ string already includes filling and/or stroking, in which case
741
+ `_draw_ps` is just supplying properties and clipping.
742
+ """
743
+ write = self._pswriter.write
744
+ mightstroke = (gc.get_linewidth() > 0
745
+ and not self._is_transparent(gc.get_rgb()))
746
+ if not mightstroke:
747
+ stroke = False
748
+ if self._is_transparent(rgbFace):
749
+ fill = False
750
+ hatch = gc.get_hatch()
751
+
752
+ if mightstroke:
753
+ self.set_linewidth(gc.get_linewidth())
754
+ self.set_linejoin(gc.get_joinstyle())
755
+ self.set_linecap(gc.get_capstyle())
756
+ self.set_linedash(*gc.get_dashes())
757
+ if mightstroke or hatch:
758
+ self.set_color(*gc.get_rgb()[:3])
759
+ write('gsave\n')
760
+
761
+ write(self._get_clip_cmd(gc))
762
+
763
+ write(ps.strip())
764
+ write("\n")
765
+
766
+ if fill:
767
+ if stroke or hatch:
768
+ write("gsave\n")
769
+ self.set_color(*rgbFace[:3], store=False)
770
+ write("fill\n")
771
+ if stroke or hatch:
772
+ write("grestore\n")
773
+
774
+ if hatch:
775
+ hatch_name = self.create_hatch(hatch)
776
+ write("gsave\n")
777
+ write(_nums_to_str(*gc.get_hatch_color()[:3]))
778
+ write(f" {hatch_name} setpattern fill grestore\n")
779
+
780
+ if stroke:
781
+ write("stroke\n")
782
+
783
+ write("grestore\n")
784
+
785
+
786
+ class _Orientation(Enum):
787
+ portrait, landscape = range(2)
788
+
789
+ def swap_if_landscape(self, shape):
790
+ return shape[::-1] if self.name == "landscape" else shape
791
+
792
+
793
+ class FigureCanvasPS(FigureCanvasBase):
794
+ fixed_dpi = 72
795
+ filetypes = {'ps': 'Postscript',
796
+ 'eps': 'Encapsulated Postscript'}
797
+
798
+ def get_default_filetype(self):
799
+ return 'ps'
800
+
801
+ def _print_ps(
802
+ self, fmt, outfile, *,
803
+ metadata=None, papertype=None, orientation='portrait',
804
+ bbox_inches_restore=None, **kwargs):
805
+
806
+ dpi = self.figure.dpi
807
+ self.figure.dpi = 72 # Override the dpi kwarg
808
+
809
+ dsc_comments = {}
810
+ if isinstance(outfile, (str, os.PathLike)):
811
+ filename = pathlib.Path(outfile).name
812
+ dsc_comments["Title"] = \
813
+ filename.encode("ascii", "replace").decode("ascii")
814
+ dsc_comments["Creator"] = (metadata or {}).get(
815
+ "Creator",
816
+ f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
817
+ # See https://reproducible-builds.org/specs/source-date-epoch/
818
+ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
819
+ dsc_comments["CreationDate"] = (
820
+ datetime.datetime.fromtimestamp(
821
+ int(source_date_epoch),
822
+ datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
823
+ if source_date_epoch
824
+ else time.ctime())
825
+ dsc_comments = "\n".join(
826
+ f"%%{k}: {v}" for k, v in dsc_comments.items())
827
+
828
+ if papertype is None:
829
+ papertype = mpl.rcParams['ps.papersize']
830
+ papertype = papertype.lower()
831
+ _api.check_in_list(['figure', 'auto', *papersize], papertype=papertype)
832
+
833
+ orientation = _api.check_getitem(
834
+ _Orientation, orientation=orientation.lower())
835
+
836
+ printer = (self._print_figure_tex
837
+ if mpl.rcParams['text.usetex'] else
838
+ self._print_figure)
839
+ printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
840
+ orientation=orientation, papertype=papertype,
841
+ bbox_inches_restore=bbox_inches_restore, **kwargs)
842
+
843
+ def _print_figure(
844
+ self, fmt, outfile, *,
845
+ dpi, dsc_comments, orientation, papertype,
846
+ bbox_inches_restore=None):
847
+ """
848
+ Render the figure to a filesystem path or a file-like object.
849
+
850
+ Parameters are as for `.print_figure`, except that *dsc_comments* is a
851
+ string containing Document Structuring Convention comments,
852
+ generated from the *metadata* parameter to `.print_figure`.
853
+ """
854
+ is_eps = fmt == 'eps'
855
+ if not (isinstance(outfile, (str, os.PathLike))
856
+ or is_writable_file_like(outfile)):
857
+ raise ValueError("outfile must be a path or a file-like object")
858
+
859
+ # find the appropriate papertype
860
+ width, height = self.figure.get_size_inches()
861
+ if papertype == 'auto':
862
+ papertype = _get_papertype(*orientation.swap_if_landscape((width, height)))
863
+
864
+ if is_eps or papertype == 'figure':
865
+ paper_width, paper_height = width, height
866
+ else:
867
+ paper_width, paper_height = orientation.swap_if_landscape(
868
+ papersize[papertype])
869
+
870
+ # center the figure on the paper
871
+ xo = 72 * 0.5 * (paper_width - width)
872
+ yo = 72 * 0.5 * (paper_height - height)
873
+
874
+ llx = xo
875
+ lly = yo
876
+ urx = llx + self.figure.bbox.width
877
+ ury = lly + self.figure.bbox.height
878
+ rotation = 0
879
+ if orientation is _Orientation.landscape:
880
+ llx, lly, urx, ury = lly, llx, ury, urx
881
+ xo, yo = 72 * paper_height - yo, xo
882
+ rotation = 90
883
+ bbox = (llx, lly, urx, ury)
884
+
885
+ self._pswriter = StringIO()
886
+
887
+ # mixed mode rendering
888
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
889
+ renderer = MixedModeRenderer(
890
+ self.figure, width, height, dpi, ps_renderer,
891
+ bbox_inches_restore=bbox_inches_restore)
892
+
893
+ self.figure.draw(renderer)
894
+
895
+ def print_figure_impl(fh):
896
+ # write the PostScript headers
897
+ if is_eps:
898
+ print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
899
+ else:
900
+ print("%!PS-Adobe-3.0", file=fh)
901
+ if papertype != 'figure':
902
+ print(f"%%DocumentPaperSizes: {papertype}", file=fh)
903
+ print("%%Pages: 1", file=fh)
904
+ print(f"%%LanguageLevel: 3\n"
905
+ f"{dsc_comments}\n"
906
+ f"%%Orientation: {orientation.name}\n"
907
+ f"{_get_bbox_header(bbox)}\n"
908
+ f"%%EndComments\n",
909
+ end="", file=fh)
910
+
911
+ Ndict = len(_psDefs)
912
+ print("%%BeginProlog", file=fh)
913
+ if not mpl.rcParams['ps.useafm']:
914
+ Ndict += len(ps_renderer._character_tracker.used)
915
+ print("/mpldict %d dict def" % Ndict, file=fh)
916
+ print("mpldict begin", file=fh)
917
+ print("\n".join(_psDefs), file=fh)
918
+ if not mpl.rcParams['ps.useafm']:
919
+ for font_path, chars \
920
+ in ps_renderer._character_tracker.used.items():
921
+ if not chars:
922
+ continue
923
+ fonttype = mpl.rcParams['ps.fonttype']
924
+ # Can't use more than 255 chars from a single Type 3 font.
925
+ if len(chars) > 255:
926
+ fonttype = 42
927
+ fh.flush()
928
+ if fonttype == 3:
929
+ fh.write(_font_to_ps_type3(font_path, chars))
930
+ else: # Type 42 only.
931
+ _font_to_ps_type42(font_path, chars, fh)
932
+ print("end", file=fh)
933
+ print("%%EndProlog", file=fh)
934
+
935
+ if not is_eps:
936
+ print("%%Page: 1 1", file=fh)
937
+ print("mpldict begin", file=fh)
938
+
939
+ print("%s translate" % _nums_to_str(xo, yo), file=fh)
940
+ if rotation:
941
+ print("%d rotate" % rotation, file=fh)
942
+ print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
943
+
944
+ # write the figure
945
+ print(self._pswriter.getvalue(), file=fh)
946
+
947
+ # write the trailer
948
+ print("end", file=fh)
949
+ print("showpage", file=fh)
950
+ if not is_eps:
951
+ print("%%EOF", file=fh)
952
+ fh.flush()
953
+
954
+ if mpl.rcParams['ps.usedistiller']:
955
+ # We are going to use an external program to process the output.
956
+ # Write to a temporary file.
957
+ with TemporaryDirectory() as tmpdir:
958
+ tmpfile = os.path.join(tmpdir, "tmp.ps")
959
+ with open(tmpfile, 'w', encoding='latin-1') as fh:
960
+ print_figure_impl(fh)
961
+ if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
962
+ _try_distill(gs_distill,
963
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
964
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
965
+ _try_distill(xpdf_distill,
966
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
967
+ _move_path_to_path_or_stream(tmpfile, outfile)
968
+
969
+ else: # Write directly to outfile.
970
+ with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
971
+ if not file_requires_unicode(file):
972
+ file = codecs.getwriter("latin-1")(file)
973
+ print_figure_impl(file)
974
+
975
+ def _print_figure_tex(
976
+ self, fmt, outfile, *,
977
+ dpi, dsc_comments, orientation, papertype,
978
+ bbox_inches_restore=None):
979
+ """
980
+ If :rc:`text.usetex` is True, a temporary pair of tex/eps files
981
+ are created to allow tex to manage the text layout via the PSFrags
982
+ package. These files are processed to yield the final ps or eps file.
983
+
984
+ The rest of the behavior is as for `._print_figure`.
985
+ """
986
+ is_eps = fmt == 'eps'
987
+
988
+ width, height = self.figure.get_size_inches()
989
+ xo = 0
990
+ yo = 0
991
+
992
+ llx = xo
993
+ lly = yo
994
+ urx = llx + self.figure.bbox.width
995
+ ury = lly + self.figure.bbox.height
996
+ bbox = (llx, lly, urx, ury)
997
+
998
+ self._pswriter = StringIO()
999
+
1000
+ # mixed mode rendering
1001
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
1002
+ renderer = MixedModeRenderer(self.figure,
1003
+ width, height, dpi, ps_renderer,
1004
+ bbox_inches_restore=bbox_inches_restore)
1005
+
1006
+ self.figure.draw(renderer)
1007
+
1008
+ # write to a temp file, we'll move it to outfile when done
1009
+ with TemporaryDirectory() as tmpdir:
1010
+ tmppath = pathlib.Path(tmpdir, "tmp.ps")
1011
+ tmppath.write_text(
1012
+ f"""\
1013
+ %!PS-Adobe-3.0 EPSF-3.0
1014
+ %%LanguageLevel: 3
1015
+ {dsc_comments}
1016
+ {_get_bbox_header(bbox)}
1017
+ %%EndComments
1018
+ %%BeginProlog
1019
+ /mpldict {len(_psDefs)} dict def
1020
+ mpldict begin
1021
+ {"".join(_psDefs)}
1022
+ end
1023
+ %%EndProlog
1024
+ mpldict begin
1025
+ {_nums_to_str(xo, yo)} translate
1026
+ 0 0 {_nums_to_str(width*72, height*72)} rectclip
1027
+ {self._pswriter.getvalue()}
1028
+ end
1029
+ showpage
1030
+ """,
1031
+ encoding="latin-1")
1032
+
1033
+ if orientation is _Orientation.landscape: # now, ready to rotate
1034
+ width, height = height, width
1035
+ bbox = (lly, llx, ury, urx)
1036
+
1037
+ # set the paper size to the figure size if is_eps. The
1038
+ # resulting ps file has the given size with correct bounding
1039
+ # box so that there is no need to call 'pstoeps'
1040
+ if is_eps or papertype == 'figure':
1041
+ paper_width, paper_height = orientation.swap_if_landscape(
1042
+ self.figure.get_size_inches())
1043
+ else:
1044
+ if papertype == 'auto':
1045
+ papertype = _get_papertype(width, height)
1046
+ paper_width, paper_height = papersize[papertype]
1047
+
1048
+ psfrag_rotated = _convert_psfrags(
1049
+ tmppath, ps_renderer.psfrag, paper_width, paper_height,
1050
+ orientation.name)
1051
+
1052
+ if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
1053
+ or mpl.rcParams['text.usetex']):
1054
+ _try_distill(gs_distill,
1055
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1056
+ rotated=psfrag_rotated)
1057
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
1058
+ _try_distill(xpdf_distill,
1059
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1060
+ rotated=psfrag_rotated)
1061
+
1062
+ _move_path_to_path_or_stream(tmppath, outfile)
1063
+
1064
+ print_ps = functools.partialmethod(_print_ps, "ps")
1065
+ print_eps = functools.partialmethod(_print_ps, "eps")
1066
+
1067
+ def draw(self):
1068
+ self.figure.draw_without_rendering()
1069
+ return super().draw()
1070
+
1071
+
1072
+ def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
1073
+ """
1074
+ When we want to use the LaTeX backend with postscript, we write PSFrag tags
1075
+ to a temporary postscript file, each one marking a position for LaTeX to
1076
+ render some text. convert_psfrags generates a LaTeX document containing the
1077
+ commands to convert those tags to text. LaTeX/dvips produces the postscript
1078
+ file that includes the actual text.
1079
+ """
1080
+ with mpl.rc_context({
1081
+ "text.latex.preamble":
1082
+ mpl.rcParams["text.latex.preamble"] +
1083
+ mpl.texmanager._usepackage_if_not_loaded("color") +
1084
+ mpl.texmanager._usepackage_if_not_loaded("graphicx") +
1085
+ mpl.texmanager._usepackage_if_not_loaded("psfrag") +
1086
+ r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
1087
+ % {"width": paper_width, "height": paper_height}
1088
+ }):
1089
+ dvifile = TexManager().make_dvi(
1090
+ "\n"
1091
+ r"\begin{figure}""\n"
1092
+ r" \centering\leavevmode""\n"
1093
+ r" %(psfrags)s""\n"
1094
+ r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
1095
+ r"\end{figure}"
1096
+ % {
1097
+ "psfrags": "\n".join(psfrags),
1098
+ "angle": 90 if orientation == 'landscape' else 0,
1099
+ "epsfile": tmppath.resolve().as_posix(),
1100
+ },
1101
+ fontsize=10) # tex's default fontsize.
1102
+
1103
+ with TemporaryDirectory() as tmpdir:
1104
+ psfile = os.path.join(tmpdir, "tmp.ps")
1105
+ cbook._check_and_log_subprocess(
1106
+ ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
1107
+ shutil.move(psfile, tmppath)
1108
+
1109
+ # check if the dvips created a ps in landscape paper. Somehow,
1110
+ # above latex+dvips results in a ps file in a landscape mode for a
1111
+ # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
1112
+ # bounding box of the final output got messed up. We check see if
1113
+ # the generated ps file is in landscape and return this
1114
+ # information. The return value is used in pstoeps step to recover
1115
+ # the correct bounding box. 2010-06-05 JJL
1116
+ with open(tmppath) as fh:
1117
+ psfrag_rotated = "Landscape" in fh.read(1000)
1118
+ return psfrag_rotated
1119
+
1120
+
1121
+ def _try_distill(func, tmppath, *args, **kwargs):
1122
+ try:
1123
+ func(str(tmppath), *args, **kwargs)
1124
+ except mpl.ExecutableNotFoundError as exc:
1125
+ _log.warning("%s. Distillation step skipped.", exc)
1126
+
1127
+
1128
+ def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1129
+ """
1130
+ Use ghostscript's pswrite or epswrite device to distill a file.
1131
+ This yields smaller files without illegal encapsulated postscript
1132
+ operators. The output is low-level, converting text to outlines.
1133
+ """
1134
+
1135
+ if eps:
1136
+ paper_option = ["-dEPSCrop"]
1137
+ elif ptype == "figure":
1138
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1139
+ # corner corresponds with paper size.
1140
+ paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
1141
+ f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
1142
+ else:
1143
+ paper_option = [f"-sPAPERSIZE={ptype}"]
1144
+
1145
+ psfile = tmpfile + '.ps'
1146
+ dpi = mpl.rcParams['ps.distiller.res']
1147
+
1148
+ cbook._check_and_log_subprocess(
1149
+ [mpl._get_executable_info("gs").executable,
1150
+ "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
1151
+ *paper_option, f"-sOutputFile={psfile}", tmpfile],
1152
+ _log)
1153
+
1154
+ os.remove(tmpfile)
1155
+ shutil.move(psfile, tmpfile)
1156
+
1157
+ # While it is best if above steps preserve the original bounding
1158
+ # box, there seem to be cases when it is not. For those cases,
1159
+ # the original bbox can be restored during the pstoeps step.
1160
+
1161
+ if eps:
1162
+ # For some versions of gs, above steps result in a ps file where the
1163
+ # original bbox is no more correct. Do not adjust bbox for now.
1164
+ pstoeps(tmpfile, bbox, rotated=rotated)
1165
+
1166
+
1167
+ def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1168
+ """
1169
+ Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
1170
+ This yields smaller files without illegal encapsulated postscript
1171
+ operators. This distiller is preferred, generating high-level postscript
1172
+ output that treats text as text.
1173
+ """
1174
+ mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
1175
+ mpl._get_executable_info("pdftops")
1176
+
1177
+ if eps:
1178
+ paper_option = ["-dEPSCrop"]
1179
+ elif ptype == "figure":
1180
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1181
+ # corner corresponds with paper size.
1182
+ paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
1183
+ f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
1184
+ else:
1185
+ paper_option = [f"-sPAPERSIZE#{ptype}"]
1186
+
1187
+ with TemporaryDirectory() as tmpdir:
1188
+ tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
1189
+ tmpps = pathlib.Path(tmpdir, "tmp.ps")
1190
+ # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
1191
+ # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
1192
+ cbook._check_and_log_subprocess(
1193
+ ["ps2pdf",
1194
+ "-dAutoFilterColorImages#false",
1195
+ "-dAutoFilterGrayImages#false",
1196
+ "-sAutoRotatePages#None",
1197
+ "-sGrayImageFilter#FlateEncode",
1198
+ "-sColorImageFilter#FlateEncode",
1199
+ *paper_option,
1200
+ tmpfile, tmppdf], _log)
1201
+ cbook._check_and_log_subprocess(
1202
+ ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
1203
+ shutil.move(tmpps, tmpfile)
1204
+ if eps:
1205
+ pstoeps(tmpfile)
1206
+
1207
+
1208
+ @_api.deprecated("3.9")
1209
+ def get_bbox_header(lbrt, rotated=False):
1210
+ """
1211
+ Return a postscript header string for the given bbox lbrt=(l, b, r, t).
1212
+ Optionally, return rotate command.
1213
+ """
1214
+ return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "")
1215
+
1216
+
1217
+ def _get_bbox_header(lbrt):
1218
+ """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t)."""
1219
+ l, b, r, t = lbrt
1220
+ return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n"
1221
+ f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}")
1222
+
1223
+
1224
+ def _get_rotate_command(lbrt):
1225
+ """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t)."""
1226
+ l, b, r, t = lbrt
1227
+ return f"{l+r:.2f} {0:.2f} translate\n90 rotate"
1228
+
1229
+
1230
+ def pstoeps(tmpfile, bbox=None, rotated=False):
1231
+ """
1232
+ Convert the postscript to encapsulated postscript. The bbox of
1233
+ the eps file will be replaced with the given *bbox* argument. If
1234
+ None, original bbox will be used.
1235
+ """
1236
+
1237
+ epsfile = tmpfile + '.eps'
1238
+ with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
1239
+ write = epsh.write
1240
+ # Modify the header:
1241
+ for line in tmph:
1242
+ if line.startswith(b'%!PS'):
1243
+ write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
1244
+ if bbox:
1245
+ write(_get_bbox_header(bbox).encode('ascii') + b'\n')
1246
+ elif line.startswith(b'%%EndComments'):
1247
+ write(line)
1248
+ write(b'%%BeginProlog\n'
1249
+ b'save\n'
1250
+ b'countdictstack\n'
1251
+ b'mark\n'
1252
+ b'newpath\n'
1253
+ b'/showpage {} def\n'
1254
+ b'/setpagedevice {pop} def\n'
1255
+ b'%%EndProlog\n'
1256
+ b'%%Page 1 1\n')
1257
+ if rotated: # The output eps file need to be rotated.
1258
+ write(_get_rotate_command(bbox).encode('ascii') + b'\n')
1259
+ break
1260
+ elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
1261
+ b'%%DocumentMedia', b'%%Pages')):
1262
+ pass
1263
+ else:
1264
+ write(line)
1265
+ # Now rewrite the rest of the file, and modify the trailer.
1266
+ # This is done in a second loop such that the header of the embedded
1267
+ # eps file is not modified.
1268
+ for line in tmph:
1269
+ if line.startswith(b'%%EOF'):
1270
+ write(b'cleartomark\n'
1271
+ b'countdictstack\n'
1272
+ b'exch sub { end } repeat\n'
1273
+ b'restore\n'
1274
+ b'showpage\n'
1275
+ b'%%EOF\n')
1276
+ elif line.startswith(b'%%PageBoundingBox'):
1277
+ pass
1278
+ else:
1279
+ write(line)
1280
+
1281
+ os.remove(tmpfile)
1282
+ shutil.move(epsfile, tmpfile)
1283
+
1284
+
1285
+ FigureManagerPS = FigureManagerBase
1286
+
1287
+
1288
+ # The following Python dictionary psDefs contains the entries for the
1289
+ # PostScript dictionary mpldict. This dictionary implements most of
1290
+ # the matplotlib primitives and some abbreviations.
1291
+ #
1292
+ # References:
1293
+ # https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
1294
+ # http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
1295
+ # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
1296
+ #
1297
+
1298
+ # The usage comments use the notation of the operator summary
1299
+ # in the PostScript Language reference manual.
1300
+ _psDefs = [
1301
+ # name proc *_d* -
1302
+ # Note that this cannot be bound to /d, because when embedding a Type3 font
1303
+ # we may want to define a "d" glyph using "/d{...} d" which would locally
1304
+ # overwrite the definition.
1305
+ "/_d { bind def } bind def",
1306
+ # x y *m* -
1307
+ "/m { moveto } _d",
1308
+ # x y *l* -
1309
+ "/l { lineto } _d",
1310
+ # x y *r* -
1311
+ "/r { rlineto } _d",
1312
+ # x1 y1 x2 y2 x y *c* -
1313
+ "/c { curveto } _d",
1314
+ # *cl* -
1315
+ "/cl { closepath } _d",
1316
+ # *ce* -
1317
+ "/ce { closepath eofill } _d",
1318
+ # wx wy llx lly urx ury *setcachedevice* -
1319
+ "/sc { setcachedevice } _d",
1320
+ ]
1321
+
1322
+
1323
+ @_Backend.export
1324
+ class _BackendPS(_Backend):
1325
+ backend_version = 'Level II'
1326
+ FigureCanvas = FigureCanvasPS
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import os
3
+ import sys
4
+ import traceback
5
+
6
+ import matplotlib as mpl
7
+ from matplotlib import _api, backend_tools, cbook
8
+ from matplotlib._pylab_helpers import Gcf
9
+ from matplotlib.backend_bases import (
10
+ _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
11
+ TimerBase, cursors, ToolContainerBase, MouseButton,
12
+ CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent,
13
+ _allow_interrupt)
14
+ import matplotlib.backends.qt_editor.figureoptions as figureoptions
15
+ from . import qt_compat
16
+ from .qt_compat import (
17
+ QtCore, QtGui, QtWidgets, __version__, QT_API, _to_int, _isdeleted)
18
+
19
+
20
+ # SPECIAL_KEYS are Qt::Key that do *not* return their Unicode name
21
+ # instead they have manually specified names.
22
+ SPECIAL_KEYS = {
23
+ _to_int(getattr(QtCore.Qt.Key, k)): v for k, v in [
24
+ ("Key_Escape", "escape"),
25
+ ("Key_Tab", "tab"),
26
+ ("Key_Backspace", "backspace"),
27
+ ("Key_Return", "enter"),
28
+ ("Key_Enter", "enter"),
29
+ ("Key_Insert", "insert"),
30
+ ("Key_Delete", "delete"),
31
+ ("Key_Pause", "pause"),
32
+ ("Key_SysReq", "sysreq"),
33
+ ("Key_Clear", "clear"),
34
+ ("Key_Home", "home"),
35
+ ("Key_End", "end"),
36
+ ("Key_Left", "left"),
37
+ ("Key_Up", "up"),
38
+ ("Key_Right", "right"),
39
+ ("Key_Down", "down"),
40
+ ("Key_PageUp", "pageup"),
41
+ ("Key_PageDown", "pagedown"),
42
+ ("Key_Shift", "shift"),
43
+ # In macOS, the control and super (aka cmd/apple) keys are switched.
44
+ ("Key_Control", "control" if sys.platform != "darwin" else "cmd"),
45
+ ("Key_Meta", "meta" if sys.platform != "darwin" else "control"),
46
+ ("Key_Alt", "alt"),
47
+ ("Key_CapsLock", "caps_lock"),
48
+ ("Key_F1", "f1"),
49
+ ("Key_F2", "f2"),
50
+ ("Key_F3", "f3"),
51
+ ("Key_F4", "f4"),
52
+ ("Key_F5", "f5"),
53
+ ("Key_F6", "f6"),
54
+ ("Key_F7", "f7"),
55
+ ("Key_F8", "f8"),
56
+ ("Key_F9", "f9"),
57
+ ("Key_F10", "f10"),
58
+ ("Key_F10", "f11"),
59
+ ("Key_F12", "f12"),
60
+ ("Key_Super_L", "super"),
61
+ ("Key_Super_R", "super"),
62
+ ]
63
+ }
64
+ # Define which modifier keys are collected on keyboard events.
65
+ # Elements are (Qt::KeyboardModifiers, Qt::Key) tuples.
66
+ # Order determines the modifier order (ctrl+alt+...) reported by Matplotlib.
67
+ _MODIFIER_KEYS = [
68
+ (_to_int(getattr(QtCore.Qt.KeyboardModifier, mod)),
69
+ _to_int(getattr(QtCore.Qt.Key, key)))
70
+ for mod, key in [
71
+ ("ControlModifier", "Key_Control"),
72
+ ("AltModifier", "Key_Alt"),
73
+ ("ShiftModifier", "Key_Shift"),
74
+ ("MetaModifier", "Key_Meta"),
75
+ ]
76
+ ]
77
+ cursord = {
78
+ k: getattr(QtCore.Qt.CursorShape, v) for k, v in [
79
+ (cursors.MOVE, "SizeAllCursor"),
80
+ (cursors.HAND, "PointingHandCursor"),
81
+ (cursors.POINTER, "ArrowCursor"),
82
+ (cursors.SELECT_REGION, "CrossCursor"),
83
+ (cursors.WAIT, "WaitCursor"),
84
+ (cursors.RESIZE_HORIZONTAL, "SizeHorCursor"),
85
+ (cursors.RESIZE_VERTICAL, "SizeVerCursor"),
86
+ ]
87
+ }
88
+
89
+
90
+ # lru_cache keeps a reference to the QApplication instance, keeping it from
91
+ # being GC'd.
92
+ @functools.lru_cache(1)
93
+ def _create_qApp():
94
+ app = QtWidgets.QApplication.instance()
95
+
96
+ # Create a new QApplication and configure it if none exists yet, as only
97
+ # one QApplication can exist at a time.
98
+ if app is None:
99
+ # display_is_valid returns False only if on Linux and neither X11
100
+ # nor Wayland display can be opened.
101
+ if not mpl._c_internal_utils.display_is_valid():
102
+ raise RuntimeError('Invalid DISPLAY variable')
103
+
104
+ # Check to make sure a QApplication from a different major version
105
+ # of Qt is not instantiated in the process
106
+ if QT_API in {'PyQt6', 'PySide6'}:
107
+ other_bindings = ('PyQt5', 'PySide2')
108
+ qt_version = 6
109
+ elif QT_API in {'PyQt5', 'PySide2'}:
110
+ other_bindings = ('PyQt6', 'PySide6')
111
+ qt_version = 5
112
+ else:
113
+ raise RuntimeError("Should never be here")
114
+
115
+ for binding in other_bindings:
116
+ mod = sys.modules.get(f'{binding}.QtWidgets')
117
+ if mod is not None and mod.QApplication.instance() is not None:
118
+ other_core = sys.modules.get(f'{binding}.QtCore')
119
+ _api.warn_external(
120
+ f'Matplotlib is using {QT_API} which wraps '
121
+ f'{QtCore.qVersion()} however an instantiated '
122
+ f'QApplication from {binding} which wraps '
123
+ f'{other_core.qVersion()} exists. Mixing Qt major '
124
+ 'versions may not work as expected.'
125
+ )
126
+ break
127
+ if qt_version == 5:
128
+ try:
129
+ QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
130
+ except AttributeError: # Only for Qt>=5.6, <6.
131
+ pass
132
+ try:
133
+ QtWidgets.QApplication.setHighDpiScaleFactorRoundingPolicy(
134
+ QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
135
+ except AttributeError: # Only for Qt>=5.14.
136
+ pass
137
+ app = QtWidgets.QApplication(["matplotlib"])
138
+ if sys.platform == "darwin":
139
+ image = str(cbook._get_data_path('images/matplotlib.svg'))
140
+ icon = QtGui.QIcon(image)
141
+ app.setWindowIcon(icon)
142
+ app.setQuitOnLastWindowClosed(True)
143
+ cbook._setup_new_guiapp()
144
+ if qt_version == 5:
145
+ app.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
146
+
147
+ return app
148
+
149
+
150
+ def _allow_interrupt_qt(qapp_or_eventloop):
151
+ """A context manager that allows terminating a plot by sending a SIGINT."""
152
+
153
+ # Use QSocketNotifier to read the socketpair while the Qt event loop runs.
154
+
155
+ def prepare_notifier(rsock):
156
+ sn = QtCore.QSocketNotifier(rsock.fileno(), QtCore.QSocketNotifier.Type.Read)
157
+
158
+ @sn.activated.connect
159
+ def _may_clear_sock():
160
+ # Running a Python function on socket activation gives the interpreter a
161
+ # chance to handle the signal in Python land. We also need to drain the
162
+ # socket with recv() to re-arm it, because it will be written to as part of
163
+ # the wakeup. (We need this in case set_wakeup_fd catches a signal other
164
+ # than SIGINT and we shall continue waiting.)
165
+ try:
166
+ rsock.recv(1)
167
+ except BlockingIOError:
168
+ # This may occasionally fire too soon or more than once on Windows, so
169
+ # be forgiving about reading an empty socket.
170
+ pass
171
+
172
+ return sn # Actually keep the notifier alive.
173
+
174
+ def handle_sigint():
175
+ if hasattr(qapp_or_eventloop, 'closeAllWindows'):
176
+ qapp_or_eventloop.closeAllWindows()
177
+ qapp_or_eventloop.quit()
178
+
179
+ return _allow_interrupt(prepare_notifier, handle_sigint)
180
+
181
+
182
+ class TimerQT(TimerBase):
183
+ """Subclass of `.TimerBase` using QTimer events."""
184
+
185
+ def __init__(self, *args, **kwargs):
186
+ # Create a new timer and connect the timeout() signal to the
187
+ # _on_timer method.
188
+ self._timer = QtCore.QTimer()
189
+ self._timer.timeout.connect(self._on_timer)
190
+ super().__init__(*args, **kwargs)
191
+
192
+ def __del__(self):
193
+ # The check for deletedness is needed to avoid an error at animation
194
+ # shutdown with PySide2.
195
+ if not _isdeleted(self._timer):
196
+ self._timer_stop()
197
+
198
+ def _timer_set_single_shot(self):
199
+ self._timer.setSingleShot(self._single)
200
+
201
+ def _timer_set_interval(self):
202
+ self._timer.setInterval(self._interval)
203
+
204
+ def _timer_start(self):
205
+ self._timer.start()
206
+
207
+ def _timer_stop(self):
208
+ self._timer.stop()
209
+
210
+
211
+ class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget):
212
+ required_interactive_framework = "qt"
213
+ _timer_cls = TimerQT
214
+ manager_class = _api.classproperty(lambda cls: FigureManagerQT)
215
+
216
+ buttond = {
217
+ getattr(QtCore.Qt.MouseButton, k): v for k, v in [
218
+ ("LeftButton", MouseButton.LEFT),
219
+ ("RightButton", MouseButton.RIGHT),
220
+ ("MiddleButton", MouseButton.MIDDLE),
221
+ ("XButton1", MouseButton.BACK),
222
+ ("XButton2", MouseButton.FORWARD),
223
+ ]
224
+ }
225
+
226
+ def __init__(self, figure=None):
227
+ _create_qApp()
228
+ super().__init__(figure=figure)
229
+
230
+ self._draw_pending = False
231
+ self._is_drawing = False
232
+ self._draw_rect_callback = lambda painter: None
233
+ self._in_resize_event = False
234
+
235
+ self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent)
236
+ self.setMouseTracking(True)
237
+ self.resize(*self.get_width_height())
238
+
239
+ palette = QtGui.QPalette(QtGui.QColor("white"))
240
+ self.setPalette(palette)
241
+
242
+ def _update_pixel_ratio(self):
243
+ if self._set_device_pixel_ratio(
244
+ self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0
245
+ # The easiest way to resize the canvas is to emit a resizeEvent
246
+ # since we implement all the logic for resizing the canvas for
247
+ # that event.
248
+ event = QtGui.QResizeEvent(self.size(), self.size())
249
+ self.resizeEvent(event)
250
+
251
+ def _update_screen(self, screen):
252
+ # Handler for changes to a window's attached screen.
253
+ self._update_pixel_ratio()
254
+ if screen is not None:
255
+ screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio)
256
+ screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio)
257
+
258
+ def showEvent(self, event):
259
+ # Set up correct pixel ratio, and connect to any signal changes for it,
260
+ # once the window is shown (and thus has these attributes).
261
+ window = self.window().windowHandle()
262
+ window.screenChanged.connect(self._update_screen)
263
+ self._update_screen(window.screen())
264
+
265
+ def set_cursor(self, cursor):
266
+ # docstring inherited
267
+ self.setCursor(_api.check_getitem(cursord, cursor=cursor))
268
+
269
+ def mouseEventCoords(self, pos=None):
270
+ """
271
+ Calculate mouse coordinates in physical pixels.
272
+
273
+ Qt uses logical pixels, but the figure is scaled to physical
274
+ pixels for rendering. Transform to physical pixels so that
275
+ all of the down-stream transforms work as expected.
276
+
277
+ Also, the origin is different and needs to be corrected.
278
+ """
279
+ if pos is None:
280
+ pos = self.mapFromGlobal(QtGui.QCursor.pos())
281
+ elif hasattr(pos, "position"): # qt6 QtGui.QEvent
282
+ pos = pos.position()
283
+ elif hasattr(pos, "pos"): # qt5 QtCore.QEvent
284
+ pos = pos.pos()
285
+ # (otherwise, it's already a QPoint)
286
+ x = pos.x()
287
+ # flip y so y=0 is bottom of canvas
288
+ y = self.figure.bbox.height / self.device_pixel_ratio - pos.y()
289
+ return x * self.device_pixel_ratio, y * self.device_pixel_ratio
290
+
291
+ def enterEvent(self, event):
292
+ # Force querying of the modifiers, as the cached modifier state can
293
+ # have been invalidated while the window was out of focus.
294
+ mods = QtWidgets.QApplication.instance().queryKeyboardModifiers()
295
+ if self.figure is None:
296
+ return
297
+ LocationEvent("figure_enter_event", self,
298
+ *self.mouseEventCoords(event),
299
+ modifiers=self._mpl_modifiers(mods),
300
+ guiEvent=event)._process()
301
+
302
+ def leaveEvent(self, event):
303
+ QtWidgets.QApplication.restoreOverrideCursor()
304
+ if self.figure is None:
305
+ return
306
+ LocationEvent("figure_leave_event", self,
307
+ *self.mouseEventCoords(),
308
+ modifiers=self._mpl_modifiers(),
309
+ guiEvent=event)._process()
310
+
311
+ def mousePressEvent(self, event):
312
+ button = self.buttond.get(event.button())
313
+ if button is not None and self.figure is not None:
314
+ MouseEvent("button_press_event", self,
315
+ *self.mouseEventCoords(event), button,
316
+ modifiers=self._mpl_modifiers(),
317
+ guiEvent=event)._process()
318
+
319
+ def mouseDoubleClickEvent(self, event):
320
+ button = self.buttond.get(event.button())
321
+ if button is not None and self.figure is not None:
322
+ MouseEvent("button_press_event", self,
323
+ *self.mouseEventCoords(event), button, dblclick=True,
324
+ modifiers=self._mpl_modifiers(),
325
+ guiEvent=event)._process()
326
+
327
+ def mouseMoveEvent(self, event):
328
+ if self.figure is None:
329
+ return
330
+ MouseEvent("motion_notify_event", self,
331
+ *self.mouseEventCoords(event),
332
+ modifiers=self._mpl_modifiers(),
333
+ guiEvent=event)._process()
334
+
335
+ def mouseReleaseEvent(self, event):
336
+ button = self.buttond.get(event.button())
337
+ if button is not None and self.figure is not None:
338
+ MouseEvent("button_release_event", self,
339
+ *self.mouseEventCoords(event), button,
340
+ modifiers=self._mpl_modifiers(),
341
+ guiEvent=event)._process()
342
+
343
+ def wheelEvent(self, event):
344
+ # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not
345
+ # provided (`isNull()`) and is unreliable on X11 ("xcb").
346
+ if (event.pixelDelta().isNull()
347
+ or QtWidgets.QApplication.instance().platformName() == "xcb"):
348
+ steps = event.angleDelta().y() / 120
349
+ else:
350
+ steps = event.pixelDelta().y()
351
+ if steps and self.figure is not None:
352
+ MouseEvent("scroll_event", self,
353
+ *self.mouseEventCoords(event), step=steps,
354
+ modifiers=self._mpl_modifiers(),
355
+ guiEvent=event)._process()
356
+
357
+ def keyPressEvent(self, event):
358
+ key = self._get_key(event)
359
+ if key is not None and self.figure is not None:
360
+ KeyEvent("key_press_event", self,
361
+ key, *self.mouseEventCoords(),
362
+ guiEvent=event)._process()
363
+
364
+ def keyReleaseEvent(self, event):
365
+ key = self._get_key(event)
366
+ if key is not None and self.figure is not None:
367
+ KeyEvent("key_release_event", self,
368
+ key, *self.mouseEventCoords(),
369
+ guiEvent=event)._process()
370
+
371
+ def resizeEvent(self, event):
372
+ if self._in_resize_event: # Prevent PyQt6 recursion
373
+ return
374
+ if self.figure is None:
375
+ return
376
+ self._in_resize_event = True
377
+ try:
378
+ w = event.size().width() * self.device_pixel_ratio
379
+ h = event.size().height() * self.device_pixel_ratio
380
+ dpival = self.figure.dpi
381
+ winch = w / dpival
382
+ hinch = h / dpival
383
+ self.figure.set_size_inches(winch, hinch, forward=False)
384
+ # pass back into Qt to let it finish
385
+ QtWidgets.QWidget.resizeEvent(self, event)
386
+ # emit our resize events
387
+ ResizeEvent("resize_event", self)._process()
388
+ self.draw_idle()
389
+ finally:
390
+ self._in_resize_event = False
391
+
392
+ def sizeHint(self):
393
+ w, h = self.get_width_height()
394
+ return QtCore.QSize(w, h)
395
+
396
+ def minumumSizeHint(self):
397
+ return QtCore.QSize(10, 10)
398
+
399
+ @staticmethod
400
+ def _mpl_modifiers(modifiers=None, *, exclude=None):
401
+ if modifiers is None:
402
+ modifiers = QtWidgets.QApplication.instance().keyboardModifiers()
403
+ modifiers = _to_int(modifiers)
404
+ # get names of the pressed modifier keys
405
+ # 'control' is named 'control' when a standalone key, but 'ctrl' when a
406
+ # modifier
407
+ # bit twiddling to pick out modifier keys from modifiers bitmask,
408
+ # if exclude is a MODIFIER, it should not be duplicated in mods
409
+ return [SPECIAL_KEYS[key].replace('control', 'ctrl')
410
+ for mask, key in _MODIFIER_KEYS
411
+ if exclude != key and modifiers & mask]
412
+
413
+ def _get_key(self, event):
414
+ event_key = event.key()
415
+ mods = self._mpl_modifiers(exclude=event_key)
416
+ try:
417
+ # for certain keys (enter, left, backspace, etc) use a word for the
418
+ # key, rather than Unicode
419
+ key = SPECIAL_KEYS[event_key]
420
+ except KeyError:
421
+ # Unicode defines code points up to 0x10ffff (sys.maxunicode)
422
+ # QT will use Key_Codes larger than that for keyboard keys that are
423
+ # not Unicode characters (like multimedia keys)
424
+ # skip these
425
+ # if you really want them, you should add them to SPECIAL_KEYS
426
+ if event_key > sys.maxunicode:
427
+ return None
428
+
429
+ key = chr(event_key)
430
+ # qt delivers capitalized letters. fix capitalization
431
+ # note that capslock is ignored
432
+ if 'shift' in mods:
433
+ mods.remove('shift')
434
+ else:
435
+ key = key.lower()
436
+
437
+ return '+'.join(mods + [key])
438
+
439
+ def flush_events(self):
440
+ # docstring inherited
441
+ QtWidgets.QApplication.instance().processEvents()
442
+
443
+ def start_event_loop(self, timeout=0):
444
+ # docstring inherited
445
+ if hasattr(self, "_event_loop") and self._event_loop.isRunning():
446
+ raise RuntimeError("Event loop already running")
447
+ self._event_loop = event_loop = QtCore.QEventLoop()
448
+ if timeout > 0:
449
+ _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit)
450
+
451
+ with _allow_interrupt_qt(event_loop):
452
+ qt_compat._exec(event_loop)
453
+
454
+ def stop_event_loop(self, event=None):
455
+ # docstring inherited
456
+ if hasattr(self, "_event_loop"):
457
+ self._event_loop.quit()
458
+
459
+ def draw(self):
460
+ """Render the figure, and queue a request for a Qt draw."""
461
+ # The renderer draw is done here; delaying causes problems with code
462
+ # that uses the result of the draw() to update plot elements.
463
+ if self._is_drawing:
464
+ return
465
+ with cbook._setattr_cm(self, _is_drawing=True):
466
+ super().draw()
467
+ self.update()
468
+
469
+ def draw_idle(self):
470
+ """Queue redraw of the Agg buffer and request Qt paintEvent."""
471
+ # The Agg draw needs to be handled by the same thread Matplotlib
472
+ # modifies the scene graph from. Post Agg draw request to the
473
+ # current event loop in order to ensure thread affinity and to
474
+ # accumulate multiple draw requests from event handling.
475
+ # TODO: queued signal connection might be safer than singleShot
476
+ if not (getattr(self, '_draw_pending', False) or
477
+ getattr(self, '_is_drawing', False)):
478
+ self._draw_pending = True
479
+ QtCore.QTimer.singleShot(0, self._draw_idle)
480
+
481
+ def blit(self, bbox=None):
482
+ # docstring inherited
483
+ if bbox is None and self.figure:
484
+ bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
485
+ # repaint uses logical pixels, not physical pixels like the renderer.
486
+ l, b, w, h = [int(pt / self.device_pixel_ratio) for pt in bbox.bounds]
487
+ t = b + h
488
+ self.repaint(l, self.rect().height() - t, w, h)
489
+
490
+ def _draw_idle(self):
491
+ with self._idle_draw_cntx():
492
+ if not self._draw_pending:
493
+ return
494
+ self._draw_pending = False
495
+ if self.height() <= 0 or self.width() <= 0:
496
+ return
497
+ try:
498
+ self.draw()
499
+ except Exception:
500
+ # Uncaught exceptions are fatal for PyQt5, so catch them.
501
+ traceback.print_exc()
502
+
503
+ def drawRectangle(self, rect):
504
+ # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
505
+ # to be called at the end of paintEvent.
506
+ if rect is not None:
507
+ x0, y0, w, h = [int(pt / self.device_pixel_ratio) for pt in rect]
508
+ x1 = x0 + w
509
+ y1 = y0 + h
510
+ def _draw_rect_callback(painter):
511
+ pen = QtGui.QPen(
512
+ QtGui.QColor("black"),
513
+ 1 / self.device_pixel_ratio
514
+ )
515
+
516
+ pen.setDashPattern([3, 3])
517
+ for color, offset in [
518
+ (QtGui.QColor("black"), 0),
519
+ (QtGui.QColor("white"), 3),
520
+ ]:
521
+ pen.setDashOffset(offset)
522
+ pen.setColor(color)
523
+ painter.setPen(pen)
524
+ # Draw the lines from x0, y0 towards x1, y1 so that the
525
+ # dashes don't "jump" when moving the zoom box.
526
+ painter.drawLine(x0, y0, x0, y1)
527
+ painter.drawLine(x0, y0, x1, y0)
528
+ painter.drawLine(x0, y1, x1, y1)
529
+ painter.drawLine(x1, y0, x1, y1)
530
+ else:
531
+ def _draw_rect_callback(painter):
532
+ return
533
+ self._draw_rect_callback = _draw_rect_callback
534
+ self.update()
535
+
536
+
537
+ class MainWindow(QtWidgets.QMainWindow):
538
+ closing = QtCore.Signal()
539
+
540
+ def closeEvent(self, event):
541
+ self.closing.emit()
542
+ super().closeEvent(event)
543
+
544
+
545
+ class FigureManagerQT(FigureManagerBase):
546
+ """
547
+ Attributes
548
+ ----------
549
+ canvas : `FigureCanvas`
550
+ The FigureCanvas instance
551
+ num : int or str
552
+ The Figure number
553
+ toolbar : qt.QToolBar
554
+ The qt.QToolBar
555
+ window : qt.QMainWindow
556
+ The qt.QMainWindow
557
+ """
558
+
559
+ def __init__(self, canvas, num):
560
+ self.window = MainWindow()
561
+ super().__init__(canvas, num)
562
+ self.window.closing.connect(self._widgetclosed)
563
+
564
+ if sys.platform != "darwin":
565
+ image = str(cbook._get_data_path('images/matplotlib.svg'))
566
+ icon = QtGui.QIcon(image)
567
+ self.window.setWindowIcon(icon)
568
+
569
+ self.window._destroying = False
570
+
571
+ if self.toolbar:
572
+ self.window.addToolBar(self.toolbar)
573
+ tbs_height = self.toolbar.sizeHint().height()
574
+ else:
575
+ tbs_height = 0
576
+
577
+ # resize the main window so it will display the canvas with the
578
+ # requested size:
579
+ cs = canvas.sizeHint()
580
+ cs_height = cs.height()
581
+ height = cs_height + tbs_height
582
+ self.window.resize(cs.width(), height)
583
+
584
+ self.window.setCentralWidget(self.canvas)
585
+
586
+ if mpl.is_interactive():
587
+ self.window.show()
588
+ self.canvas.draw_idle()
589
+
590
+ # Give the keyboard focus to the figure instead of the manager:
591
+ # StrongFocus accepts both tab and click to focus and will enable the
592
+ # canvas to process event without clicking.
593
+ # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum
594
+ self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
595
+ self.canvas.setFocus()
596
+
597
+ self.window.raise_()
598
+
599
+ def full_screen_toggle(self):
600
+ if self.window.isFullScreen():
601
+ self.window.showNormal()
602
+ else:
603
+ self.window.showFullScreen()
604
+
605
+ def _widgetclosed(self):
606
+ CloseEvent("close_event", self.canvas)._process()
607
+ if self.window._destroying:
608
+ return
609
+ self.window._destroying = True
610
+ try:
611
+ Gcf.destroy(self)
612
+ except AttributeError:
613
+ pass
614
+ # It seems that when the python session is killed,
615
+ # Gcf can get destroyed before the Gcf.destroy
616
+ # line is run, leading to a useless AttributeError.
617
+
618
+ def resize(self, width, height):
619
+ # The Qt methods return sizes in 'virtual' pixels so we do need to
620
+ # rescale from physical to logical pixels.
621
+ width = int(width / self.canvas.device_pixel_ratio)
622
+ height = int(height / self.canvas.device_pixel_ratio)
623
+ extra_width = self.window.width() - self.canvas.width()
624
+ extra_height = self.window.height() - self.canvas.height()
625
+ self.canvas.resize(width, height)
626
+ self.window.resize(width + extra_width, height + extra_height)
627
+
628
+ @classmethod
629
+ def start_main_loop(cls):
630
+ qapp = QtWidgets.QApplication.instance()
631
+ if qapp:
632
+ with _allow_interrupt_qt(qapp):
633
+ qt_compat._exec(qapp)
634
+
635
+ def show(self):
636
+ self.window._destroying = False
637
+ self.window.show()
638
+ if mpl.rcParams['figure.raise_window']:
639
+ self.window.activateWindow()
640
+ self.window.raise_()
641
+
642
+ def destroy(self, *args):
643
+ # check for qApp first, as PySide deletes it in its atexit handler
644
+ if QtWidgets.QApplication.instance() is None:
645
+ return
646
+ if self.window._destroying:
647
+ return
648
+ self.window._destroying = True
649
+ if self.toolbar:
650
+ self.toolbar.destroy()
651
+ self.window.close()
652
+
653
+ def get_window_title(self):
654
+ return self.window.windowTitle()
655
+
656
+ def set_window_title(self, title):
657
+ self.window.setWindowTitle(title)
658
+
659
+
660
+ class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar):
661
+ _message = QtCore.Signal(str) # Remove once deprecation below elapses.
662
+ message = _api.deprecate_privatize_attribute("3.8")
663
+
664
+ toolitems = [*NavigationToolbar2.toolitems]
665
+ toolitems.insert(
666
+ # Add 'customize' action after 'subplots'
667
+ [name for name, *_ in toolitems].index("Subplots") + 1,
668
+ ("Customize", "Edit axis, curve and image parameters",
669
+ "qt4_editor_options", "edit_parameters"))
670
+
671
+ def __init__(self, canvas, parent=None, coordinates=True):
672
+ """coordinates: should we show the coordinates on the right?"""
673
+ QtWidgets.QToolBar.__init__(self, parent)
674
+ self.setAllowedAreas(QtCore.Qt.ToolBarArea(
675
+ _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
676
+ _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
677
+ self.coordinates = coordinates
678
+ self._actions = {} # mapping of toolitem method names to QActions.
679
+ self._subplot_dialog = None
680
+
681
+ for text, tooltip_text, image_file, callback in self.toolitems:
682
+ if text is None:
683
+ self.addSeparator()
684
+ else:
685
+ slot = getattr(self, callback)
686
+ # https://bugreports.qt.io/browse/PYSIDE-2512
687
+ slot = functools.wraps(slot)(functools.partial(slot))
688
+ slot = QtCore.Slot()(slot)
689
+
690
+ a = self.addAction(self._icon(image_file + '.png'),
691
+ text, slot)
692
+ self._actions[callback] = a
693
+ if callback in ['zoom', 'pan']:
694
+ a.setCheckable(True)
695
+ if tooltip_text is not None:
696
+ a.setToolTip(tooltip_text)
697
+
698
+ # Add the (x, y) location widget at the right side of the toolbar
699
+ # The stretch factor is 1 which means any resizing of the toolbar
700
+ # will resize this label instead of the buttons.
701
+ if self.coordinates:
702
+ self.locLabel = QtWidgets.QLabel("", self)
703
+ self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag(
704
+ _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
705
+ _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
706
+
707
+ self.locLabel.setSizePolicy(QtWidgets.QSizePolicy(
708
+ QtWidgets.QSizePolicy.Policy.Expanding,
709
+ QtWidgets.QSizePolicy.Policy.Ignored,
710
+ ))
711
+ labelAction = self.addWidget(self.locLabel)
712
+ labelAction.setVisible(True)
713
+
714
+ NavigationToolbar2.__init__(self, canvas)
715
+
716
+ def _icon(self, name):
717
+ """
718
+ Construct a `.QIcon` from an image file *name*, including the extension
719
+ and relative to Matplotlib's "images" data directory.
720
+ """
721
+ # use a high-resolution icon with suffix '_large' if available
722
+ # note: user-provided icons may not have '_large' versions
723
+ path_regular = cbook._get_data_path('images', name)
724
+ path_large = path_regular.with_name(
725
+ path_regular.name.replace('.png', '_large.png'))
726
+ filename = str(path_large if path_large.exists() else path_regular)
727
+
728
+ pm = QtGui.QPixmap(filename)
729
+ pm.setDevicePixelRatio(
730
+ self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0
731
+ if self.palette().color(self.backgroundRole()).value() < 128:
732
+ icon_color = self.palette().color(self.foregroundRole())
733
+ mask = pm.createMaskFromColor(
734
+ QtGui.QColor('black'),
735
+ QtCore.Qt.MaskMode.MaskOutColor)
736
+ pm.fill(icon_color)
737
+ pm.setMask(mask)
738
+ return QtGui.QIcon(pm)
739
+
740
+ def edit_parameters(self):
741
+ axes = self.canvas.figure.get_axes()
742
+ if not axes:
743
+ QtWidgets.QMessageBox.warning(
744
+ self.canvas.parent(), "Error", "There are no Axes to edit.")
745
+ return
746
+ elif len(axes) == 1:
747
+ ax, = axes
748
+ else:
749
+ titles = [
750
+ ax.get_label() or
751
+ ax.get_title() or
752
+ ax.get_title("left") or
753
+ ax.get_title("right") or
754
+ " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
755
+ f"<anonymous {type(ax).__name__}>"
756
+ for ax in axes]
757
+ duplicate_titles = [
758
+ title for title in titles if titles.count(title) > 1]
759
+ for i, ax in enumerate(axes):
760
+ if titles[i] in duplicate_titles:
761
+ titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles.
762
+ item, ok = QtWidgets.QInputDialog.getItem(
763
+ self.canvas.parent(),
764
+ 'Customize', 'Select Axes:', titles, 0, False)
765
+ if not ok:
766
+ return
767
+ ax = axes[titles.index(item)]
768
+ figureoptions.figure_edit(ax, self)
769
+
770
+ def _update_buttons_checked(self):
771
+ # sync button checkstates to match active mode
772
+ if 'pan' in self._actions:
773
+ self._actions['pan'].setChecked(self.mode.name == 'PAN')
774
+ if 'zoom' in self._actions:
775
+ self._actions['zoom'].setChecked(self.mode.name == 'ZOOM')
776
+
777
+ def pan(self, *args):
778
+ super().pan(*args)
779
+ self._update_buttons_checked()
780
+
781
+ def zoom(self, *args):
782
+ super().zoom(*args)
783
+ self._update_buttons_checked()
784
+
785
+ def set_message(self, s):
786
+ self._message.emit(s)
787
+ if self.coordinates:
788
+ self.locLabel.setText(s)
789
+
790
+ def draw_rubberband(self, event, x0, y0, x1, y1):
791
+ height = self.canvas.figure.bbox.height
792
+ y1 = height - y1
793
+ y0 = height - y0
794
+ rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
795
+ self.canvas.drawRectangle(rect)
796
+
797
+ def remove_rubberband(self):
798
+ self.canvas.drawRectangle(None)
799
+
800
+ def configure_subplots(self):
801
+ if self._subplot_dialog is None:
802
+ self._subplot_dialog = SubplotToolQt(
803
+ self.canvas.figure, self.canvas.parent())
804
+ self.canvas.mpl_connect(
805
+ "close_event", lambda e: self._subplot_dialog.reject())
806
+ self._subplot_dialog.update_from_current_subplotpars()
807
+ self._subplot_dialog.setModal(True)
808
+ self._subplot_dialog.show()
809
+ return self._subplot_dialog
810
+
811
+ def save_figure(self, *args):
812
+ filetypes = self.canvas.get_supported_filetypes_grouped()
813
+ sorted_filetypes = sorted(filetypes.items())
814
+ default_filetype = self.canvas.get_default_filetype()
815
+
816
+ startpath = os.path.expanduser(mpl.rcParams['savefig.directory'])
817
+ start = os.path.join(startpath, self.canvas.get_default_filename())
818
+ filters = []
819
+ selectedFilter = None
820
+ for name, exts in sorted_filetypes:
821
+ exts_list = " ".join(['*.%s' % ext for ext in exts])
822
+ filter = f'{name} ({exts_list})'
823
+ if default_filetype in exts:
824
+ selectedFilter = filter
825
+ filters.append(filter)
826
+ filters = ';;'.join(filters)
827
+
828
+ fname, filter = QtWidgets.QFileDialog.getSaveFileName(
829
+ self.canvas.parent(), "Choose a filename to save to", start,
830
+ filters, selectedFilter)
831
+ if fname:
832
+ # Save dir for next time, unless empty str (i.e., use cwd).
833
+ if startpath != "":
834
+ mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
835
+ try:
836
+ self.canvas.figure.savefig(fname)
837
+ except Exception as e:
838
+ QtWidgets.QMessageBox.critical(
839
+ self, "Error saving file", str(e),
840
+ QtWidgets.QMessageBox.StandardButton.Ok,
841
+ QtWidgets.QMessageBox.StandardButton.NoButton)
842
+
843
+ def set_history_buttons(self):
844
+ can_backward = self._nav_stack._pos > 0
845
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
846
+ if 'back' in self._actions:
847
+ self._actions['back'].setEnabled(can_backward)
848
+ if 'forward' in self._actions:
849
+ self._actions['forward'].setEnabled(can_forward)
850
+
851
+
852
+ class SubplotToolQt(QtWidgets.QDialog):
853
+ def __init__(self, targetfig, parent):
854
+ super().__init__()
855
+ self.setWindowIcon(QtGui.QIcon(
856
+ str(cbook._get_data_path("images/matplotlib.png"))))
857
+ self.setObjectName("SubplotTool")
858
+ self._spinboxes = {}
859
+ main_layout = QtWidgets.QHBoxLayout()
860
+ self.setLayout(main_layout)
861
+ for group, spinboxes, buttons in [
862
+ ("Borders",
863
+ ["top", "bottom", "left", "right"],
864
+ [("Export values", self._export_values)]),
865
+ ("Spacings",
866
+ ["hspace", "wspace"],
867
+ [("Tight layout", self._tight_layout),
868
+ ("Reset", self._reset),
869
+ ("Close", self.close)])]:
870
+ layout = QtWidgets.QVBoxLayout()
871
+ main_layout.addLayout(layout)
872
+ box = QtWidgets.QGroupBox(group)
873
+ layout.addWidget(box)
874
+ inner = QtWidgets.QFormLayout(box)
875
+ for name in spinboxes:
876
+ self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox()
877
+ spinbox.setRange(0, 1)
878
+ spinbox.setDecimals(3)
879
+ spinbox.setSingleStep(0.005)
880
+ spinbox.setKeyboardTracking(False)
881
+ spinbox.valueChanged.connect(self._on_value_changed)
882
+ inner.addRow(name, spinbox)
883
+ layout.addStretch(1)
884
+ for name, method in buttons:
885
+ button = QtWidgets.QPushButton(name)
886
+ # Don't trigger on <enter>, which is used to input values.
887
+ button.setAutoDefault(False)
888
+ button.clicked.connect(method)
889
+ layout.addWidget(button)
890
+ if name == "Close":
891
+ button.setFocus()
892
+ self._figure = targetfig
893
+ self._defaults = {}
894
+ self._export_values_dialog = None
895
+ self.update_from_current_subplotpars()
896
+
897
+ def update_from_current_subplotpars(self):
898
+ self._defaults = {spinbox: getattr(self._figure.subplotpars, name)
899
+ for name, spinbox in self._spinboxes.items()}
900
+ self._reset() # Set spinbox current values without triggering signals.
901
+
902
+ def _export_values(self):
903
+ # Explicitly round to 3 decimals (which is also the spinbox precision)
904
+ # to avoid numbers of the form 0.100...001.
905
+ self._export_values_dialog = QtWidgets.QDialog()
906
+ layout = QtWidgets.QVBoxLayout()
907
+ self._export_values_dialog.setLayout(layout)
908
+ text = QtWidgets.QPlainTextEdit()
909
+ text.setReadOnly(True)
910
+ layout.addWidget(text)
911
+ text.setPlainText(
912
+ ",\n".join(f"{attr}={spinbox.value():.3}"
913
+ for attr, spinbox in self._spinboxes.items()))
914
+ # Adjust the height of the text widget to fit the whole text, plus
915
+ # some padding.
916
+ size = text.maximumSize()
917
+ size.setHeight(
918
+ QtGui.QFontMetrics(text.document().defaultFont())
919
+ .size(0, text.toPlainText()).height() + 20)
920
+ text.setMaximumSize(size)
921
+ self._export_values_dialog.show()
922
+
923
+ def _on_value_changed(self):
924
+ spinboxes = self._spinboxes
925
+ # Set all mins and maxes, so that this can also be used in _reset().
926
+ for lower, higher in [("bottom", "top"), ("left", "right")]:
927
+ spinboxes[higher].setMinimum(spinboxes[lower].value() + .001)
928
+ spinboxes[lower].setMaximum(spinboxes[higher].value() - .001)
929
+ self._figure.subplots_adjust(
930
+ **{attr: spinbox.value() for attr, spinbox in spinboxes.items()})
931
+ self._figure.canvas.draw_idle()
932
+
933
+ def _tight_layout(self):
934
+ self._figure.tight_layout()
935
+ for attr, spinbox in self._spinboxes.items():
936
+ spinbox.blockSignals(True)
937
+ spinbox.setValue(getattr(self._figure.subplotpars, attr))
938
+ spinbox.blockSignals(False)
939
+ self._figure.canvas.draw_idle()
940
+
941
+ def _reset(self):
942
+ for spinbox, value in self._defaults.items():
943
+ spinbox.setRange(0, 1)
944
+ spinbox.blockSignals(True)
945
+ spinbox.setValue(value)
946
+ spinbox.blockSignals(False)
947
+ self._on_value_changed()
948
+
949
+
950
+ class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar):
951
+ def __init__(self, toolmanager, parent=None):
952
+ ToolContainerBase.__init__(self, toolmanager)
953
+ QtWidgets.QToolBar.__init__(self, parent)
954
+ self.setAllowedAreas(QtCore.Qt.ToolBarArea(
955
+ _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
956
+ _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
957
+ message_label = QtWidgets.QLabel("")
958
+ message_label.setAlignment(QtCore.Qt.AlignmentFlag(
959
+ _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
960
+ _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
961
+ message_label.setSizePolicy(QtWidgets.QSizePolicy(
962
+ QtWidgets.QSizePolicy.Policy.Expanding,
963
+ QtWidgets.QSizePolicy.Policy.Ignored,
964
+ ))
965
+ self._message_action = self.addWidget(message_label)
966
+ self._toolitems = {}
967
+ self._groups = {}
968
+
969
+ def add_toolitem(
970
+ self, name, group, position, image_file, description, toggle):
971
+
972
+ button = QtWidgets.QToolButton(self)
973
+ if image_file:
974
+ button.setIcon(NavigationToolbar2QT._icon(self, image_file))
975
+ button.setText(name)
976
+ if description:
977
+ button.setToolTip(description)
978
+
979
+ def handler():
980
+ self.trigger_tool(name)
981
+ if toggle:
982
+ button.setCheckable(True)
983
+ button.toggled.connect(handler)
984
+ else:
985
+ button.clicked.connect(handler)
986
+
987
+ self._toolitems.setdefault(name, [])
988
+ self._add_to_group(group, name, button, position)
989
+ self._toolitems[name].append((button, handler))
990
+
991
+ def _add_to_group(self, group, name, button, position):
992
+ gr = self._groups.get(group, [])
993
+ if not gr:
994
+ sep = self.insertSeparator(self._message_action)
995
+ gr.append(sep)
996
+ before = gr[position]
997
+ widget = self.insertWidget(before, button)
998
+ gr.insert(position, widget)
999
+ self._groups[group] = gr
1000
+
1001
+ def toggle_toolitem(self, name, toggled):
1002
+ if name not in self._toolitems:
1003
+ return
1004
+ for button, handler in self._toolitems[name]:
1005
+ button.toggled.disconnect(handler)
1006
+ button.setChecked(toggled)
1007
+ button.toggled.connect(handler)
1008
+
1009
+ def remove_toolitem(self, name):
1010
+ for button, handler in self._toolitems.pop(name, []):
1011
+ button.setParent(None)
1012
+
1013
+ def set_message(self, s):
1014
+ self.widgetForAction(self._message_action).setText(s)
1015
+
1016
+
1017
+ @backend_tools._register_tool_class(FigureCanvasQT)
1018
+ class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase):
1019
+ def __init__(self, *args, **kwargs):
1020
+ super().__init__(*args, **kwargs)
1021
+ self._subplot_dialog = None
1022
+
1023
+ def trigger(self, *args):
1024
+ NavigationToolbar2QT.configure_subplots(self)
1025
+
1026
+
1027
+ @backend_tools._register_tool_class(FigureCanvasQT)
1028
+ class SaveFigureQt(backend_tools.SaveFigureBase):
1029
+ def trigger(self, *args):
1030
+ NavigationToolbar2QT.save_figure(
1031
+ self._make_classic_style_pseudo_toolbar())
1032
+
1033
+
1034
+ @backend_tools._register_tool_class(FigureCanvasQT)
1035
+ class RubberbandQt(backend_tools.RubberbandBase):
1036
+ def draw_rubberband(self, x0, y0, x1, y1):
1037
+ NavigationToolbar2QT.draw_rubberband(
1038
+ self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
1039
+
1040
+ def remove_rubberband(self):
1041
+ NavigationToolbar2QT.remove_rubberband(
1042
+ self._make_classic_style_pseudo_toolbar())
1043
+
1044
+
1045
+ @backend_tools._register_tool_class(FigureCanvasQT)
1046
+ class HelpQt(backend_tools.ToolHelpBase):
1047
+ def trigger(self, *args):
1048
+ QtWidgets.QMessageBox.information(None, "Help", self._get_help_html())
1049
+
1050
+
1051
+ @backend_tools._register_tool_class(FigureCanvasQT)
1052
+ class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase):
1053
+ def trigger(self, *args, **kwargs):
1054
+ pixmap = self.canvas.grab()
1055
+ QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap)
1056
+
1057
+
1058
+ FigureManagerQT._toolbar2_class = NavigationToolbar2QT
1059
+ FigureManagerQT._toolmanager_toolbar_class = ToolbarQt
1060
+
1061
+
1062
+ @_Backend.export
1063
+ class _BackendQT(_Backend):
1064
+ backend_version = __version__
1065
+ FigureCanvas = FigureCanvasQT
1066
+ FigureManager = FigureManagerQT
1067
+ mainloop = FigureManagerQT.start_main_loop
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import backends
2
+
3
+ backends._QT_FORCE_QT5_BINDING = True
4
+
5
+
6
+ from .backend_qt import ( # noqa
7
+ SPECIAL_KEYS,
8
+ # Public API
9
+ cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT,
10
+ FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt,
11
+ SaveFigureQt, ConfigureSubplotsQt, RubberbandQt,
12
+ HelpQt, ToolCopyToClipboardQT,
13
+ # internal re-exports
14
+ FigureCanvasBase, FigureManagerBase, MouseButton, NavigationToolbar2,
15
+ TimerBase, ToolContainerBase, figureoptions, Gcf
16
+ )
17
+ from . import backend_qt as _backend_qt # noqa
18
+
19
+
20
+ @_BackendQT.export
21
+ class _BackendQT5(_BackendQT):
22
+ pass
23
+
24
+
25
+ def __getattr__(name):
26
+ if name == 'qApp':
27
+ return _backend_qt.qApp
28
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5agg.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Render to qt from agg
3
+ """
4
+ from .. import backends
5
+
6
+ backends._QT_FORCE_QT5_BINDING = True
7
+ from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611
8
+ _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT,
9
+ FigureCanvasAgg, FigureCanvasQT)
10
+
11
+
12
+ @_BackendQTAgg.export
13
+ class _BackendQT5Agg(_BackendQTAgg):
14
+ pass
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qt5cairo.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import backends
2
+
3
+ backends._QT_FORCE_QT5_BINDING = True
4
+ from .backend_qtcairo import ( # noqa: F401, E402 # pylint: disable=W0611
5
+ _BackendQTCairo, FigureCanvasQTCairo, FigureCanvasCairo, FigureCanvasQT
6
+ )
7
+
8
+
9
+ @_BackendQTCairo.export
10
+ class _BackendQT5Cairo(_BackendQTCairo):
11
+ pass
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_qtagg.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Render to qt from agg.
3
+ """
4
+
5
+ import ctypes
6
+
7
+ from matplotlib.transforms import Bbox
8
+
9
+ from .qt_compat import QT_API, QtCore, QtGui
10
+ from .backend_agg import FigureCanvasAgg
11
+ from .backend_qt import _BackendQT, FigureCanvasQT
12
+ from .backend_qt import ( # noqa: F401 # pylint: disable=W0611
13
+ FigureManagerQT, NavigationToolbar2QT)
14
+
15
+
16
+ class FigureCanvasQTAgg(FigureCanvasAgg, FigureCanvasQT):
17
+
18
+ def paintEvent(self, event):
19
+ """
20
+ Copy the image from the Agg canvas to the qt.drawable.
21
+
22
+ In Qt, all drawing should be done inside of here when a widget is
23
+ shown onscreen.
24
+ """
25
+ self._draw_idle() # Only does something if a draw is pending.
26
+
27
+ # If the canvas does not have a renderer, then give up and wait for
28
+ # FigureCanvasAgg.draw(self) to be called.
29
+ if not hasattr(self, 'renderer'):
30
+ return
31
+
32
+ painter = QtGui.QPainter(self)
33
+ try:
34
+ # See documentation of QRect: bottom() and right() are off
35
+ # by 1, so use left() + width() and top() + height().
36
+ rect = event.rect()
37
+ # scale rect dimensions using the screen dpi ratio to get
38
+ # correct values for the Figure coordinates (rather than
39
+ # QT5's coords)
40
+ width = rect.width() * self.device_pixel_ratio
41
+ height = rect.height() * self.device_pixel_ratio
42
+ left, top = self.mouseEventCoords(rect.topLeft())
43
+ # shift the "top" by the height of the image to get the
44
+ # correct corner for our coordinate system
45
+ bottom = top - height
46
+ # same with the right side of the image
47
+ right = left + width
48
+ # create a buffer using the image bounding box
49
+ bbox = Bbox([[left, bottom], [right, top]])
50
+ buf = memoryview(self.copy_from_bbox(bbox))
51
+
52
+ if QT_API == "PyQt6":
53
+ from PyQt6 import sip
54
+ ptr = int(sip.voidptr(buf))
55
+ else:
56
+ ptr = buf
57
+
58
+ painter.eraseRect(rect) # clear the widget canvas
59
+ qimage = QtGui.QImage(ptr, buf.shape[1], buf.shape[0],
60
+ QtGui.QImage.Format.Format_RGBA8888)
61
+ qimage.setDevicePixelRatio(self.device_pixel_ratio)
62
+ # set origin using original QT coordinates
63
+ origin = QtCore.QPoint(rect.left(), rect.top())
64
+ painter.drawImage(origin, qimage)
65
+ # Adjust the buf reference count to work around a memory
66
+ # leak bug in QImage under PySide.
67
+ if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):
68
+ ctypes.c_long.from_address(id(buf)).value = 1
69
+
70
+ self._draw_rect_callback(painter)
71
+ finally:
72
+ painter.end()
73
+
74
+ def print_figure(self, *args, **kwargs):
75
+ super().print_figure(*args, **kwargs)
76
+ # In some cases, Qt will itself trigger a paint event after closing the file
77
+ # save dialog. When that happens, we need to be sure that the internal canvas is
78
+ # re-drawn. However, if the user is using an automatically-chosen Qt backend but
79
+ # saving with a different backend (such as pgf), we do not want to trigger a
80
+ # full draw in Qt, so just set the flag for next time.
81
+ self._draw_pending = True
82
+
83
+
84
+ @_BackendQT.export
85
+ class _BackendQTAgg(_BackendQT):
86
+ FigureCanvas = FigureCanvasQTAgg
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_svg.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import codecs
3
+ import datetime
4
+ import gzip
5
+ import hashlib
6
+ from io import BytesIO
7
+ import itertools
8
+ import logging
9
+ import os
10
+ import re
11
+ import uuid
12
+
13
+ import numpy as np
14
+ from PIL import Image
15
+
16
+ import matplotlib as mpl
17
+ from matplotlib import cbook, font_manager as fm
18
+ from matplotlib.backend_bases import (
19
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
20
+ from matplotlib.backends.backend_mixed import MixedModeRenderer
21
+ from matplotlib.colors import rgb2hex
22
+ from matplotlib.dates import UTC
23
+ from matplotlib.path import Path
24
+ from matplotlib import _path
25
+ from matplotlib.transforms import Affine2D, Affine2DBase
26
+
27
+
28
+ _log = logging.getLogger(__name__)
29
+
30
+
31
+ # ----------------------------------------------------------------------
32
+ # SimpleXMLWriter class
33
+ #
34
+ # Based on an original by Fredrik Lundh, but modified here to:
35
+ # 1. Support modern Python idioms
36
+ # 2. Remove encoding support (it's handled by the file writer instead)
37
+ # 3. Support proper indentation
38
+ # 4. Minify things a little bit
39
+
40
+ # --------------------------------------------------------------------
41
+ # The SimpleXMLWriter module is
42
+ #
43
+ # Copyright (c) 2001-2004 by Fredrik Lundh
44
+ #
45
+ # By obtaining, using, and/or copying this software and/or its
46
+ # associated documentation, you agree that you have read, understood,
47
+ # and will comply with the following terms and conditions:
48
+ #
49
+ # Permission to use, copy, modify, and distribute this software and
50
+ # its associated documentation for any purpose and without fee is
51
+ # hereby granted, provided that the above copyright notice appears in
52
+ # all copies, and that both that copyright notice and this permission
53
+ # notice appear in supporting documentation, and that the name of
54
+ # Secret Labs AB or the author not be used in advertising or publicity
55
+ # pertaining to distribution of the software without specific, written
56
+ # prior permission.
57
+ #
58
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
59
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
60
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
61
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
62
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
63
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
64
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
65
+ # OF THIS SOFTWARE.
66
+ # --------------------------------------------------------------------
67
+
68
+
69
+ def _escape_cdata(s):
70
+ s = s.replace("&", "&amp;")
71
+ s = s.replace("<", "&lt;")
72
+ s = s.replace(">", "&gt;")
73
+ return s
74
+
75
+
76
+ _escape_xml_comment = re.compile(r'-(?=-)')
77
+
78
+
79
+ def _escape_comment(s):
80
+ s = _escape_cdata(s)
81
+ return _escape_xml_comment.sub('- ', s)
82
+
83
+
84
+ def _escape_attrib(s):
85
+ s = s.replace("&", "&amp;")
86
+ s = s.replace("'", "&apos;")
87
+ s = s.replace('"', "&quot;")
88
+ s = s.replace("<", "&lt;")
89
+ s = s.replace(">", "&gt;")
90
+ return s
91
+
92
+
93
+ def _quote_escape_attrib(s):
94
+ return ('"' + _escape_cdata(s) + '"' if '"' not in s else
95
+ "'" + _escape_cdata(s) + "'" if "'" not in s else
96
+ '"' + _escape_attrib(s) + '"')
97
+
98
+
99
+ def _short_float_fmt(x):
100
+ """
101
+ Create a short string representation of a float, which is %f
102
+ formatting with trailing zeros and the decimal point removed.
103
+ """
104
+ return f'{x:f}'.rstrip('0').rstrip('.')
105
+
106
+
107
+ class XMLWriter:
108
+ """
109
+ Parameters
110
+ ----------
111
+ file : writable text file-like object
112
+ """
113
+
114
+ def __init__(self, file):
115
+ self.__write = file.write
116
+ if hasattr(file, "flush"):
117
+ self.flush = file.flush
118
+ self.__open = 0 # true if start tag is open
119
+ self.__tags = []
120
+ self.__data = []
121
+ self.__indentation = " " * 64
122
+
123
+ def __flush(self, indent=True):
124
+ # flush internal buffers
125
+ if self.__open:
126
+ if indent:
127
+ self.__write(">\n")
128
+ else:
129
+ self.__write(">")
130
+ self.__open = 0
131
+ if self.__data:
132
+ data = ''.join(self.__data)
133
+ self.__write(_escape_cdata(data))
134
+ self.__data = []
135
+
136
+ def start(self, tag, attrib={}, **extra):
137
+ """
138
+ Open a new element. Attributes can be given as keyword
139
+ arguments, or as a string/string dictionary. The method returns
140
+ an opaque identifier that can be passed to the :meth:`close`
141
+ method, to close all open elements up to and including this one.
142
+
143
+ Parameters
144
+ ----------
145
+ tag
146
+ Element tag.
147
+ attrib
148
+ Attribute dictionary. Alternatively, attributes can be given as
149
+ keyword arguments.
150
+
151
+ Returns
152
+ -------
153
+ An element identifier.
154
+ """
155
+ self.__flush()
156
+ tag = _escape_cdata(tag)
157
+ self.__data = []
158
+ self.__tags.append(tag)
159
+ self.__write(self.__indentation[:len(self.__tags) - 1])
160
+ self.__write(f"<{tag}")
161
+ for k, v in {**attrib, **extra}.items():
162
+ if v:
163
+ k = _escape_cdata(k)
164
+ v = _quote_escape_attrib(v)
165
+ self.__write(f' {k}={v}')
166
+ self.__open = 1
167
+ return len(self.__tags) - 1
168
+
169
+ def comment(self, comment):
170
+ """
171
+ Add a comment to the output stream.
172
+
173
+ Parameters
174
+ ----------
175
+ comment : str
176
+ Comment text.
177
+ """
178
+ self.__flush()
179
+ self.__write(self.__indentation[:len(self.__tags)])
180
+ self.__write(f"<!-- {_escape_comment(comment)} -->\n")
181
+
182
+ def data(self, text):
183
+ """
184
+ Add character data to the output stream.
185
+
186
+ Parameters
187
+ ----------
188
+ text : str
189
+ Character data.
190
+ """
191
+ self.__data.append(text)
192
+
193
+ def end(self, tag=None, indent=True):
194
+ """
195
+ Close the current element (opened by the most recent call to
196
+ :meth:`start`).
197
+
198
+ Parameters
199
+ ----------
200
+ tag
201
+ Element tag. If given, the tag must match the start tag. If
202
+ omitted, the current element is closed.
203
+ indent : bool, default: True
204
+ """
205
+ if tag:
206
+ assert self.__tags, f"unbalanced end({tag})"
207
+ assert _escape_cdata(tag) == self.__tags[-1], \
208
+ f"expected end({self.__tags[-1]}), got {tag}"
209
+ else:
210
+ assert self.__tags, "unbalanced end()"
211
+ tag = self.__tags.pop()
212
+ if self.__data:
213
+ self.__flush(indent)
214
+ elif self.__open:
215
+ self.__open = 0
216
+ self.__write("/>\n")
217
+ return
218
+ if indent:
219
+ self.__write(self.__indentation[:len(self.__tags)])
220
+ self.__write(f"</{tag}>\n")
221
+
222
+ def close(self, id):
223
+ """
224
+ Close open elements, up to (and including) the element identified
225
+ by the given identifier.
226
+
227
+ Parameters
228
+ ----------
229
+ id
230
+ Element identifier, as returned by the :meth:`start` method.
231
+ """
232
+ while len(self.__tags) > id:
233
+ self.end()
234
+
235
+ def element(self, tag, text=None, attrib={}, **extra):
236
+ """
237
+ Add an entire element. This is the same as calling :meth:`start`,
238
+ :meth:`data`, and :meth:`end` in sequence. The *text* argument can be
239
+ omitted.
240
+ """
241
+ self.start(tag, attrib, **extra)
242
+ if text:
243
+ self.data(text)
244
+ self.end(indent=False)
245
+
246
+ def flush(self):
247
+ """Flush the output stream."""
248
+ pass # replaced by the constructor
249
+
250
+
251
+ def _generate_transform(transform_list):
252
+ parts = []
253
+ for type, value in transform_list:
254
+ if (type == 'scale' and (value == (1,) or value == (1, 1))
255
+ or type == 'translate' and value == (0, 0)
256
+ or type == 'rotate' and value == (0,)):
257
+ continue
258
+ if type == 'matrix' and isinstance(value, Affine2DBase):
259
+ value = value.to_values()
260
+ parts.append('{}({})'.format(
261
+ type, ' '.join(_short_float_fmt(x) for x in value)))
262
+ return ' '.join(parts)
263
+
264
+
265
+ def _generate_css(attrib):
266
+ return "; ".join(f"{k}: {v}" for k, v in attrib.items())
267
+
268
+
269
+ _capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'}
270
+
271
+
272
+ def _check_is_str(info, key):
273
+ if not isinstance(info, str):
274
+ raise TypeError(f'Invalid type for {key} metadata. Expected str, not '
275
+ f'{type(info)}.')
276
+
277
+
278
+ def _check_is_iterable_of_str(infos, key):
279
+ if np.iterable(infos):
280
+ for info in infos:
281
+ if not isinstance(info, str):
282
+ raise TypeError(f'Invalid type for {key} metadata. Expected '
283
+ f'iterable of str, not {type(info)}.')
284
+ else:
285
+ raise TypeError(f'Invalid type for {key} metadata. Expected str or '
286
+ f'iterable of str, not {type(infos)}.')
287
+
288
+
289
+ class RendererSVG(RendererBase):
290
+ def __init__(self, width, height, svgwriter, basename=None, image_dpi=72,
291
+ *, metadata=None):
292
+ self.width = width
293
+ self.height = height
294
+ self.writer = XMLWriter(svgwriter)
295
+ self.image_dpi = image_dpi # actual dpi at which we rasterize stuff
296
+
297
+ if basename is None:
298
+ basename = getattr(svgwriter, "name", "")
299
+ if not isinstance(basename, str):
300
+ basename = ""
301
+ self.basename = basename
302
+
303
+ self._groupd = {}
304
+ self._image_counter = itertools.count()
305
+ self._clipd = {}
306
+ self._markers = {}
307
+ self._path_collection_id = 0
308
+ self._hatchd = {}
309
+ self._has_gouraud = False
310
+ self._n_gradients = 0
311
+
312
+ super().__init__()
313
+ self._glyph_map = dict()
314
+ str_height = _short_float_fmt(height)
315
+ str_width = _short_float_fmt(width)
316
+ svgwriter.write(svgProlog)
317
+ self._start_id = self.writer.start(
318
+ 'svg',
319
+ width=f'{str_width}pt',
320
+ height=f'{str_height}pt',
321
+ viewBox=f'0 0 {str_width} {str_height}',
322
+ xmlns="http://www.w3.org/2000/svg",
323
+ version="1.1",
324
+ attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"})
325
+ self._write_metadata(metadata)
326
+ self._write_default_style()
327
+
328
+ def finalize(self):
329
+ self._write_clips()
330
+ self._write_hatches()
331
+ self.writer.close(self._start_id)
332
+ self.writer.flush()
333
+
334
+ def _write_metadata(self, metadata):
335
+ # Add metadata following the Dublin Core Metadata Initiative, and the
336
+ # Creative Commons Rights Expression Language. This is mainly for
337
+ # compatibility with Inkscape.
338
+ if metadata is None:
339
+ metadata = {}
340
+ metadata = {
341
+ 'Format': 'image/svg+xml',
342
+ 'Type': 'http://purl.org/dc/dcmitype/StillImage',
343
+ 'Creator':
344
+ f'Matplotlib v{mpl.__version__}, https://matplotlib.org/',
345
+ **metadata
346
+ }
347
+ writer = self.writer
348
+
349
+ if 'Title' in metadata:
350
+ title = metadata['Title']
351
+ _check_is_str(title, 'Title')
352
+ writer.element('title', text=title)
353
+
354
+ # Special handling.
355
+ date = metadata.get('Date', None)
356
+ if date is not None:
357
+ if isinstance(date, str):
358
+ dates = [date]
359
+ elif isinstance(date, (datetime.datetime, datetime.date)):
360
+ dates = [date.isoformat()]
361
+ elif np.iterable(date):
362
+ dates = []
363
+ for d in date:
364
+ if isinstance(d, str):
365
+ dates.append(d)
366
+ elif isinstance(d, (datetime.datetime, datetime.date)):
367
+ dates.append(d.isoformat())
368
+ else:
369
+ raise TypeError(
370
+ f'Invalid type for Date metadata. '
371
+ f'Expected iterable of str, date, or datetime, '
372
+ f'not {type(d)}.')
373
+ else:
374
+ raise TypeError(f'Invalid type for Date metadata. '
375
+ f'Expected str, date, datetime, or iterable '
376
+ f'of the same, not {type(date)}.')
377
+ metadata['Date'] = '/'.join(dates)
378
+ elif 'Date' not in metadata:
379
+ # Do not add `Date` if the user explicitly set `Date` to `None`
380
+ # Get source date from SOURCE_DATE_EPOCH, if set.
381
+ # See https://reproducible-builds.org/specs/source-date-epoch/
382
+ date = os.getenv("SOURCE_DATE_EPOCH")
383
+ if date:
384
+ date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc)
385
+ metadata['Date'] = date.replace(tzinfo=UTC).isoformat()
386
+ else:
387
+ metadata['Date'] = datetime.datetime.today().isoformat()
388
+
389
+ mid = None
390
+ def ensure_metadata(mid):
391
+ if mid is not None:
392
+ return mid
393
+ mid = writer.start('metadata')
394
+ writer.start('rdf:RDF', attrib={
395
+ 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
396
+ 'xmlns:cc': "http://creativecommons.org/ns#",
397
+ 'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
398
+ })
399
+ writer.start('cc:Work')
400
+ return mid
401
+
402
+ uri = metadata.pop('Type', None)
403
+ if uri is not None:
404
+ mid = ensure_metadata(mid)
405
+ writer.element('dc:type', attrib={'rdf:resource': uri})
406
+
407
+ # Single value only.
408
+ for key in ['Title', 'Coverage', 'Date', 'Description', 'Format',
409
+ 'Identifier', 'Language', 'Relation', 'Source']:
410
+ info = metadata.pop(key, None)
411
+ if info is not None:
412
+ mid = ensure_metadata(mid)
413
+ _check_is_str(info, key)
414
+ writer.element(f'dc:{key.lower()}', text=info)
415
+
416
+ # Multiple Agent values.
417
+ for key in ['Creator', 'Contributor', 'Publisher', 'Rights']:
418
+ agents = metadata.pop(key, None)
419
+ if agents is None:
420
+ continue
421
+
422
+ if isinstance(agents, str):
423
+ agents = [agents]
424
+
425
+ _check_is_iterable_of_str(agents, key)
426
+ # Now we know that we have an iterable of str
427
+ mid = ensure_metadata(mid)
428
+ writer.start(f'dc:{key.lower()}')
429
+ for agent in agents:
430
+ writer.start('cc:Agent')
431
+ writer.element('dc:title', text=agent)
432
+ writer.end('cc:Agent')
433
+ writer.end(f'dc:{key.lower()}')
434
+
435
+ # Multiple values.
436
+ keywords = metadata.pop('Keywords', None)
437
+ if keywords is not None:
438
+ if isinstance(keywords, str):
439
+ keywords = [keywords]
440
+ _check_is_iterable_of_str(keywords, 'Keywords')
441
+ # Now we know that we have an iterable of str
442
+ mid = ensure_metadata(mid)
443
+ writer.start('dc:subject')
444
+ writer.start('rdf:Bag')
445
+ for keyword in keywords:
446
+ writer.element('rdf:li', text=keyword)
447
+ writer.end('rdf:Bag')
448
+ writer.end('dc:subject')
449
+
450
+ if mid is not None:
451
+ writer.close(mid)
452
+
453
+ if metadata:
454
+ raise ValueError('Unknown metadata key(s) passed to SVG writer: ' +
455
+ ','.join(metadata))
456
+
457
+ def _write_default_style(self):
458
+ writer = self.writer
459
+ default_style = _generate_css({
460
+ 'stroke-linejoin': 'round',
461
+ 'stroke-linecap': 'butt'})
462
+ writer.start('defs')
463
+ writer.element('style', type='text/css', text='*{%s}' % default_style)
464
+ writer.end('defs')
465
+
466
+ def _make_id(self, type, content):
467
+ salt = mpl.rcParams['svg.hashsalt']
468
+ if salt is None:
469
+ salt = str(uuid.uuid4())
470
+ m = hashlib.sha256()
471
+ m.update(salt.encode('utf8'))
472
+ m.update(str(content).encode('utf8'))
473
+ return f'{type}{m.hexdigest()[:10]}'
474
+
475
+ def _make_flip_transform(self, transform):
476
+ return transform + Affine2D().scale(1, -1).translate(0, self.height)
477
+
478
+ def _get_hatch(self, gc, rgbFace):
479
+ """
480
+ Create a new hatch pattern
481
+ """
482
+ if rgbFace is not None:
483
+ rgbFace = tuple(rgbFace)
484
+ edge = gc.get_hatch_color()
485
+ if edge is not None:
486
+ edge = tuple(edge)
487
+ dictkey = (gc.get_hatch(), rgbFace, edge)
488
+ oid = self._hatchd.get(dictkey)
489
+ if oid is None:
490
+ oid = self._make_id('h', dictkey)
491
+ self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge), oid)
492
+ else:
493
+ _, oid = oid
494
+ return oid
495
+
496
+ def _write_hatches(self):
497
+ if not len(self._hatchd):
498
+ return
499
+ HATCH_SIZE = 72
500
+ writer = self.writer
501
+ writer.start('defs')
502
+ for (path, face, stroke), oid in self._hatchd.values():
503
+ writer.start(
504
+ 'pattern',
505
+ id=oid,
506
+ patternUnits="userSpaceOnUse",
507
+ x="0", y="0", width=str(HATCH_SIZE),
508
+ height=str(HATCH_SIZE))
509
+ path_data = self._convert_path(
510
+ path,
511
+ Affine2D()
512
+ .scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE),
513
+ simplify=False)
514
+ if face is None:
515
+ fill = 'none'
516
+ else:
517
+ fill = rgb2hex(face)
518
+ writer.element(
519
+ 'rect',
520
+ x="0", y="0", width=str(HATCH_SIZE+1),
521
+ height=str(HATCH_SIZE+1),
522
+ fill=fill)
523
+ hatch_style = {
524
+ 'fill': rgb2hex(stroke),
525
+ 'stroke': rgb2hex(stroke),
526
+ 'stroke-width': str(mpl.rcParams['hatch.linewidth']),
527
+ 'stroke-linecap': 'butt',
528
+ 'stroke-linejoin': 'miter'
529
+ }
530
+ if stroke[3] < 1:
531
+ hatch_style['stroke-opacity'] = str(stroke[3])
532
+ writer.element(
533
+ 'path',
534
+ d=path_data,
535
+ style=_generate_css(hatch_style)
536
+ )
537
+ writer.end('pattern')
538
+ writer.end('defs')
539
+
540
+ def _get_style_dict(self, gc, rgbFace):
541
+ """Generate a style string from the GraphicsContext and rgbFace."""
542
+ attrib = {}
543
+
544
+ forced_alpha = gc.get_forced_alpha()
545
+
546
+ if gc.get_hatch() is not None:
547
+ attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})"
548
+ if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0
549
+ and not forced_alpha):
550
+ attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])
551
+ else:
552
+ if rgbFace is None:
553
+ attrib['fill'] = 'none'
554
+ else:
555
+ if tuple(rgbFace[:3]) != (0, 0, 0):
556
+ attrib['fill'] = rgb2hex(rgbFace)
557
+ if (len(rgbFace) == 4 and rgbFace[3] != 1.0
558
+ and not forced_alpha):
559
+ attrib['fill-opacity'] = _short_float_fmt(rgbFace[3])
560
+
561
+ if forced_alpha and gc.get_alpha() != 1.0:
562
+ attrib['opacity'] = _short_float_fmt(gc.get_alpha())
563
+
564
+ offset, seq = gc.get_dashes()
565
+ if seq is not None:
566
+ attrib['stroke-dasharray'] = ','.join(
567
+ _short_float_fmt(val) for val in seq)
568
+ attrib['stroke-dashoffset'] = _short_float_fmt(float(offset))
569
+
570
+ linewidth = gc.get_linewidth()
571
+ if linewidth:
572
+ rgb = gc.get_rgb()
573
+ attrib['stroke'] = rgb2hex(rgb)
574
+ if not forced_alpha and rgb[3] != 1.0:
575
+ attrib['stroke-opacity'] = _short_float_fmt(rgb[3])
576
+ if linewidth != 1.0:
577
+ attrib['stroke-width'] = _short_float_fmt(linewidth)
578
+ if gc.get_joinstyle() != 'round':
579
+ attrib['stroke-linejoin'] = gc.get_joinstyle()
580
+ if gc.get_capstyle() != 'butt':
581
+ attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()]
582
+
583
+ return attrib
584
+
585
+ def _get_style(self, gc, rgbFace):
586
+ return _generate_css(self._get_style_dict(gc, rgbFace))
587
+
588
+ def _get_clip_attrs(self, gc):
589
+ cliprect = gc.get_clip_rectangle()
590
+ clippath, clippath_trans = gc.get_clip_path()
591
+ if clippath is not None:
592
+ clippath_trans = self._make_flip_transform(clippath_trans)
593
+ dictkey = (id(clippath), str(clippath_trans))
594
+ elif cliprect is not None:
595
+ x, y, w, h = cliprect.bounds
596
+ y = self.height-(y+h)
597
+ dictkey = (x, y, w, h)
598
+ else:
599
+ return {}
600
+ clip = self._clipd.get(dictkey)
601
+ if clip is None:
602
+ oid = self._make_id('p', dictkey)
603
+ if clippath is not None:
604
+ self._clipd[dictkey] = ((clippath, clippath_trans), oid)
605
+ else:
606
+ self._clipd[dictkey] = (dictkey, oid)
607
+ else:
608
+ clip, oid = clip
609
+ return {'clip-path': f'url(#{oid})'}
610
+
611
+ def _write_clips(self):
612
+ if not len(self._clipd):
613
+ return
614
+ writer = self.writer
615
+ writer.start('defs')
616
+ for clip, oid in self._clipd.values():
617
+ writer.start('clipPath', id=oid)
618
+ if len(clip) == 2:
619
+ clippath, clippath_trans = clip
620
+ path_data = self._convert_path(
621
+ clippath, clippath_trans, simplify=False)
622
+ writer.element('path', d=path_data)
623
+ else:
624
+ x, y, w, h = clip
625
+ writer.element(
626
+ 'rect',
627
+ x=_short_float_fmt(x),
628
+ y=_short_float_fmt(y),
629
+ width=_short_float_fmt(w),
630
+ height=_short_float_fmt(h))
631
+ writer.end('clipPath')
632
+ writer.end('defs')
633
+
634
+ def open_group(self, s, gid=None):
635
+ # docstring inherited
636
+ if gid:
637
+ self.writer.start('g', id=gid)
638
+ else:
639
+ self._groupd[s] = self._groupd.get(s, 0) + 1
640
+ self.writer.start('g', id=f"{s}_{self._groupd[s]:d}")
641
+
642
+ def close_group(self, s):
643
+ # docstring inherited
644
+ self.writer.end('g')
645
+
646
+ def option_image_nocomposite(self):
647
+ # docstring inherited
648
+ return not mpl.rcParams['image.composite_image']
649
+
650
+ def _convert_path(self, path, transform=None, clip=None, simplify=None,
651
+ sketch=None):
652
+ if clip:
653
+ clip = (0.0, 0.0, self.width, self.height)
654
+ else:
655
+ clip = None
656
+ return _path.convert_to_string(
657
+ path, transform, clip, simplify, sketch, 6,
658
+ [b'M', b'L', b'Q', b'C', b'z'], False).decode('ascii')
659
+
660
+ def draw_path(self, gc, path, transform, rgbFace=None):
661
+ # docstring inherited
662
+ trans_and_flip = self._make_flip_transform(transform)
663
+ clip = (rgbFace is None and gc.get_hatch_path() is None)
664
+ simplify = path.should_simplify and clip
665
+ path_data = self._convert_path(
666
+ path, trans_and_flip, clip=clip, simplify=simplify,
667
+ sketch=gc.get_sketch_params())
668
+
669
+ if gc.get_url() is not None:
670
+ self.writer.start('a', {'xlink:href': gc.get_url()})
671
+ self.writer.element('path', d=path_data, **self._get_clip_attrs(gc),
672
+ style=self._get_style(gc, rgbFace))
673
+ if gc.get_url() is not None:
674
+ self.writer.end('a')
675
+
676
+ def draw_markers(
677
+ self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
678
+ # docstring inherited
679
+
680
+ if not len(path.vertices):
681
+ return
682
+
683
+ writer = self.writer
684
+ path_data = self._convert_path(
685
+ marker_path,
686
+ marker_trans + Affine2D().scale(1.0, -1.0),
687
+ simplify=False)
688
+ style = self._get_style_dict(gc, rgbFace)
689
+ dictkey = (path_data, _generate_css(style))
690
+ oid = self._markers.get(dictkey)
691
+ style = _generate_css({k: v for k, v in style.items()
692
+ if k.startswith('stroke')})
693
+
694
+ if oid is None:
695
+ oid = self._make_id('m', dictkey)
696
+ writer.start('defs')
697
+ writer.element('path', id=oid, d=path_data, style=style)
698
+ writer.end('defs')
699
+ self._markers[dictkey] = oid
700
+
701
+ writer.start('g', **self._get_clip_attrs(gc))
702
+ trans_and_flip = self._make_flip_transform(trans)
703
+ attrib = {'xlink:href': f'#{oid}'}
704
+ clip = (0, 0, self.width*72, self.height*72)
705
+ for vertices, code in path.iter_segments(
706
+ trans_and_flip, clip=clip, simplify=False):
707
+ if len(vertices):
708
+ x, y = vertices[-2:]
709
+ attrib['x'] = _short_float_fmt(x)
710
+ attrib['y'] = _short_float_fmt(y)
711
+ attrib['style'] = self._get_style(gc, rgbFace)
712
+ writer.element('use', attrib=attrib)
713
+ writer.end('g')
714
+
715
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
716
+ offsets, offset_trans, facecolors, edgecolors,
717
+ linewidths, linestyles, antialiaseds, urls,
718
+ offset_position):
719
+ # Is the optimization worth it? Rough calculation:
720
+ # cost of emitting a path in-line is
721
+ # (len_path + 5) * uses_per_path
722
+ # cost of definition+use is
723
+ # (len_path + 3) + 9 * uses_per_path
724
+ len_path = len(paths[0].vertices) if len(paths) > 0 else 0
725
+ uses_per_path = self._iter_collection_uses_per_path(
726
+ paths, all_transforms, offsets, facecolors, edgecolors)
727
+ should_do_optimization = \
728
+ len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path
729
+ if not should_do_optimization:
730
+ return super().draw_path_collection(
731
+ gc, master_transform, paths, all_transforms,
732
+ offsets, offset_trans, facecolors, edgecolors,
733
+ linewidths, linestyles, antialiaseds, urls,
734
+ offset_position)
735
+
736
+ writer = self.writer
737
+ path_codes = []
738
+ writer.start('defs')
739
+ for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
740
+ master_transform, paths, all_transforms)):
741
+ transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
742
+ d = self._convert_path(path, transform, simplify=False)
743
+ oid = 'C{:x}_{:x}_{}'.format(
744
+ self._path_collection_id, i, self._make_id('', d))
745
+ writer.element('path', id=oid, d=d)
746
+ path_codes.append(oid)
747
+ writer.end('defs')
748
+
749
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
750
+ gc, path_codes, offsets, offset_trans,
751
+ facecolors, edgecolors, linewidths, linestyles,
752
+ antialiaseds, urls, offset_position):
753
+ url = gc0.get_url()
754
+ if url is not None:
755
+ writer.start('a', attrib={'xlink:href': url})
756
+ clip_attrs = self._get_clip_attrs(gc0)
757
+ if clip_attrs:
758
+ writer.start('g', **clip_attrs)
759
+ attrib = {
760
+ 'xlink:href': f'#{path_id}',
761
+ 'x': _short_float_fmt(xo),
762
+ 'y': _short_float_fmt(self.height - yo),
763
+ 'style': self._get_style(gc0, rgbFace)
764
+ }
765
+ writer.element('use', attrib=attrib)
766
+ if clip_attrs:
767
+ writer.end('g')
768
+ if url is not None:
769
+ writer.end('a')
770
+
771
+ self._path_collection_id += 1
772
+
773
+ def _draw_gouraud_triangle(self, transformed_points, colors):
774
+ # This uses a method described here:
775
+ #
776
+ # http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html
777
+ #
778
+ # that uses three overlapping linear gradients to simulate a
779
+ # Gouraud triangle. Each gradient goes from fully opaque in
780
+ # one corner to fully transparent along the opposite edge.
781
+ # The line between the stop points is perpendicular to the
782
+ # opposite edge. Underlying these three gradients is a solid
783
+ # triangle whose color is the average of all three points.
784
+
785
+ avg_color = np.average(colors, axis=0)
786
+ if avg_color[-1] == 0:
787
+ # Skip fully-transparent triangles
788
+ return
789
+
790
+ writer = self.writer
791
+ writer.start('defs')
792
+ for i in range(3):
793
+ x1, y1 = transformed_points[i]
794
+ x2, y2 = transformed_points[(i + 1) % 3]
795
+ x3, y3 = transformed_points[(i + 2) % 3]
796
+ rgba_color = colors[i]
797
+
798
+ if x2 == x3:
799
+ xb = x2
800
+ yb = y1
801
+ elif y2 == y3:
802
+ xb = x1
803
+ yb = y2
804
+ else:
805
+ m1 = (y2 - y3) / (x2 - x3)
806
+ b1 = y2 - (m1 * x2)
807
+ m2 = -(1.0 / m1)
808
+ b2 = y1 - (m2 * x1)
809
+ xb = (-b1 + b2) / (m1 - m2)
810
+ yb = m2 * xb + b2
811
+
812
+ writer.start(
813
+ 'linearGradient',
814
+ id=f"GR{self._n_gradients:x}_{i:d}",
815
+ gradientUnits="userSpaceOnUse",
816
+ x1=_short_float_fmt(x1), y1=_short_float_fmt(y1),
817
+ x2=_short_float_fmt(xb), y2=_short_float_fmt(yb))
818
+ writer.element(
819
+ 'stop',
820
+ offset='1',
821
+ style=_generate_css({
822
+ 'stop-color': rgb2hex(avg_color),
823
+ 'stop-opacity': _short_float_fmt(rgba_color[-1])}))
824
+ writer.element(
825
+ 'stop',
826
+ offset='0',
827
+ style=_generate_css({'stop-color': rgb2hex(rgba_color),
828
+ 'stop-opacity': "0"}))
829
+
830
+ writer.end('linearGradient')
831
+
832
+ writer.end('defs')
833
+
834
+ # triangle formation using "path"
835
+ dpath = (f"M {_short_float_fmt(x1)},{_short_float_fmt(y1)}"
836
+ f" L {_short_float_fmt(x2)},{_short_float_fmt(y2)}"
837
+ f" {_short_float_fmt(x3)},{_short_float_fmt(y3)} Z")
838
+
839
+ writer.element(
840
+ 'path',
841
+ attrib={'d': dpath,
842
+ 'fill': rgb2hex(avg_color),
843
+ 'fill-opacity': '1',
844
+ 'shape-rendering': "crispEdges"})
845
+
846
+ writer.start(
847
+ 'g',
848
+ attrib={'stroke': "none",
849
+ 'stroke-width': "0",
850
+ 'shape-rendering': "crispEdges",
851
+ 'filter': "url(#colorMat)"})
852
+
853
+ writer.element(
854
+ 'path',
855
+ attrib={'d': dpath,
856
+ 'fill': f'url(#GR{self._n_gradients:x}_0)',
857
+ 'shape-rendering': "crispEdges"})
858
+
859
+ writer.element(
860
+ 'path',
861
+ attrib={'d': dpath,
862
+ 'fill': f'url(#GR{self._n_gradients:x}_1)',
863
+ 'filter': 'url(#colorAdd)',
864
+ 'shape-rendering': "crispEdges"})
865
+
866
+ writer.element(
867
+ 'path',
868
+ attrib={'d': dpath,
869
+ 'fill': f'url(#GR{self._n_gradients:x}_2)',
870
+ 'filter': 'url(#colorAdd)',
871
+ 'shape-rendering': "crispEdges"})
872
+
873
+ writer.end('g')
874
+
875
+ self._n_gradients += 1
876
+
877
+ def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
878
+ transform):
879
+ writer = self.writer
880
+ writer.start('g', **self._get_clip_attrs(gc))
881
+ transform = transform.frozen()
882
+ trans_and_flip = self._make_flip_transform(transform)
883
+
884
+ if not self._has_gouraud:
885
+ self._has_gouraud = True
886
+ writer.start(
887
+ 'filter',
888
+ id='colorAdd')
889
+ writer.element(
890
+ 'feComposite',
891
+ attrib={'in': 'SourceGraphic'},
892
+ in2='BackgroundImage',
893
+ operator='arithmetic',
894
+ k2="1", k3="1")
895
+ writer.end('filter')
896
+ # feColorMatrix filter to correct opacity
897
+ writer.start(
898
+ 'filter',
899
+ id='colorMat')
900
+ writer.element(
901
+ 'feColorMatrix',
902
+ attrib={'type': 'matrix'},
903
+ values='1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n1 1 1 1 0 \n0 0 0 0 1 ')
904
+ writer.end('filter')
905
+
906
+ for points, colors in zip(triangles_array, colors_array):
907
+ self._draw_gouraud_triangle(trans_and_flip.transform(points), colors)
908
+ writer.end('g')
909
+
910
+ def option_scale_image(self):
911
+ # docstring inherited
912
+ return True
913
+
914
+ def get_image_magnification(self):
915
+ return self.image_dpi / 72.0
916
+
917
+ def draw_image(self, gc, x, y, im, transform=None):
918
+ # docstring inherited
919
+
920
+ h, w = im.shape[:2]
921
+
922
+ if w == 0 or h == 0:
923
+ return
924
+
925
+ clip_attrs = self._get_clip_attrs(gc)
926
+ if clip_attrs:
927
+ # Can't apply clip-path directly to the image because the image has
928
+ # a transformation, which would also be applied to the clip-path.
929
+ self.writer.start('g', **clip_attrs)
930
+
931
+ url = gc.get_url()
932
+ if url is not None:
933
+ self.writer.start('a', attrib={'xlink:href': url})
934
+
935
+ attrib = {}
936
+ oid = gc.get_gid()
937
+ if mpl.rcParams['svg.image_inline']:
938
+ buf = BytesIO()
939
+ Image.fromarray(im).save(buf, format="png")
940
+ oid = oid or self._make_id('image', buf.getvalue())
941
+ attrib['xlink:href'] = (
942
+ "data:image/png;base64,\n" +
943
+ base64.b64encode(buf.getvalue()).decode('ascii'))
944
+ else:
945
+ if self.basename is None:
946
+ raise ValueError("Cannot save image data to filesystem when "
947
+ "writing SVG to an in-memory buffer")
948
+ filename = f'{self.basename}.image{next(self._image_counter)}.png'
949
+ _log.info('Writing image file for inclusion: %s', filename)
950
+ Image.fromarray(im).save(filename)
951
+ oid = oid or 'Im_' + self._make_id('image', filename)
952
+ attrib['xlink:href'] = filename
953
+ attrib['id'] = oid
954
+
955
+ if transform is None:
956
+ w = 72.0 * w / self.image_dpi
957
+ h = 72.0 * h / self.image_dpi
958
+
959
+ self.writer.element(
960
+ 'image',
961
+ transform=_generate_transform([
962
+ ('scale', (1, -1)), ('translate', (0, -h))]),
963
+ x=_short_float_fmt(x),
964
+ y=_short_float_fmt(-(self.height - y - h)),
965
+ width=_short_float_fmt(w), height=_short_float_fmt(h),
966
+ attrib=attrib)
967
+ else:
968
+ alpha = gc.get_alpha()
969
+ if alpha != 1.0:
970
+ attrib['opacity'] = _short_float_fmt(alpha)
971
+
972
+ flipped = (
973
+ Affine2D().scale(1.0 / w, 1.0 / h) +
974
+ transform +
975
+ Affine2D()
976
+ .translate(x, y)
977
+ .scale(1.0, -1.0)
978
+ .translate(0.0, self.height))
979
+
980
+ attrib['transform'] = _generate_transform(
981
+ [('matrix', flipped.frozen())])
982
+ attrib['style'] = (
983
+ 'image-rendering:crisp-edges;'
984
+ 'image-rendering:pixelated')
985
+ self.writer.element(
986
+ 'image',
987
+ width=_short_float_fmt(w), height=_short_float_fmt(h),
988
+ attrib=attrib)
989
+
990
+ if url is not None:
991
+ self.writer.end('a')
992
+ if clip_attrs:
993
+ self.writer.end('g')
994
+
995
+ def _update_glyph_map_defs(self, glyph_map_new):
996
+ """
997
+ Emit definitions for not-yet-defined glyphs, and record them as having
998
+ been defined.
999
+ """
1000
+ writer = self.writer
1001
+ if glyph_map_new:
1002
+ writer.start('defs')
1003
+ for char_id, (vertices, codes) in glyph_map_new.items():
1004
+ char_id = self._adjust_char_id(char_id)
1005
+ # x64 to go back to FreeType's internal (integral) units.
1006
+ path_data = self._convert_path(
1007
+ Path(vertices * 64, codes), simplify=False)
1008
+ writer.element(
1009
+ 'path', id=char_id, d=path_data,
1010
+ transform=_generate_transform([('scale', (1 / 64,))]))
1011
+ writer.end('defs')
1012
+ self._glyph_map.update(glyph_map_new)
1013
+
1014
+ def _adjust_char_id(self, char_id):
1015
+ return char_id.replace("%20", "_")
1016
+
1017
+ def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None):
1018
+ # docstring inherited
1019
+ writer = self.writer
1020
+
1021
+ writer.comment(s)
1022
+
1023
+ glyph_map = self._glyph_map
1024
+
1025
+ text2path = self._text2path
1026
+ color = rgb2hex(gc.get_rgb())
1027
+ fontsize = prop.get_size_in_points()
1028
+
1029
+ style = {}
1030
+ if color != '#000000':
1031
+ style['fill'] = color
1032
+ alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]
1033
+ if alpha != 1:
1034
+ style['opacity'] = _short_float_fmt(alpha)
1035
+ font_scale = fontsize / text2path.FONT_SCALE
1036
+ attrib = {
1037
+ 'style': _generate_css(style),
1038
+ 'transform': _generate_transform([
1039
+ ('translate', (x, y)),
1040
+ ('rotate', (-angle,)),
1041
+ ('scale', (font_scale, -font_scale))]),
1042
+ }
1043
+ writer.start('g', attrib=attrib)
1044
+
1045
+ if not ismath:
1046
+ font = text2path._get_font(prop)
1047
+ _glyphs = text2path.get_glyphs_with_font(
1048
+ font, s, glyph_map=glyph_map, return_new_glyphs_only=True)
1049
+ glyph_info, glyph_map_new, rects = _glyphs
1050
+ self._update_glyph_map_defs(glyph_map_new)
1051
+
1052
+ for glyph_id, xposition, yposition, scale in glyph_info:
1053
+ attrib = {'xlink:href': f'#{glyph_id}'}
1054
+ if xposition != 0.0:
1055
+ attrib['x'] = _short_float_fmt(xposition)
1056
+ if yposition != 0.0:
1057
+ attrib['y'] = _short_float_fmt(yposition)
1058
+ writer.element('use', attrib=attrib)
1059
+
1060
+ else:
1061
+ if ismath == "TeX":
1062
+ _glyphs = text2path.get_glyphs_tex(
1063
+ prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)
1064
+ else:
1065
+ _glyphs = text2path.get_glyphs_mathtext(
1066
+ prop, s, glyph_map=glyph_map, return_new_glyphs_only=True)
1067
+ glyph_info, glyph_map_new, rects = _glyphs
1068
+ self._update_glyph_map_defs(glyph_map_new)
1069
+
1070
+ for char_id, xposition, yposition, scale in glyph_info:
1071
+ char_id = self._adjust_char_id(char_id)
1072
+ writer.element(
1073
+ 'use',
1074
+ transform=_generate_transform([
1075
+ ('translate', (xposition, yposition)),
1076
+ ('scale', (scale,)),
1077
+ ]),
1078
+ attrib={'xlink:href': f'#{char_id}'})
1079
+
1080
+ for verts, codes in rects:
1081
+ path = Path(verts, codes)
1082
+ path_data = self._convert_path(path, simplify=False)
1083
+ writer.element('path', d=path_data)
1084
+
1085
+ writer.end('g')
1086
+
1087
+ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None):
1088
+ # NOTE: If you change the font styling CSS, then be sure the check for
1089
+ # svg.fonttype = none in `lib/matplotlib/testing/compare.py::convert` remains in
1090
+ # sync. Also be sure to re-generate any SVG using this mode, or else such tests
1091
+ # will fail to use the right converter for the expected images, and they will
1092
+ # fail strangely.
1093
+ writer = self.writer
1094
+
1095
+ color = rgb2hex(gc.get_rgb())
1096
+ style = {}
1097
+ if color != '#000000':
1098
+ style['fill'] = color
1099
+
1100
+ alpha = gc.get_alpha() if gc.get_forced_alpha() else gc.get_rgb()[3]
1101
+ if alpha != 1:
1102
+ style['opacity'] = _short_float_fmt(alpha)
1103
+
1104
+ if not ismath:
1105
+ attrib = {}
1106
+
1107
+ font_parts = []
1108
+ if prop.get_style() != 'normal':
1109
+ font_parts.append(prop.get_style())
1110
+ if prop.get_variant() != 'normal':
1111
+ font_parts.append(prop.get_variant())
1112
+ weight = fm.weight_dict[prop.get_weight()]
1113
+ if weight != 400:
1114
+ font_parts.append(f'{weight}')
1115
+
1116
+ def _normalize_sans(name):
1117
+ return 'sans-serif' if name in ['sans', 'sans serif'] else name
1118
+
1119
+ def _expand_family_entry(fn):
1120
+ fn = _normalize_sans(fn)
1121
+ # prepend generic font families with all configured font names
1122
+ if fn in fm.font_family_aliases:
1123
+ # get all of the font names and fix spelling of sans-serif
1124
+ # (we accept 3 ways CSS only supports 1)
1125
+ for name in fm.FontManager._expand_aliases(fn):
1126
+ yield _normalize_sans(name)
1127
+ # whether a generic name or a family name, it must appear at
1128
+ # least once
1129
+ yield fn
1130
+
1131
+ def _get_all_quoted_names(prop):
1132
+ # only quote specific names, not generic names
1133
+ return [name if name in fm.font_family_aliases else repr(name)
1134
+ for entry in prop.get_family()
1135
+ for name in _expand_family_entry(entry)]
1136
+
1137
+ font_parts.extend([
1138
+ f'{_short_float_fmt(prop.get_size())}px',
1139
+ # ensure expansion, quoting, and dedupe of font names
1140
+ ", ".join(dict.fromkeys(_get_all_quoted_names(prop)))
1141
+ ])
1142
+ style['font'] = ' '.join(font_parts)
1143
+ if prop.get_stretch() != 'normal':
1144
+ style['font-stretch'] = prop.get_stretch()
1145
+ attrib['style'] = _generate_css(style)
1146
+
1147
+ if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"):
1148
+ # If text anchoring can be supported, get the original
1149
+ # coordinates and add alignment information.
1150
+
1151
+ # Get anchor coordinates.
1152
+ transform = mtext.get_transform()
1153
+ ax, ay = transform.transform(mtext.get_unitless_position())
1154
+ ay = self.height - ay
1155
+
1156
+ # Don't do vertical anchor alignment. Most applications do not
1157
+ # support 'alignment-baseline' yet. Apply the vertical layout
1158
+ # to the anchor point manually for now.
1159
+ angle_rad = np.deg2rad(angle)
1160
+ dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)])
1161
+ v_offset = np.dot(dir_vert, [(x - ax), (y - ay)])
1162
+ ax = ax + v_offset * dir_vert[0]
1163
+ ay = ay + v_offset * dir_vert[1]
1164
+
1165
+ ha_mpl_to_svg = {'left': 'start', 'right': 'end',
1166
+ 'center': 'middle'}
1167
+ style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()]
1168
+
1169
+ attrib['x'] = _short_float_fmt(ax)
1170
+ attrib['y'] = _short_float_fmt(ay)
1171
+ attrib['style'] = _generate_css(style)
1172
+ attrib['transform'] = _generate_transform([
1173
+ ("rotate", (-angle, ax, ay))])
1174
+
1175
+ else:
1176
+ attrib['transform'] = _generate_transform([
1177
+ ('translate', (x, y)),
1178
+ ('rotate', (-angle,))])
1179
+
1180
+ writer.element('text', s, attrib=attrib)
1181
+
1182
+ else:
1183
+ writer.comment(s)
1184
+
1185
+ width, height, descent, glyphs, rects = \
1186
+ self._text2path.mathtext_parser.parse(s, 72, prop)
1187
+
1188
+ # Apply attributes to 'g', not 'text', because we likely have some
1189
+ # rectangles as well with the same style and transformation.
1190
+ writer.start('g',
1191
+ style=_generate_css(style),
1192
+ transform=_generate_transform([
1193
+ ('translate', (x, y)),
1194
+ ('rotate', (-angle,))]),
1195
+ )
1196
+
1197
+ writer.start('text')
1198
+
1199
+ # Sort the characters by font, and output one tspan for each.
1200
+ spans = {}
1201
+ for font, fontsize, thetext, new_x, new_y in glyphs:
1202
+ entry = fm.ttfFontProperty(font)
1203
+ font_parts = []
1204
+ if entry.style != 'normal':
1205
+ font_parts.append(entry.style)
1206
+ if entry.variant != 'normal':
1207
+ font_parts.append(entry.variant)
1208
+ if entry.weight != 400:
1209
+ font_parts.append(f'{entry.weight}')
1210
+ font_parts.extend([
1211
+ f'{_short_float_fmt(fontsize)}px',
1212
+ f'{entry.name!r}', # ensure quoting
1213
+ ])
1214
+ style = {'font': ' '.join(font_parts)}
1215
+ if entry.stretch != 'normal':
1216
+ style['font-stretch'] = entry.stretch
1217
+ style = _generate_css(style)
1218
+ if thetext == 32:
1219
+ thetext = 0xa0 # non-breaking space
1220
+ spans.setdefault(style, []).append((new_x, -new_y, thetext))
1221
+
1222
+ for style, chars in spans.items():
1223
+ chars.sort()
1224
+
1225
+ if len({y for x, y, t in chars}) == 1: # Are all y's the same?
1226
+ ys = str(chars[0][1])
1227
+ else:
1228
+ ys = ' '.join(str(c[1]) for c in chars)
1229
+
1230
+ attrib = {
1231
+ 'style': style,
1232
+ 'x': ' '.join(_short_float_fmt(c[0]) for c in chars),
1233
+ 'y': ys
1234
+ }
1235
+
1236
+ writer.element(
1237
+ 'tspan',
1238
+ ''.join(chr(c[2]) for c in chars),
1239
+ attrib=attrib)
1240
+
1241
+ writer.end('text')
1242
+
1243
+ for x, y, width, height in rects:
1244
+ writer.element(
1245
+ 'rect',
1246
+ x=_short_float_fmt(x),
1247
+ y=_short_float_fmt(-y-1),
1248
+ width=_short_float_fmt(width),
1249
+ height=_short_float_fmt(height)
1250
+ )
1251
+
1252
+ writer.end('g')
1253
+
1254
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
1255
+ # docstring inherited
1256
+
1257
+ clip_attrs = self._get_clip_attrs(gc)
1258
+ if clip_attrs:
1259
+ # Cannot apply clip-path directly to the text, because
1260
+ # it has a transformation
1261
+ self.writer.start('g', **clip_attrs)
1262
+
1263
+ if gc.get_url() is not None:
1264
+ self.writer.start('a', {'xlink:href': gc.get_url()})
1265
+
1266
+ if mpl.rcParams['svg.fonttype'] == 'path':
1267
+ self._draw_text_as_path(gc, x, y, s, prop, angle, ismath, mtext)
1268
+ else:
1269
+ self._draw_text_as_text(gc, x, y, s, prop, angle, ismath, mtext)
1270
+
1271
+ if gc.get_url() is not None:
1272
+ self.writer.end('a')
1273
+
1274
+ if clip_attrs:
1275
+ self.writer.end('g')
1276
+
1277
+ def flipy(self):
1278
+ # docstring inherited
1279
+ return True
1280
+
1281
+ def get_canvas_width_height(self):
1282
+ # docstring inherited
1283
+ return self.width, self.height
1284
+
1285
+ def get_text_width_height_descent(self, s, prop, ismath):
1286
+ # docstring inherited
1287
+ return self._text2path.get_text_width_height_descent(s, prop, ismath)
1288
+
1289
+
1290
+ class FigureCanvasSVG(FigureCanvasBase):
1291
+ filetypes = {'svg': 'Scalable Vector Graphics',
1292
+ 'svgz': 'Scalable Vector Graphics'}
1293
+
1294
+ fixed_dpi = 72
1295
+
1296
+ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
1297
+ """
1298
+ Parameters
1299
+ ----------
1300
+ filename : str or path-like or file-like
1301
+ Output target; if a string, a file will be opened for writing.
1302
+
1303
+ metadata : dict[str, Any], optional
1304
+ Metadata in the SVG file defined as key-value pairs of strings,
1305
+ datetimes, or lists of strings, e.g., ``{'Creator': 'My software',
1306
+ 'Contributor': ['Me', 'My Friend'], 'Title': 'Awesome'}``.
1307
+
1308
+ The standard keys and their value types are:
1309
+
1310
+ * *str*: ``'Coverage'``, ``'Description'``, ``'Format'``,
1311
+ ``'Identifier'``, ``'Language'``, ``'Relation'``, ``'Source'``,
1312
+ ``'Title'``, and ``'Type'``.
1313
+ * *str* or *list of str*: ``'Contributor'``, ``'Creator'``,
1314
+ ``'Keywords'``, ``'Publisher'``, and ``'Rights'``.
1315
+ * *str*, *date*, *datetime*, or *tuple* of same: ``'Date'``. If a
1316
+ non-*str*, then it will be formatted as ISO 8601.
1317
+
1318
+ Values have been predefined for ``'Creator'``, ``'Date'``,
1319
+ ``'Format'``, and ``'Type'``. They can be removed by setting them
1320
+ to `None`.
1321
+
1322
+ Information is encoded as `Dublin Core Metadata`__.
1323
+
1324
+ .. _DC: https://www.dublincore.org/specifications/dublin-core/
1325
+
1326
+ __ DC_
1327
+ """
1328
+ with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh:
1329
+ if not cbook.file_requires_unicode(fh):
1330
+ fh = codecs.getwriter('utf-8')(fh)
1331
+ dpi = self.figure.dpi
1332
+ self.figure.dpi = 72
1333
+ width, height = self.figure.get_size_inches()
1334
+ w, h = width * 72, height * 72
1335
+ renderer = MixedModeRenderer(
1336
+ self.figure, width, height, dpi,
1337
+ RendererSVG(w, h, fh, image_dpi=dpi, metadata=metadata),
1338
+ bbox_inches_restore=bbox_inches_restore)
1339
+ self.figure.draw(renderer)
1340
+ renderer.finalize()
1341
+
1342
+ def print_svgz(self, filename, **kwargs):
1343
+ with cbook.open_file_cm(filename, "wb") as fh, \
1344
+ gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter:
1345
+ return self.print_svg(gzipwriter, **kwargs)
1346
+
1347
+ def get_default_filetype(self):
1348
+ return 'svg'
1349
+
1350
+ def draw(self):
1351
+ self.figure.draw_without_rendering()
1352
+ return super().draw()
1353
+
1354
+
1355
+ FigureManagerSVG = FigureManagerBase
1356
+
1357
+
1358
+ svgProlog = """\
1359
+ <?xml version="1.0" encoding="utf-8" standalone="no"?>
1360
+ <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
1361
+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
1362
+ """
1363
+
1364
+
1365
+ @_Backend.export
1366
+ class _BackendSVG(_Backend):
1367
+ backend_version = mpl.__version__
1368
+ FigureCanvas = FigureCanvasSVG
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_template.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A fully functional, do-nothing backend intended as a template for backend
3
+ writers. It is fully functional in that you can select it as a backend e.g.
4
+ with ::
5
+
6
+ import matplotlib
7
+ matplotlib.use("template")
8
+
9
+ and your program will (should!) run without error, though no output is
10
+ produced. This provides a starting point for backend writers; you can
11
+ selectively implement drawing methods (`~.RendererTemplate.draw_path`,
12
+ `~.RendererTemplate.draw_image`, etc.) and slowly see your figure come to life
13
+ instead having to have a full-blown implementation before getting any results.
14
+
15
+ Copy this file to a directory outside the Matplotlib source tree, somewhere
16
+ where Python can import it (by adding the directory to your ``sys.path`` or by
17
+ packaging it as a normal Python package); if the backend is importable as
18
+ ``import my.backend`` you can then select it using ::
19
+
20
+ import matplotlib
21
+ matplotlib.use("module://my.backend")
22
+
23
+ If your backend implements support for saving figures (i.e. has a `print_xyz`
24
+ method), you can register it as the default handler for a given file type::
25
+
26
+ from matplotlib.backend_bases import register_backend
27
+ register_backend('xyz', 'my_backend', 'XYZ File Format')
28
+ ...
29
+ plt.savefig("figure.xyz")
30
+ """
31
+
32
+ from matplotlib import _api
33
+ from matplotlib._pylab_helpers import Gcf
34
+ from matplotlib.backend_bases import (
35
+ FigureCanvasBase, FigureManagerBase, GraphicsContextBase, RendererBase)
36
+ from matplotlib.figure import Figure
37
+
38
+
39
+ class RendererTemplate(RendererBase):
40
+ """
41
+ The renderer handles drawing/rendering operations.
42
+
43
+ This is a minimal do-nothing class that can be used to get started when
44
+ writing a new backend. Refer to `.backend_bases.RendererBase` for
45
+ documentation of the methods.
46
+ """
47
+
48
+ def __init__(self, dpi):
49
+ super().__init__()
50
+ self.dpi = dpi
51
+
52
+ def draw_path(self, gc, path, transform, rgbFace=None):
53
+ pass
54
+
55
+ # draw_markers is optional, and we get more correct relative
56
+ # timings by leaving it out. backend implementers concerned with
57
+ # performance will probably want to implement it
58
+ # def draw_markers(self, gc, marker_path, marker_trans, path, trans,
59
+ # rgbFace=None):
60
+ # pass
61
+
62
+ # draw_path_collection is optional, and we get more correct
63
+ # relative timings by leaving it out. backend implementers concerned with
64
+ # performance will probably want to implement it
65
+ # def draw_path_collection(self, gc, master_transform, paths,
66
+ # all_transforms, offsets, offset_trans,
67
+ # facecolors, edgecolors, linewidths, linestyles,
68
+ # antialiaseds):
69
+ # pass
70
+
71
+ # draw_quad_mesh is optional, and we get more correct
72
+ # relative timings by leaving it out. backend implementers concerned with
73
+ # performance will probably want to implement it
74
+ # def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
75
+ # coordinates, offsets, offsetTrans, facecolors,
76
+ # antialiased, edgecolors):
77
+ # pass
78
+
79
+ def draw_image(self, gc, x, y, im):
80
+ pass
81
+
82
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
83
+ pass
84
+
85
+ def flipy(self):
86
+ # docstring inherited
87
+ return True
88
+
89
+ def get_canvas_width_height(self):
90
+ # docstring inherited
91
+ return 100, 100
92
+
93
+ def get_text_width_height_descent(self, s, prop, ismath):
94
+ return 1, 1, 1
95
+
96
+ def new_gc(self):
97
+ # docstring inherited
98
+ return GraphicsContextTemplate()
99
+
100
+ def points_to_pixels(self, points):
101
+ # if backend doesn't have dpi, e.g., postscript or svg
102
+ return points
103
+ # elif backend assumes a value for pixels_per_inch
104
+ # return points/72.0 * self.dpi.get() * pixels_per_inch/72.0
105
+ # else
106
+ # return points/72.0 * self.dpi.get()
107
+
108
+
109
+ class GraphicsContextTemplate(GraphicsContextBase):
110
+ """
111
+ The graphics context provides the color, line styles, etc. See the cairo
112
+ and postscript backends for examples of mapping the graphics context
113
+ attributes (cap styles, join styles, line widths, colors) to a particular
114
+ backend. In cairo this is done by wrapping a cairo.Context object and
115
+ forwarding the appropriate calls to it using a dictionary mapping styles
116
+ to gdk constants. In Postscript, all the work is done by the renderer,
117
+ mapping line styles to postscript calls.
118
+
119
+ If it's more appropriate to do the mapping at the renderer level (as in
120
+ the postscript backend), you don't need to override any of the GC methods.
121
+ If it's more appropriate to wrap an instance (as in the cairo backend) and
122
+ do the mapping here, you'll need to override several of the setter
123
+ methods.
124
+
125
+ The base GraphicsContext stores colors as an RGB tuple on the unit
126
+ interval, e.g., (0.5, 0.0, 1.0). You may need to map this to colors
127
+ appropriate for your backend.
128
+ """
129
+
130
+
131
+ ########################################################################
132
+ #
133
+ # The following functions and classes are for pyplot and implement
134
+ # window/figure managers, etc.
135
+ #
136
+ ########################################################################
137
+
138
+
139
+ class FigureManagerTemplate(FigureManagerBase):
140
+ """
141
+ Helper class for pyplot mode, wraps everything up into a neat bundle.
142
+
143
+ For non-interactive backends, the base class is sufficient. For
144
+ interactive backends, see the documentation of the `.FigureManagerBase`
145
+ class for the list of methods that can/should be overridden.
146
+ """
147
+
148
+
149
+ class FigureCanvasTemplate(FigureCanvasBase):
150
+ """
151
+ The canvas the figure renders into. Calls the draw and print fig
152
+ methods, creates the renderers, etc.
153
+
154
+ Note: GUI templates will want to connect events for button presses,
155
+ mouse movements and key presses to functions that call the base
156
+ class methods button_press_event, button_release_event,
157
+ motion_notify_event, key_press_event, and key_release_event. See the
158
+ implementations of the interactive backends for examples.
159
+
160
+ Attributes
161
+ ----------
162
+ figure : `~matplotlib.figure.Figure`
163
+ A high-level Figure instance
164
+ """
165
+
166
+ # The instantiated manager class. For further customization,
167
+ # ``FigureManager.create_with_canvas`` can also be overridden; see the
168
+ # wx-based backends for an example.
169
+ manager_class = FigureManagerTemplate
170
+
171
+ def draw(self):
172
+ """
173
+ Draw the figure using the renderer.
174
+
175
+ It is important that this method actually walk the artist tree
176
+ even if not output is produced because this will trigger
177
+ deferred work (like computing limits auto-limits and tick
178
+ values) that users may want access to before saving to disk.
179
+ """
180
+ renderer = RendererTemplate(self.figure.dpi)
181
+ self.figure.draw(renderer)
182
+
183
+ # You should provide a print_xxx function for every file format
184
+ # you can write.
185
+
186
+ # If the file type is not in the base set of filetypes,
187
+ # you should add it to the class-scope filetypes dictionary as follows:
188
+ filetypes = {**FigureCanvasBase.filetypes, 'foo': 'My magic Foo format'}
189
+
190
+ def print_foo(self, filename, **kwargs):
191
+ """
192
+ Write out format foo.
193
+
194
+ This method is normally called via `.Figure.savefig` and
195
+ `.FigureCanvasBase.print_figure`, which take care of setting the figure
196
+ facecolor, edgecolor, and dpi to the desired output values, and will
197
+ restore them to the original values. Therefore, `print_foo` does not
198
+ need to handle these settings.
199
+ """
200
+ self.draw()
201
+
202
+ def get_default_filetype(self):
203
+ return 'foo'
204
+
205
+
206
+ ########################################################################
207
+ #
208
+ # Now just provide the standard names that backend.__init__ is expecting
209
+ #
210
+ ########################################################################
211
+
212
+ FigureCanvas = FigureCanvasTemplate
213
+ FigureManager = FigureManagerTemplate
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_webagg_core.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Displays Agg images in the browser, with interactivity."""
2
+ # The WebAgg backend is divided into two modules:
3
+ #
4
+ # - `backend_webagg_core.py` contains code necessary to embed a WebAgg
5
+ # plot inside of a web application, and communicate in an abstract
6
+ # way over a web socket.
7
+ #
8
+ # - `backend_webagg.py` contains a concrete implementation of a basic
9
+ # application, implemented with asyncio.
10
+
11
+ import asyncio
12
+ import datetime
13
+ from io import BytesIO, StringIO
14
+ import json
15
+ import logging
16
+ import os
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ from PIL import Image
21
+
22
+ from matplotlib import _api, backend_bases, backend_tools
23
+ from matplotlib.backends import backend_agg
24
+ from matplotlib.backend_bases import (
25
+ _Backend, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
26
+
27
+ _log = logging.getLogger(__name__)
28
+
29
+ _SPECIAL_KEYS_LUT = {'Alt': 'alt',
30
+ 'AltGraph': 'alt',
31
+ 'CapsLock': 'caps_lock',
32
+ 'Control': 'control',
33
+ 'Meta': 'meta',
34
+ 'NumLock': 'num_lock',
35
+ 'ScrollLock': 'scroll_lock',
36
+ 'Shift': 'shift',
37
+ 'Super': 'super',
38
+ 'Enter': 'enter',
39
+ 'Tab': 'tab',
40
+ 'ArrowDown': 'down',
41
+ 'ArrowLeft': 'left',
42
+ 'ArrowRight': 'right',
43
+ 'ArrowUp': 'up',
44
+ 'End': 'end',
45
+ 'Home': 'home',
46
+ 'PageDown': 'pagedown',
47
+ 'PageUp': 'pageup',
48
+ 'Backspace': 'backspace',
49
+ 'Delete': 'delete',
50
+ 'Insert': 'insert',
51
+ 'Escape': 'escape',
52
+ 'Pause': 'pause',
53
+ 'Select': 'select',
54
+ 'Dead': 'dead',
55
+ 'F1': 'f1',
56
+ 'F2': 'f2',
57
+ 'F3': 'f3',
58
+ 'F4': 'f4',
59
+ 'F5': 'f5',
60
+ 'F6': 'f6',
61
+ 'F7': 'f7',
62
+ 'F8': 'f8',
63
+ 'F9': 'f9',
64
+ 'F10': 'f10',
65
+ 'F11': 'f11',
66
+ 'F12': 'f12'}
67
+
68
+
69
+ def _handle_key(key):
70
+ """Handle key values"""
71
+ value = key[key.index('k') + 1:]
72
+ if 'shift+' in key:
73
+ if len(value) == 1:
74
+ key = key.replace('shift+', '')
75
+ if value in _SPECIAL_KEYS_LUT:
76
+ value = _SPECIAL_KEYS_LUT[value]
77
+ key = key[:key.index('k')] + value
78
+ return key
79
+
80
+
81
+ class TimerTornado(backend_bases.TimerBase):
82
+ def __init__(self, *args, **kwargs):
83
+ self._timer = None
84
+ super().__init__(*args, **kwargs)
85
+
86
+ def _timer_start(self):
87
+ import tornado
88
+
89
+ self._timer_stop()
90
+ if self._single:
91
+ ioloop = tornado.ioloop.IOLoop.instance()
92
+ self._timer = ioloop.add_timeout(
93
+ datetime.timedelta(milliseconds=self.interval),
94
+ self._on_timer)
95
+ else:
96
+ self._timer = tornado.ioloop.PeriodicCallback(
97
+ self._on_timer,
98
+ max(self.interval, 1e-6))
99
+ self._timer.start()
100
+
101
+ def _timer_stop(self):
102
+ import tornado
103
+
104
+ if self._timer is None:
105
+ return
106
+ elif self._single:
107
+ ioloop = tornado.ioloop.IOLoop.instance()
108
+ ioloop.remove_timeout(self._timer)
109
+ else:
110
+ self._timer.stop()
111
+ self._timer = None
112
+
113
+ def _timer_set_interval(self):
114
+ # Only stop and restart it if the timer has already been started
115
+ if self._timer is not None:
116
+ self._timer_stop()
117
+ self._timer_start()
118
+
119
+
120
+ class TimerAsyncio(backend_bases.TimerBase):
121
+ def __init__(self, *args, **kwargs):
122
+ self._task = None
123
+ super().__init__(*args, **kwargs)
124
+
125
+ async def _timer_task(self, interval):
126
+ while True:
127
+ try:
128
+ await asyncio.sleep(interval)
129
+ self._on_timer()
130
+
131
+ if self._single:
132
+ break
133
+ except asyncio.CancelledError:
134
+ break
135
+
136
+ def _timer_start(self):
137
+ self._timer_stop()
138
+
139
+ self._task = asyncio.ensure_future(
140
+ self._timer_task(max(self.interval / 1_000., 1e-6))
141
+ )
142
+
143
+ def _timer_stop(self):
144
+ if self._task is not None:
145
+ self._task.cancel()
146
+ self._task = None
147
+
148
+ def _timer_set_interval(self):
149
+ # Only stop and restart it if the timer has already been started
150
+ if self._task is not None:
151
+ self._timer_stop()
152
+ self._timer_start()
153
+
154
+
155
+ class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg):
156
+ manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg)
157
+ _timer_cls = TimerAsyncio
158
+ # Webagg and friends having the right methods, but still
159
+ # having bugs in practice. Do not advertise that it works until
160
+ # we can debug this.
161
+ supports_blit = False
162
+
163
+ def __init__(self, *args, **kwargs):
164
+ super().__init__(*args, **kwargs)
165
+ # Set to True when the renderer contains data that is newer
166
+ # than the PNG buffer.
167
+ self._png_is_old = True
168
+ # Set to True by the `refresh` message so that the next frame
169
+ # sent to the clients will be a full frame.
170
+ self._force_full = True
171
+ # The last buffer, for diff mode.
172
+ self._last_buff = np.empty((0, 0))
173
+ # Store the current image mode so that at any point, clients can
174
+ # request the information. This should be changed by calling
175
+ # self.set_image_mode(mode) so that the notification can be given
176
+ # to the connected clients.
177
+ self._current_image_mode = 'full'
178
+ # Track mouse events to fill in the x, y position of key events.
179
+ self._last_mouse_xy = (None, None)
180
+
181
+ def show(self):
182
+ # show the figure window
183
+ from matplotlib.pyplot import show
184
+ show()
185
+
186
+ def draw(self):
187
+ self._png_is_old = True
188
+ try:
189
+ super().draw()
190
+ finally:
191
+ self.manager.refresh_all() # Swap the frames.
192
+
193
+ def blit(self, bbox=None):
194
+ self._png_is_old = True
195
+ self.manager.refresh_all()
196
+
197
+ def draw_idle(self):
198
+ self.send_event("draw")
199
+
200
+ def set_cursor(self, cursor):
201
+ # docstring inherited
202
+ cursor = _api.check_getitem({
203
+ backend_tools.Cursors.HAND: 'pointer',
204
+ backend_tools.Cursors.POINTER: 'default',
205
+ backend_tools.Cursors.SELECT_REGION: 'crosshair',
206
+ backend_tools.Cursors.MOVE: 'move',
207
+ backend_tools.Cursors.WAIT: 'wait',
208
+ backend_tools.Cursors.RESIZE_HORIZONTAL: 'ew-resize',
209
+ backend_tools.Cursors.RESIZE_VERTICAL: 'ns-resize',
210
+ }, cursor=cursor)
211
+ self.send_event('cursor', cursor=cursor)
212
+
213
+ def set_image_mode(self, mode):
214
+ """
215
+ Set the image mode for any subsequent images which will be sent
216
+ to the clients. The modes may currently be either 'full' or 'diff'.
217
+
218
+ Note: diff images may not contain transparency, therefore upon
219
+ draw this mode may be changed if the resulting image has any
220
+ transparent component.
221
+ """
222
+ _api.check_in_list(['full', 'diff'], mode=mode)
223
+ if self._current_image_mode != mode:
224
+ self._current_image_mode = mode
225
+ self.handle_send_image_mode(None)
226
+
227
+ def get_diff_image(self):
228
+ if self._png_is_old:
229
+ renderer = self.get_renderer()
230
+
231
+ pixels = np.asarray(renderer.buffer_rgba())
232
+ # The buffer is created as type uint32 so that entire
233
+ # pixels can be compared in one numpy call, rather than
234
+ # needing to compare each plane separately.
235
+ buff = pixels.view(np.uint32).squeeze(2)
236
+
237
+ if (self._force_full
238
+ # If the buffer has changed size we need to do a full draw.
239
+ or buff.shape != self._last_buff.shape
240
+ # If any pixels have transparency, we need to force a full
241
+ # draw as we cannot overlay new on top of old.
242
+ or (pixels[:, :, 3] != 255).any()):
243
+ self.set_image_mode('full')
244
+ output = buff
245
+ else:
246
+ self.set_image_mode('diff')
247
+ diff = buff != self._last_buff
248
+ output = np.where(diff, buff, 0)
249
+
250
+ # Store the current buffer so we can compute the next diff.
251
+ self._last_buff = buff.copy()
252
+ self._force_full = False
253
+ self._png_is_old = False
254
+
255
+ data = output.view(dtype=np.uint8).reshape((*output.shape, 4))
256
+ with BytesIO() as png:
257
+ Image.fromarray(data).save(png, format="png")
258
+ return png.getvalue()
259
+
260
+ def handle_event(self, event):
261
+ e_type = event['type']
262
+ handler = getattr(self, f'handle_{e_type}',
263
+ self.handle_unknown_event)
264
+ return handler(event)
265
+
266
+ def handle_unknown_event(self, event):
267
+ _log.warning('Unhandled message type %s. %s', event["type"], event)
268
+
269
+ def handle_ack(self, event):
270
+ # Network latency tends to decrease if traffic is flowing
271
+ # in both directions. Therefore, the browser sends back
272
+ # an "ack" message after each image frame is received.
273
+ # This could also be used as a simple sanity check in the
274
+ # future, but for now the performance increase is enough
275
+ # to justify it, even if the server does nothing with it.
276
+ pass
277
+
278
+ def handle_draw(self, event):
279
+ self.draw()
280
+
281
+ def _handle_mouse(self, event):
282
+ x = event['x']
283
+ y = event['y']
284
+ y = self.get_renderer().height - y
285
+ self._last_mouse_xy = x, y
286
+ # JavaScript button numbers and Matplotlib button numbers are off by 1.
287
+ button = event['button'] + 1
288
+
289
+ e_type = event['type']
290
+ modifiers = event['modifiers']
291
+ guiEvent = event.get('guiEvent')
292
+ if e_type in ['button_press', 'button_release']:
293
+ MouseEvent(e_type + '_event', self, x, y, button,
294
+ modifiers=modifiers, guiEvent=guiEvent)._process()
295
+ elif e_type == 'dblclick':
296
+ MouseEvent('button_press_event', self, x, y, button, dblclick=True,
297
+ modifiers=modifiers, guiEvent=guiEvent)._process()
298
+ elif e_type == 'scroll':
299
+ MouseEvent('scroll_event', self, x, y, step=event['step'],
300
+ modifiers=modifiers, guiEvent=guiEvent)._process()
301
+ elif e_type == 'motion_notify':
302
+ MouseEvent(e_type + '_event', self, x, y,
303
+ modifiers=modifiers, guiEvent=guiEvent)._process()
304
+ elif e_type in ['figure_enter', 'figure_leave']:
305
+ LocationEvent(e_type + '_event', self, x, y,
306
+ modifiers=modifiers, guiEvent=guiEvent)._process()
307
+ handle_button_press = handle_button_release = handle_dblclick = \
308
+ handle_figure_enter = handle_figure_leave = handle_motion_notify = \
309
+ handle_scroll = _handle_mouse
310
+
311
+ def _handle_key(self, event):
312
+ KeyEvent(event['type'] + '_event', self,
313
+ _handle_key(event['key']), *self._last_mouse_xy,
314
+ guiEvent=event.get('guiEvent'))._process()
315
+ handle_key_press = handle_key_release = _handle_key
316
+
317
+ def handle_toolbar_button(self, event):
318
+ # TODO: Be more suspicious of the input
319
+ getattr(self.toolbar, event['name'])()
320
+
321
+ def handle_refresh(self, event):
322
+ figure_label = self.figure.get_label()
323
+ if not figure_label:
324
+ figure_label = f"Figure {self.manager.num}"
325
+ self.send_event('figure_label', label=figure_label)
326
+ self._force_full = True
327
+ if self.toolbar:
328
+ # Normal toolbar init would refresh this, but it happens before the
329
+ # browser canvas is set up.
330
+ self.toolbar.set_history_buttons()
331
+ self.draw_idle()
332
+
333
+ def handle_resize(self, event):
334
+ x = int(event.get('width', 800)) * self.device_pixel_ratio
335
+ y = int(event.get('height', 800)) * self.device_pixel_ratio
336
+ fig = self.figure
337
+ # An attempt at approximating the figure size in pixels.
338
+ fig.set_size_inches(x / fig.dpi, y / fig.dpi, forward=False)
339
+ # Acknowledge the resize, and force the viewer to update the
340
+ # canvas size to the figure's new size (which is hopefully
341
+ # identical or within a pixel or so).
342
+ self._png_is_old = True
343
+ self.manager.resize(*fig.bbox.size, forward=False)
344
+ ResizeEvent('resize_event', self)._process()
345
+ self.draw_idle()
346
+
347
+ def handle_send_image_mode(self, event):
348
+ # The client requests notification of what the current image mode is.
349
+ self.send_event('image_mode', mode=self._current_image_mode)
350
+
351
+ def handle_set_device_pixel_ratio(self, event):
352
+ self._handle_set_device_pixel_ratio(event.get('device_pixel_ratio', 1))
353
+
354
+ def handle_set_dpi_ratio(self, event):
355
+ # This handler is for backwards-compatibility with older ipympl.
356
+ self._handle_set_device_pixel_ratio(event.get('dpi_ratio', 1))
357
+
358
+ def _handle_set_device_pixel_ratio(self, device_pixel_ratio):
359
+ if self._set_device_pixel_ratio(device_pixel_ratio):
360
+ self._force_full = True
361
+ self.draw_idle()
362
+
363
+ def send_event(self, event_type, **kwargs):
364
+ if self.manager:
365
+ self.manager._send_event(event_type, **kwargs)
366
+
367
+
368
+ _ALLOWED_TOOL_ITEMS = {
369
+ 'home',
370
+ 'back',
371
+ 'forward',
372
+ 'pan',
373
+ 'zoom',
374
+ 'download',
375
+ None,
376
+ }
377
+
378
+
379
+ class NavigationToolbar2WebAgg(backend_bases.NavigationToolbar2):
380
+
381
+ # Use the standard toolbar items + download button
382
+ toolitems = [
383
+ (text, tooltip_text, image_file, name_of_method)
384
+ for text, tooltip_text, image_file, name_of_method
385
+ in (*backend_bases.NavigationToolbar2.toolitems,
386
+ ('Download', 'Download plot', 'filesave', 'download'))
387
+ if name_of_method in _ALLOWED_TOOL_ITEMS
388
+ ]
389
+
390
+ def __init__(self, canvas):
391
+ self.message = ''
392
+ super().__init__(canvas)
393
+
394
+ def set_message(self, message):
395
+ if message != self.message:
396
+ self.canvas.send_event("message", message=message)
397
+ self.message = message
398
+
399
+ def draw_rubberband(self, event, x0, y0, x1, y1):
400
+ self.canvas.send_event("rubberband", x0=x0, y0=y0, x1=x1, y1=y1)
401
+
402
+ def remove_rubberband(self):
403
+ self.canvas.send_event("rubberband", x0=-1, y0=-1, x1=-1, y1=-1)
404
+
405
+ def save_figure(self, *args):
406
+ """Save the current figure"""
407
+ self.canvas.send_event('save')
408
+
409
+ def pan(self):
410
+ super().pan()
411
+ self.canvas.send_event('navigate_mode', mode=self.mode.name)
412
+
413
+ def zoom(self):
414
+ super().zoom()
415
+ self.canvas.send_event('navigate_mode', mode=self.mode.name)
416
+
417
+ def set_history_buttons(self):
418
+ can_backward = self._nav_stack._pos > 0
419
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
420
+ self.canvas.send_event('history_buttons',
421
+ Back=can_backward, Forward=can_forward)
422
+
423
+
424
+ class FigureManagerWebAgg(backend_bases.FigureManagerBase):
425
+ # This must be None to not break ipympl
426
+ _toolbar2_class = None
427
+ ToolbarCls = NavigationToolbar2WebAgg
428
+ _window_title = "Matplotlib"
429
+
430
+ def __init__(self, canvas, num):
431
+ self.web_sockets = set()
432
+ super().__init__(canvas, num)
433
+
434
+ def show(self):
435
+ pass
436
+
437
+ def resize(self, w, h, forward=True):
438
+ self._send_event(
439
+ 'resize',
440
+ size=(w / self.canvas.device_pixel_ratio,
441
+ h / self.canvas.device_pixel_ratio),
442
+ forward=forward)
443
+
444
+ def set_window_title(self, title):
445
+ self._send_event('figure_label', label=title)
446
+ self._window_title = title
447
+
448
+ def get_window_title(self):
449
+ return self._window_title
450
+
451
+ # The following methods are specific to FigureManagerWebAgg
452
+
453
+ def add_web_socket(self, web_socket):
454
+ assert hasattr(web_socket, 'send_binary')
455
+ assert hasattr(web_socket, 'send_json')
456
+ self.web_sockets.add(web_socket)
457
+ self.resize(*self.canvas.figure.bbox.size)
458
+ self._send_event('refresh')
459
+
460
+ def remove_web_socket(self, web_socket):
461
+ self.web_sockets.remove(web_socket)
462
+
463
+ def handle_json(self, content):
464
+ self.canvas.handle_event(content)
465
+
466
+ def refresh_all(self):
467
+ if self.web_sockets:
468
+ diff = self.canvas.get_diff_image()
469
+ if diff is not None:
470
+ for s in self.web_sockets:
471
+ s.send_binary(diff)
472
+
473
+ @classmethod
474
+ def get_javascript(cls, stream=None):
475
+ if stream is None:
476
+ output = StringIO()
477
+ else:
478
+ output = stream
479
+
480
+ output.write((Path(__file__).parent / "web_backend/js/mpl.js")
481
+ .read_text(encoding="utf-8"))
482
+
483
+ toolitems = []
484
+ for name, tooltip, image, method in cls.ToolbarCls.toolitems:
485
+ if name is None:
486
+ toolitems.append(['', '', '', ''])
487
+ else:
488
+ toolitems.append([name, tooltip, image, method])
489
+ output.write(f"mpl.toolbar_items = {json.dumps(toolitems)};\n\n")
490
+
491
+ extensions = []
492
+ for filetype, ext in sorted(FigureCanvasWebAggCore.
493
+ get_supported_filetypes_grouped().
494
+ items()):
495
+ extensions.append(ext[0])
496
+ output.write(f"mpl.extensions = {json.dumps(extensions)};\n\n")
497
+
498
+ output.write("mpl.default_extension = {};".format(
499
+ json.dumps(FigureCanvasWebAggCore.get_default_filetype())))
500
+
501
+ if stream is None:
502
+ return output.getvalue()
503
+
504
+ @classmethod
505
+ def get_static_file_path(cls):
506
+ return os.path.join(os.path.dirname(__file__), 'web_backend')
507
+
508
+ def _send_event(self, event_type, **kwargs):
509
+ payload = {'type': event_type, **kwargs}
510
+ for s in self.web_sockets:
511
+ s.send_json(payload)
512
+
513
+
514
+ @_Backend.export
515
+ class _BackendWebAggCoreAgg(_Backend):
516
+ FigureCanvas = FigureCanvasWebAggCore
517
+ FigureManager = FigureManagerWebAgg
parrot/lib/python3.10/site-packages/matplotlib/backends/backend_wxagg.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wx
2
+
3
+ from .backend_agg import FigureCanvasAgg
4
+ from .backend_wx import _BackendWx, _FigureCanvasWxBase
5
+ from .backend_wx import ( # noqa: F401 # pylint: disable=W0611
6
+ NavigationToolbar2Wx as NavigationToolbar2WxAgg)
7
+
8
+
9
+ class FigureCanvasWxAgg(FigureCanvasAgg, _FigureCanvasWxBase):
10
+ def draw(self, drawDC=None):
11
+ """
12
+ Render the figure using agg.
13
+ """
14
+ FigureCanvasAgg.draw(self)
15
+ self.bitmap = self._create_bitmap()
16
+ self._isDrawn = True
17
+ self.gui_repaint(drawDC=drawDC)
18
+
19
+ def blit(self, bbox=None):
20
+ # docstring inherited
21
+ bitmap = self._create_bitmap()
22
+ if bbox is None:
23
+ self.bitmap = bitmap
24
+ else:
25
+ srcDC = wx.MemoryDC(bitmap)
26
+ destDC = wx.MemoryDC(self.bitmap)
27
+ x = int(bbox.x0)
28
+ y = int(self.bitmap.GetHeight() - bbox.y1)
29
+ destDC.Blit(x, y, int(bbox.width), int(bbox.height), srcDC, x, y)
30
+ destDC.SelectObject(wx.NullBitmap)
31
+ srcDC.SelectObject(wx.NullBitmap)
32
+ self.gui_repaint()
33
+
34
+ def _create_bitmap(self):
35
+ """Create a wx.Bitmap from the renderer RGBA buffer"""
36
+ rgba = self.get_renderer().buffer_rgba()
37
+ h, w, _ = rgba.shape
38
+ bitmap = wx.Bitmap.FromBufferRGBA(w, h, rgba)
39
+ bitmap.SetScaleFactor(self.GetDPIScaleFactor())
40
+ return bitmap
41
+
42
+
43
+ @_BackendWx.export
44
+ class _BackendWxAgg(_BackendWx):
45
+ FigureCanvas = FigureCanvasWxAgg
parrot/lib/python3.10/site-packages/matplotlib/backends/registry.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ import importlib
3
+
4
+
5
+ class BackendFilter(Enum):
6
+ """
7
+ Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin`
8
+
9
+ .. versionadded:: 3.9
10
+ """
11
+ INTERACTIVE = 0
12
+ NON_INTERACTIVE = 1
13
+
14
+
15
+ class BackendRegistry:
16
+ """
17
+ Registry of backends available within Matplotlib.
18
+
19
+ This is the single source of truth for available backends.
20
+
21
+ All use of ``BackendRegistry`` should be via the singleton instance
22
+ ``backend_registry`` which can be imported from ``matplotlib.backends``.
23
+
24
+ Each backend has a name, a module name containing the backend code, and an
25
+ optional GUI framework that must be running if the backend is interactive.
26
+ There are three sources of backends: built-in (source code is within the
27
+ Matplotlib repository), explicit ``module://some.backend`` syntax (backend is
28
+ obtained by loading the module), or via an entry point (self-registering
29
+ backend in an external package).
30
+
31
+ .. versionadded:: 3.9
32
+ """
33
+ # Mapping of built-in backend name to GUI framework, or "headless" for no
34
+ # GUI framework. Built-in backends are those which are included in the
35
+ # Matplotlib repo. A backend with name 'name' is located in the module
36
+ # f"matplotlib.backends.backend_{name.lower()}"
37
+ _BUILTIN_BACKEND_TO_GUI_FRAMEWORK = {
38
+ "gtk3agg": "gtk3",
39
+ "gtk3cairo": "gtk3",
40
+ "gtk4agg": "gtk4",
41
+ "gtk4cairo": "gtk4",
42
+ "macosx": "macosx",
43
+ "nbagg": "nbagg",
44
+ "notebook": "nbagg",
45
+ "qtagg": "qt",
46
+ "qtcairo": "qt",
47
+ "qt5agg": "qt5",
48
+ "qt5cairo": "qt5",
49
+ "tkagg": "tk",
50
+ "tkcairo": "tk",
51
+ "webagg": "webagg",
52
+ "wx": "wx",
53
+ "wxagg": "wx",
54
+ "wxcairo": "wx",
55
+ "agg": "headless",
56
+ "cairo": "headless",
57
+ "pdf": "headless",
58
+ "pgf": "headless",
59
+ "ps": "headless",
60
+ "svg": "headless",
61
+ "template": "headless",
62
+ }
63
+
64
+ # Reverse mapping of gui framework to preferred built-in backend.
65
+ _GUI_FRAMEWORK_TO_BACKEND = {
66
+ "gtk3": "gtk3agg",
67
+ "gtk4": "gtk4agg",
68
+ "headless": "agg",
69
+ "macosx": "macosx",
70
+ "qt": "qtagg",
71
+ "qt5": "qt5agg",
72
+ "qt6": "qtagg",
73
+ "tk": "tkagg",
74
+ "wx": "wxagg",
75
+ }
76
+
77
+ def __init__(self):
78
+ # Only load entry points when first needed.
79
+ self._loaded_entry_points = False
80
+
81
+ # Mapping of non-built-in backend to GUI framework, added dynamically from
82
+ # entry points and from matplotlib.use("module://some.backend") format.
83
+ # New entries have an "unknown" GUI framework that is determined when first
84
+ # needed by calling _get_gui_framework_by_loading.
85
+ self._backend_to_gui_framework = {}
86
+
87
+ # Mapping of backend name to module name, where different from
88
+ # f"matplotlib.backends.backend_{backend_name.lower()}". These are either
89
+ # hardcoded for backward compatibility, or loaded from entry points or
90
+ # "module://some.backend" syntax.
91
+ self._name_to_module = {
92
+ "notebook": "nbagg",
93
+ }
94
+
95
+ def _backend_module_name(self, backend):
96
+ if backend.startswith("module://"):
97
+ return backend[9:]
98
+
99
+ # Return name of module containing the specified backend.
100
+ # Does not check if the backend is valid, use is_valid_backend for that.
101
+ backend = backend.lower()
102
+
103
+ # Check if have specific name to module mapping.
104
+ backend = self._name_to_module.get(backend, backend)
105
+
106
+ return (backend[9:] if backend.startswith("module://")
107
+ else f"matplotlib.backends.backend_{backend}")
108
+
109
+ def _clear(self):
110
+ # Clear all dynamically-added data, used for testing only.
111
+ self.__init__()
112
+
113
+ def _ensure_entry_points_loaded(self):
114
+ # Load entry points, if they have not already been loaded.
115
+ if not self._loaded_entry_points:
116
+ entries = self._read_entry_points()
117
+ self._validate_and_store_entry_points(entries)
118
+ self._loaded_entry_points = True
119
+
120
+ def _get_gui_framework_by_loading(self, backend):
121
+ # Determine GUI framework for a backend by loading its module and reading the
122
+ # FigureCanvas.required_interactive_framework attribute.
123
+ # Returns "headless" if there is no GUI framework.
124
+ module = self.load_backend_module(backend)
125
+ canvas_class = module.FigureCanvas
126
+ return canvas_class.required_interactive_framework or "headless"
127
+
128
+ def _read_entry_points(self):
129
+ # Read entry points of modules that self-advertise as Matplotlib backends.
130
+ # Expects entry points like this one from matplotlib-inline (in pyproject.toml
131
+ # format):
132
+ # [project.entry-points."matplotlib.backend"]
133
+ # inline = "matplotlib_inline.backend_inline"
134
+ import importlib.metadata as im
135
+ import sys
136
+
137
+ # entry_points group keyword not available before Python 3.10
138
+ group = "matplotlib.backend"
139
+ if sys.version_info >= (3, 10):
140
+ entry_points = im.entry_points(group=group)
141
+ else:
142
+ entry_points = im.entry_points().get(group, ())
143
+ entries = [(entry.name, entry.value) for entry in entry_points]
144
+
145
+ # For backward compatibility, if matplotlib-inline and/or ipympl are installed
146
+ # but too old to include entry points, create them. Do not import ipympl
147
+ # directly as this calls matplotlib.use() whilst in this function.
148
+ def backward_compatible_entry_points(
149
+ entries, module_name, threshold_version, names, target):
150
+ from matplotlib import _parse_to_version_info
151
+ try:
152
+ module_version = im.version(module_name)
153
+ if _parse_to_version_info(module_version) < threshold_version:
154
+ for name in names:
155
+ entries.append((name, target))
156
+ except im.PackageNotFoundError:
157
+ pass
158
+
159
+ names = [entry[0] for entry in entries]
160
+ if "inline" not in names:
161
+ backward_compatible_entry_points(
162
+ entries, "matplotlib_inline", (0, 1, 7), ["inline"],
163
+ "matplotlib_inline.backend_inline")
164
+ if "ipympl" not in names:
165
+ backward_compatible_entry_points(
166
+ entries, "ipympl", (0, 9, 4), ["ipympl", "widget"],
167
+ "ipympl.backend_nbagg")
168
+
169
+ return entries
170
+
171
+ def _validate_and_store_entry_points(self, entries):
172
+ # Validate and store entry points so that they can be used via matplotlib.use()
173
+ # in the normal manner. Entry point names cannot be of module:// format, cannot
174
+ # shadow a built-in backend name, and there cannot be multiple entry points
175
+ # with the same name but different modules. Multiple entry points with the same
176
+ # name and value are permitted (it can sometimes happen outside of our control,
177
+ # see https://github.com/matplotlib/matplotlib/issues/28367).
178
+ for name, module in set(entries):
179
+ name = name.lower()
180
+ if name.startswith("module://"):
181
+ raise RuntimeError(
182
+ f"Entry point name '{name}' cannot start with 'module://'")
183
+ if name in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK:
184
+ raise RuntimeError(f"Entry point name '{name}' is a built-in backend")
185
+ if name in self._backend_to_gui_framework:
186
+ raise RuntimeError(f"Entry point name '{name}' duplicated")
187
+
188
+ self._name_to_module[name] = "module://" + module
189
+ # Do not yet know backend GUI framework, determine it only when necessary.
190
+ self._backend_to_gui_framework[name] = "unknown"
191
+
192
+ def backend_for_gui_framework(self, framework):
193
+ """
194
+ Return the name of the backend corresponding to the specified GUI framework.
195
+
196
+ Parameters
197
+ ----------
198
+ framework : str
199
+ GUI framework such as "qt".
200
+
201
+ Returns
202
+ -------
203
+ str or None
204
+ Backend name or None if GUI framework not recognised.
205
+ """
206
+ return self._GUI_FRAMEWORK_TO_BACKEND.get(framework.lower())
207
+
208
+ def is_valid_backend(self, backend):
209
+ """
210
+ Return True if the backend name is valid, False otherwise.
211
+
212
+ A backend name is valid if it is one of the built-in backends or has been
213
+ dynamically added via an entry point. Those beginning with ``module://`` are
214
+ always considered valid and are added to the current list of all backends
215
+ within this function.
216
+
217
+ Even if a name is valid, it may not be importable or usable. This can only be
218
+ determined by loading and using the backend module.
219
+
220
+ Parameters
221
+ ----------
222
+ backend : str
223
+ Name of backend.
224
+
225
+ Returns
226
+ -------
227
+ bool
228
+ True if backend is valid, False otherwise.
229
+ """
230
+ if not backend.startswith("module://"):
231
+ backend = backend.lower()
232
+
233
+ # For backward compatibility, convert ipympl and matplotlib-inline long
234
+ # module:// names to their shortened forms.
235
+ backwards_compat = {
236
+ "module://ipympl.backend_nbagg": "widget",
237
+ "module://matplotlib_inline.backend_inline": "inline",
238
+ }
239
+ backend = backwards_compat.get(backend, backend)
240
+
241
+ if (backend in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK or
242
+ backend in self._backend_to_gui_framework):
243
+ return True
244
+
245
+ if backend.startswith("module://"):
246
+ self._backend_to_gui_framework[backend] = "unknown"
247
+ return True
248
+
249
+ # Only load entry points if really need to and not already done so.
250
+ self._ensure_entry_points_loaded()
251
+ if backend in self._backend_to_gui_framework:
252
+ return True
253
+
254
+ return False
255
+
256
+ def list_all(self):
257
+ """
258
+ Return list of all known backends.
259
+
260
+ These include built-in backends and those obtained at runtime either from entry
261
+ points or explicit ``module://some.backend`` syntax.
262
+
263
+ Entry points will be loaded if they haven't been already.
264
+
265
+ Returns
266
+ -------
267
+ list of str
268
+ Backend names.
269
+ """
270
+ self._ensure_entry_points_loaded()
271
+ return [*self.list_builtin(), *self._backend_to_gui_framework]
272
+
273
+ def list_builtin(self, filter_=None):
274
+ """
275
+ Return list of backends that are built into Matplotlib.
276
+
277
+ Parameters
278
+ ----------
279
+ filter_ : `~.BackendFilter`, optional
280
+ Filter to apply to returned backends. For example, to return only
281
+ non-interactive backends use `.BackendFilter.NON_INTERACTIVE`.
282
+
283
+ Returns
284
+ -------
285
+ list of str
286
+ Backend names.
287
+ """
288
+ if filter_ == BackendFilter.INTERACTIVE:
289
+ return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items()
290
+ if v != "headless"]
291
+ elif filter_ == BackendFilter.NON_INTERACTIVE:
292
+ return [k for k, v in self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.items()
293
+ if v == "headless"]
294
+
295
+ return [*self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK]
296
+
297
+ def list_gui_frameworks(self):
298
+ """
299
+ Return list of GUI frameworks used by Matplotlib backends.
300
+
301
+ Returns
302
+ -------
303
+ list of str
304
+ GUI framework names.
305
+ """
306
+ return [k for k in self._GUI_FRAMEWORK_TO_BACKEND if k != "headless"]
307
+
308
+ def load_backend_module(self, backend):
309
+ """
310
+ Load and return the module containing the specified backend.
311
+
312
+ Parameters
313
+ ----------
314
+ backend : str
315
+ Name of backend to load.
316
+
317
+ Returns
318
+ -------
319
+ Module
320
+ Module containing backend.
321
+ """
322
+ module_name = self._backend_module_name(backend)
323
+ return importlib.import_module(module_name)
324
+
325
+ def resolve_backend(self, backend):
326
+ """
327
+ Return the backend and GUI framework for the specified backend name.
328
+
329
+ If the GUI framework is not yet known then it will be determined by loading the
330
+ backend module and checking the ``FigureCanvas.required_interactive_framework``
331
+ attribute.
332
+
333
+ This function only loads entry points if they have not already been loaded and
334
+ the backend is not built-in and not of ``module://some.backend`` format.
335
+
336
+ Parameters
337
+ ----------
338
+ backend : str or None
339
+ Name of backend, or None to use the default backend.
340
+
341
+ Returns
342
+ -------
343
+ backend : str
344
+ The backend name.
345
+ framework : str or None
346
+ The GUI framework, which will be None for a backend that is non-interactive.
347
+ """
348
+ if isinstance(backend, str):
349
+ if not backend.startswith("module://"):
350
+ backend = backend.lower()
351
+ else: # Might be _auto_backend_sentinel or None
352
+ # Use whatever is already running...
353
+ from matplotlib import get_backend
354
+ backend = get_backend()
355
+
356
+ # Is backend already known (built-in or dynamically loaded)?
357
+ gui = (self._BUILTIN_BACKEND_TO_GUI_FRAMEWORK.get(backend) or
358
+ self._backend_to_gui_framework.get(backend))
359
+
360
+ # Is backend "module://something"?
361
+ if gui is None and isinstance(backend, str) and backend.startswith("module://"):
362
+ gui = "unknown"
363
+
364
+ # Is backend a possible entry point?
365
+ if gui is None and not self._loaded_entry_points:
366
+ self._ensure_entry_points_loaded()
367
+ gui = self._backend_to_gui_framework.get(backend)
368
+
369
+ # Backend known but not its gui framework.
370
+ if gui == "unknown":
371
+ gui = self._get_gui_framework_by_loading(backend)
372
+ self._backend_to_gui_framework[backend] = gui
373
+
374
+ if gui is None:
375
+ raise RuntimeError(f"'{backend}' is not a recognised backend name")
376
+
377
+ return backend, gui if gui != "headless" else None
378
+
379
+ def resolve_gui_or_backend(self, gui_or_backend):
380
+ """
381
+ Return the backend and GUI framework for the specified string that may be
382
+ either a GUI framework or a backend name, tested in that order.
383
+
384
+ This is for use with the IPython %matplotlib magic command which may be a GUI
385
+ framework such as ``%matplotlib qt`` or a backend name such as
386
+ ``%matplotlib qtagg``.
387
+
388
+ This function only loads entry points if they have not already been loaded and
389
+ the backend is not built-in and not of ``module://some.backend`` format.
390
+
391
+ Parameters
392
+ ----------
393
+ gui_or_backend : str or None
394
+ Name of GUI framework or backend, or None to use the default backend.
395
+
396
+ Returns
397
+ -------
398
+ backend : str
399
+ The backend name.
400
+ framework : str or None
401
+ The GUI framework, which will be None for a backend that is non-interactive.
402
+ """
403
+ if not gui_or_backend.startswith("module://"):
404
+ gui_or_backend = gui_or_backend.lower()
405
+
406
+ # First check if it is a gui loop name.
407
+ backend = self.backend_for_gui_framework(gui_or_backend)
408
+ if backend is not None:
409
+ return backend, gui_or_backend if gui_or_backend != "headless" else None
410
+
411
+ # Then check if it is a backend name.
412
+ try:
413
+ return self.resolve_backend(gui_or_backend)
414
+ except Exception: # KeyError ?
415
+ raise RuntimeError(
416
+ f"'{gui_or_backend} is not a recognised GUI loop or backend name")
417
+
418
+
419
+ # Singleton
420
+ backend_registry = BackendRegistry()
parrot/lib/python3.10/site-packages/matplotlib/pyplot.py ADDED
The diff for this file is too large to render. See raw diff
 
parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.03 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/_markers.cpython-310.pyc ADDED
Binary file (1.43 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/compare.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/testing/__pycache__/decorators.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/Epoch.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Epoch module."""
2
+
3
+ import functools
4
+ import operator
5
+ import math
6
+ import datetime as DT
7
+
8
+ from matplotlib import _api
9
+ from matplotlib.dates import date2num
10
+
11
+
12
+ class Epoch:
13
+ # Frame conversion offsets in seconds
14
+ # t(TO) = t(FROM) + allowed[ FROM ][ TO ]
15
+ allowed = {
16
+ "ET": {
17
+ "UTC": +64.1839,
18
+ },
19
+ "UTC": {
20
+ "ET": -64.1839,
21
+ },
22
+ }
23
+
24
+ def __init__(self, frame, sec=None, jd=None, daynum=None, dt=None):
25
+ """
26
+ Create a new Epoch object.
27
+
28
+ Build an epoch 1 of 2 ways:
29
+
30
+ Using seconds past a Julian date:
31
+ # Epoch('ET', sec=1e8, jd=2451545)
32
+
33
+ or using a matplotlib day number
34
+ # Epoch('ET', daynum=730119.5)
35
+
36
+ = ERROR CONDITIONS
37
+ - If the input units are not in the allowed list, an error is thrown.
38
+
39
+ = INPUT VARIABLES
40
+ - frame The frame of the epoch. Must be 'ET' or 'UTC'
41
+ - sec The number of seconds past the input JD.
42
+ - jd The Julian date of the epoch.
43
+ - daynum The matplotlib day number of the epoch.
44
+ - dt A python datetime instance.
45
+ """
46
+ if ((sec is None and jd is not None) or
47
+ (sec is not None and jd is None) or
48
+ (daynum is not None and
49
+ (sec is not None or jd is not None)) or
50
+ (daynum is None and dt is None and
51
+ (sec is None or jd is None)) or
52
+ (daynum is not None and dt is not None) or
53
+ (dt is not None and (sec is not None or jd is not None)) or
54
+ ((dt is not None) and not isinstance(dt, DT.datetime))):
55
+ raise ValueError(
56
+ "Invalid inputs. Must enter sec and jd together, "
57
+ "daynum by itself, or dt (must be a python datetime).\n"
58
+ "Sec = %s\n"
59
+ "JD = %s\n"
60
+ "dnum= %s\n"
61
+ "dt = %s" % (sec, jd, daynum, dt))
62
+
63
+ _api.check_in_list(self.allowed, frame=frame)
64
+ self._frame = frame
65
+
66
+ if dt is not None:
67
+ daynum = date2num(dt)
68
+
69
+ if daynum is not None:
70
+ # 1-JAN-0001 in JD = 1721425.5
71
+ jd = float(daynum) + 1721425.5
72
+ self._jd = math.floor(jd)
73
+ self._seconds = (jd - self._jd) * 86400.0
74
+
75
+ else:
76
+ self._seconds = float(sec)
77
+ self._jd = float(jd)
78
+
79
+ # Resolve seconds down to [ 0, 86400)
80
+ deltaDays = math.floor(self._seconds / 86400)
81
+ self._jd += deltaDays
82
+ self._seconds -= deltaDays * 86400.0
83
+
84
+ def convert(self, frame):
85
+ if self._frame == frame:
86
+ return self
87
+
88
+ offset = self.allowed[self._frame][frame]
89
+
90
+ return Epoch(frame, self._seconds + offset, self._jd)
91
+
92
+ def frame(self):
93
+ return self._frame
94
+
95
+ def julianDate(self, frame):
96
+ t = self
97
+ if frame != self._frame:
98
+ t = self.convert(frame)
99
+
100
+ return t._jd + t._seconds / 86400.0
101
+
102
+ def secondsPast(self, frame, jd):
103
+ t = self
104
+ if frame != self._frame:
105
+ t = self.convert(frame)
106
+
107
+ delta = t._jd - jd
108
+ return t._seconds + delta * 86400
109
+
110
+ def _cmp(self, op, rhs):
111
+ """Compare Epochs *self* and *rhs* using operator *op*."""
112
+ t = self
113
+ if self._frame != rhs._frame:
114
+ t = self.convert(rhs._frame)
115
+ if t._jd != rhs._jd:
116
+ return op(t._jd, rhs._jd)
117
+ return op(t._seconds, rhs._seconds)
118
+
119
+ __eq__ = functools.partialmethod(_cmp, operator.eq)
120
+ __ne__ = functools.partialmethod(_cmp, operator.ne)
121
+ __lt__ = functools.partialmethod(_cmp, operator.lt)
122
+ __le__ = functools.partialmethod(_cmp, operator.le)
123
+ __gt__ = functools.partialmethod(_cmp, operator.gt)
124
+ __ge__ = functools.partialmethod(_cmp, operator.ge)
125
+
126
+ def __add__(self, rhs):
127
+ """
128
+ Add a duration to an Epoch.
129
+
130
+ = INPUT VARIABLES
131
+ - rhs The Epoch to subtract.
132
+
133
+ = RETURN VALUE
134
+ - Returns the difference of ourselves and the input Epoch.
135
+ """
136
+ t = self
137
+ if self._frame != rhs.frame():
138
+ t = self.convert(rhs._frame)
139
+
140
+ sec = t._seconds + rhs.seconds()
141
+
142
+ return Epoch(t._frame, sec, t._jd)
143
+
144
+ def __sub__(self, rhs):
145
+ """
146
+ Subtract two Epoch's or a Duration from an Epoch.
147
+
148
+ Valid:
149
+ Duration = Epoch - Epoch
150
+ Epoch = Epoch - Duration
151
+
152
+ = INPUT VARIABLES
153
+ - rhs The Epoch to subtract.
154
+
155
+ = RETURN VALUE
156
+ - Returns either the duration between to Epoch's or the a new
157
+ Epoch that is the result of subtracting a duration from an epoch.
158
+ """
159
+ # Delay-load due to circular dependencies.
160
+ import matplotlib.testing.jpl_units as U
161
+
162
+ # Handle Epoch - Duration
163
+ if isinstance(rhs, U.Duration):
164
+ return self + -rhs
165
+
166
+ t = self
167
+ if self._frame != rhs._frame:
168
+ t = self.convert(rhs._frame)
169
+
170
+ days = t._jd - rhs._jd
171
+ sec = t._seconds - rhs._seconds
172
+
173
+ return U.Duration(rhs._frame, days*86400 + sec)
174
+
175
+ def __str__(self):
176
+ """Print the Epoch."""
177
+ return f"{self.julianDate(self._frame):22.15e} {self._frame}"
178
+
179
+ def __repr__(self):
180
+ """Print the Epoch."""
181
+ return str(self)
182
+
183
+ @staticmethod
184
+ def range(start, stop, step):
185
+ """
186
+ Generate a range of Epoch objects.
187
+
188
+ Similar to the Python range() method. Returns the range [
189
+ start, stop) at the requested step. Each element will be a
190
+ Epoch object.
191
+
192
+ = INPUT VARIABLES
193
+ - start The starting value of the range.
194
+ - stop The stop value of the range.
195
+ - step Step to use.
196
+
197
+ = RETURN VALUE
198
+ - Returns a list containing the requested Epoch values.
199
+ """
200
+ elems = []
201
+
202
+ i = 0
203
+ while True:
204
+ d = start + i * step
205
+ if d >= stop:
206
+ break
207
+
208
+ elems.append(d)
209
+ i += 1
210
+
211
+ return elems
parrot/lib/python3.10/site-packages/matplotlib/testing/jpl_units/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.66 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f41871d4f27ecbddbff09e268203fb6938c59c2b7d36ff313d05b42530f39a77
3
+ size 617056
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size);
21
+ TORCH_API at::Tensor _adaptive_avg_pool2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & _efficientzerotensor_out(at::Tensor & out, at::IntArrayRef size);
21
+ TORCH_API at::Tensor & _efficientzerotensor_outf(at::IntArrayRef size, at::Tensor & out);
22
+ TORCH_API at::Tensor & _efficientzerotensor_symint_out(at::Tensor & out, c10::SymIntArrayRef size);
23
+ TORCH_API at::Tensor & _efficientzerotensor_symint_outf(c10::SymIntArrayRef size, at::Tensor & out);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_div_Scalar {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList, const at::Scalar &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self, const at::Scalar & scalar);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
26
+ };
27
+
28
+ struct TORCH_API _foreach_div__Scalar {
29
+ using schema = void (at::TensorList, const at::Scalar &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()")
35
+ static void call(at::TensorList self, const at::Scalar & scalar);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
37
+ };
38
+
39
+ struct TORCH_API _foreach_div_List {
40
+ using schema = ::std::vector<at::Tensor> (at::TensorList, at::TensorList);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]")
46
+ static ::std::vector<at::Tensor> call(at::TensorList self, at::TensorList other);
47
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
48
+ };
49
+
50
+ struct TORCH_API _foreach_div__List {
51
+ using schema = void (at::TensorList, at::TensorList);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> ()")
57
+ static void call(at::TensorList self, at::TensorList other);
58
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
59
+ };
60
+
61
+ struct TORCH_API _foreach_div_ScalarList {
62
+ using schema = ::std::vector<at::Tensor> (at::TensorList, at::ArrayRef<at::Scalar>);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]")
68
+ static ::std::vector<at::Tensor> call(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
69
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars);
70
+ };
71
+
72
+ struct TORCH_API _foreach_div__ScalarList {
73
+ using schema = void (at::TensorList, at::ArrayRef<at::Scalar>);
74
+ using ptr_schema = schema*;
75
+ // See Note [static constexpr char* members for windows NVCC]
76
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
77
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList")
78
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()")
79
+ static void call(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
80
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars);
81
+ };
82
+
83
+ struct TORCH_API _foreach_div_Tensor {
84
+ using schema = ::std::vector<at::Tensor> (at::TensorList, const at::Tensor &);
85
+ using ptr_schema = schema*;
86
+ // See Note [static constexpr char* members for windows NVCC]
87
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
88
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
89
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[]")
90
+ static ::std::vector<at::Tensor> call(at::TensorList self, const at::Tensor & other);
91
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other);
92
+ };
93
+
94
+ struct TORCH_API _foreach_div__Tensor {
95
+ using schema = void (at::TensorList, const at::Tensor &);
96
+ using ptr_schema = schema*;
97
+ // See Note [static constexpr char* members for windows NVCC]
98
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
99
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
100
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> ()")
101
+ static void call(at::TensorList self, const at::Tensor & other);
102
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other);
103
+ };
104
+
105
+ struct TORCH_API _foreach_div_Scalar_out {
106
+ using schema = void (at::TensorList, const at::Scalar &, at::TensorList);
107
+ using ptr_schema = schema*;
108
+ // See Note [static constexpr char* members for windows NVCC]
109
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
110
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
111
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()")
112
+ static void call(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
113
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar, at::TensorList out);
114
+ };
115
+
116
+ struct TORCH_API _foreach_div_List_out {
117
+ using schema = void (at::TensorList, at::TensorList, at::TensorList);
118
+ using ptr_schema = schema*;
119
+ // See Note [static constexpr char* members for windows NVCC]
120
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
121
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List_out")
122
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()")
123
+ static void call(at::TensorList self, at::TensorList other, at::TensorList out);
124
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, at::TensorList out);
125
+ };
126
+
127
+ struct TORCH_API _foreach_div_ScalarList_out {
128
+ using schema = void (at::TensorList, at::ArrayRef<at::Scalar>, at::TensorList);
129
+ using ptr_schema = schema*;
130
+ // See Note [static constexpr char* members for windows NVCC]
131
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
132
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList_out")
133
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()")
134
+ static void call(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
135
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
136
+ };
137
+
138
+ struct TORCH_API _foreach_div_Tensor_out {
139
+ using schema = void (at::TensorList, const at::Tensor &, at::TensorList);
140
+ using ptr_schema = schema*;
141
+ // See Note [static constexpr char* members for windows NVCC]
142
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
143
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
144
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor_out(Tensor[] self, Tensor other, *, Tensor(a!)[] out) -> ()")
145
+ static void call(at::TensorList self, const at::Tensor & other, at::TensorList out);
146
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other, at::TensorList out);
147
+ };
148
+
149
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_max {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max(Tensor[] self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
26
+ };
27
+
28
+ struct TORCH_API _foreach_max_out {
29
+ using schema = void (at::TensorList, at::TensorList);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
35
+ static void call(at::TensorList self, at::TensorList out);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API bool _is_zerotensor(const at::Tensor & self);
20
+ } // namespace native
21
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _neg_view_copy_out(const at::Tensor & self, at::Tensor & out);
20
+ TORCH_API at::Tensor _neg_view_copy(const at::Tensor & self);
21
+ } // namespace native
22
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_min_seqlen_native.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ } // namespace native
20
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ } // namespace native
20
+ } // namespace at