anhtld commited on
Commit
0fe40da
·
verified ·
1 Parent(s): df92190

auto-sync 2026-07-02T13:37:00Z workspace (part 6)

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 +19 -0
  2. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_type1font.py +879 -0
  3. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_version.py +1 -0
  4. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/animation.py +1823 -0
  5. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/animation.pyi +217 -0
  6. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/artist.py +1855 -0
  7. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/artist.pyi +199 -0
  8. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/__init__.py +18 -0
  9. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/__init__.pyi +16 -0
  10. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_axes.py +0 -0
  11. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_axes.pyi +780 -0
  12. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_base.py +0 -0
  13. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_base.pyi +459 -0
  14. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.py +322 -0
  15. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.pyi +45 -0
  16. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axis.py +0 -0
  17. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axis.pyi +280 -0
  18. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_bases.py +0 -0
  19. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_bases.pyi +482 -0
  20. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_managers.py +387 -0
  21. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_managers.pyi +64 -0
  22. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_tools.py +998 -0
  23. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_tools.pyi +121 -0
  24. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/__init__.py +5 -0
  25. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so +3 -0
  26. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.pyi +0 -0
  27. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_gtk.py +331 -0
  28. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_pdf_ps.py +189 -0
  29. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_tk.py +1105 -0
  30. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_macosx.pyi +0 -0
  31. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so +3 -0
  32. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_tkagg.pyi +15 -0
  33. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py +528 -0
  34. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_cairo.py +529 -0
  35. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3.py +596 -0
  36. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3agg.py +74 -0
  37. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3cairo.py +35 -0
  38. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4.py +642 -0
  39. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4agg.py +41 -0
  40. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4cairo.py +32 -0
  41. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_macosx.py +196 -0
  42. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_mixed.py +119 -0
  43. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_nbagg.py +243 -0
  44. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_pdf.py +0 -0
  45. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py +1010 -0
  46. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_ps.py +1481 -0
  47. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_qt.py +1089 -0
  48. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_qt5.py +28 -0
  49. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_qt5agg.py +14 -0
  50. workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_qt5cairo.py +11 -0
.gitattributes CHANGED
@@ -151,3 +151,22 @@ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_image.cpyt
151
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
152
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
153
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
152
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
153
  workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
154
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
155
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
156
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/ft2font.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
157
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf filter=lfs diff=lfs merge=lfs -text
158
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
159
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
160
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
161
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf filter=lfs diff=lfs merge=lfs -text
162
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
163
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
164
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
165
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf filter=lfs diff=lfs merge=lfs -text
166
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf filter=lfs diff=lfs merge=lfs -text
167
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf filter=lfs diff=lfs merge=lfs -text
168
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf filter=lfs diff=lfs merge=lfs -text
169
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf filter=lfs diff=lfs merge=lfs -text
170
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text
171
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text
172
+ workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_type1font.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A class representing a Type 1 font.
3
+
4
+ This version reads pfa and pfb files and splits them for embedding in
5
+ pdf files. It also supports SlantFont and ExtendFont transformations,
6
+ similarly to pdfTeX and friends. There is no support yet for subsetting.
7
+
8
+ Usage::
9
+
10
+ font = Type1Font(filename)
11
+ clear_part, encrypted_part, finale = font.parts
12
+ slanted_font = font.transform({'slant': 0.167})
13
+ extended_font = font.transform({'extend': 1.2})
14
+
15
+ Sources:
16
+
17
+ * Adobe Technical Note #5040, Supporting Downloadable PostScript
18
+ Language Fonts.
19
+
20
+ * Adobe Type 1 Font Format, Adobe Systems Incorporated, third printing,
21
+ v1.1, 1993. ISBN 0-201-57044-0.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import binascii
27
+ import functools
28
+ import logging
29
+ import re
30
+ import string
31
+ import struct
32
+ import typing as T
33
+
34
+ import numpy as np
35
+
36
+ from matplotlib.cbook import _format_approx
37
+ from . import _api
38
+
39
+ _log = logging.getLogger(__name__)
40
+
41
+
42
+ class _Token:
43
+ """
44
+ A token in a PostScript stream.
45
+
46
+ Attributes
47
+ ----------
48
+ pos : int
49
+ Position, i.e. offset from the beginning of the data.
50
+ raw : str
51
+ Raw text of the token.
52
+ kind : str
53
+ Description of the token (for debugging or testing).
54
+ """
55
+ __slots__ = ('pos', 'raw')
56
+ kind = '?'
57
+
58
+ def __init__(self, pos, raw):
59
+ _log.debug('type1font._Token %s at %d: %r', self.kind, pos, raw)
60
+ self.pos = pos
61
+ self.raw = raw
62
+
63
+ def __str__(self):
64
+ return f"<{self.kind} {self.raw} @{self.pos}>"
65
+
66
+ def endpos(self):
67
+ """Position one past the end of the token"""
68
+ return self.pos + len(self.raw)
69
+
70
+ def is_keyword(self, *names):
71
+ """Is this a name token with one of the names?"""
72
+ return False
73
+
74
+ def is_slash_name(self):
75
+ """Is this a name token that starts with a slash?"""
76
+ return False
77
+
78
+ def is_delim(self):
79
+ """Is this a delimiter token?"""
80
+ return False
81
+
82
+ def is_number(self):
83
+ """Is this a number token?"""
84
+ return False
85
+
86
+ def value(self):
87
+ return self.raw
88
+
89
+
90
+ class _NameToken(_Token):
91
+ kind = 'name'
92
+
93
+ def is_slash_name(self):
94
+ return self.raw.startswith('/')
95
+
96
+ def value(self):
97
+ return self.raw[1:]
98
+
99
+
100
+ class _BooleanToken(_Token):
101
+ kind = 'boolean'
102
+
103
+ def value(self):
104
+ return self.raw == 'true'
105
+
106
+
107
+ class _KeywordToken(_Token):
108
+ kind = 'keyword'
109
+
110
+ def is_keyword(self, *names):
111
+ return self.raw in names
112
+
113
+
114
+ class _DelimiterToken(_Token):
115
+ kind = 'delimiter'
116
+
117
+ def is_delim(self):
118
+ return True
119
+
120
+ def opposite(self):
121
+ return {'[': ']', ']': '[',
122
+ '{': '}', '}': '{',
123
+ '<<': '>>', '>>': '<<'
124
+ }[self.raw]
125
+
126
+
127
+ class _WhitespaceToken(_Token):
128
+ kind = 'whitespace'
129
+
130
+
131
+ class _StringToken(_Token):
132
+ kind = 'string'
133
+ _escapes_re = re.compile(r'\\([\\()nrtbf]|[0-7]{1,3})')
134
+ _replacements = {'\\': '\\', '(': '(', ')': ')', 'n': '\n',
135
+ 'r': '\r', 't': '\t', 'b': '\b', 'f': '\f'}
136
+ _ws_re = re.compile('[\0\t\r\f\n ]')
137
+
138
+ @classmethod
139
+ def _escape(cls, match):
140
+ group = match.group(1)
141
+ try:
142
+ return cls._replacements[group]
143
+ except KeyError:
144
+ return chr(int(group, 8))
145
+
146
+ @functools.lru_cache
147
+ def value(self):
148
+ if self.raw[0] == '(':
149
+ return self._escapes_re.sub(self._escape, self.raw[1:-1])
150
+ else:
151
+ data = self._ws_re.sub('', self.raw[1:-1])
152
+ if len(data) % 2 == 1:
153
+ data += '0'
154
+ return binascii.unhexlify(data)
155
+
156
+
157
+ class _BinaryToken(_Token):
158
+ kind = 'binary'
159
+
160
+ def value(self):
161
+ return self.raw[1:]
162
+
163
+
164
+ class _NumberToken(_Token):
165
+ kind = 'number'
166
+
167
+ def is_number(self):
168
+ return True
169
+
170
+ def value(self):
171
+ if '.' not in self.raw:
172
+ return int(self.raw)
173
+ else:
174
+ return float(self.raw)
175
+
176
+
177
+ def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]:
178
+ """
179
+ A generator that produces _Token instances from Type-1 font code.
180
+
181
+ The consumer of the generator may send an integer to the tokenizer to
182
+ indicate that the next token should be _BinaryToken of the given length.
183
+
184
+ Parameters
185
+ ----------
186
+ data : bytes
187
+ The data of the font to tokenize.
188
+
189
+ skip_ws : bool
190
+ If true, the generator will drop any _WhitespaceTokens from the output.
191
+ """
192
+
193
+ text = data.decode('ascii', 'replace')
194
+ whitespace_or_comment_re = re.compile(r'[\0\t\r\f\n ]+|%[^\r\n]*')
195
+ token_re = re.compile(r'/{0,2}[^]\0\t\r\f\n ()<>{}/%[]+')
196
+ instring_re = re.compile(r'[()\\]')
197
+ hex_re = re.compile(r'^<[0-9a-fA-F\0\t\r\f\n ]*>$')
198
+ oct_re = re.compile(r'[0-7]{1,3}')
199
+ pos = 0
200
+ next_binary: int | None = None
201
+
202
+ while pos < len(text):
203
+ if next_binary is not None:
204
+ n = next_binary
205
+ next_binary = (yield _BinaryToken(pos, data[pos:pos+n]))
206
+ pos += n
207
+ continue
208
+ match = whitespace_or_comment_re.match(text, pos)
209
+ if match:
210
+ if not skip_ws:
211
+ next_binary = (yield _WhitespaceToken(pos, match.group()))
212
+ pos = match.end()
213
+ elif text[pos] == '(':
214
+ # PostScript string rules:
215
+ # - parentheses must be balanced
216
+ # - backslashes escape backslashes and parens
217
+ # - also codes \n\r\t\b\f and octal escapes are recognized
218
+ # - other backslashes do not escape anything
219
+ start = pos
220
+ pos += 1
221
+ depth = 1
222
+ while depth:
223
+ match = instring_re.search(text, pos)
224
+ if match is None:
225
+ raise ValueError(
226
+ f'Unterminated string starting at {start}')
227
+ pos = match.end()
228
+ if match.group() == '(':
229
+ depth += 1
230
+ elif match.group() == ')':
231
+ depth -= 1
232
+ else: # a backslash
233
+ char = text[pos]
234
+ if char in r'\()nrtbf':
235
+ pos += 1
236
+ else:
237
+ octal = oct_re.match(text, pos)
238
+ if octal:
239
+ pos = octal.end()
240
+ else:
241
+ pass # non-escaping backslash
242
+ next_binary = (yield _StringToken(start, text[start:pos]))
243
+ elif text[pos:pos + 2] in ('<<', '>>'):
244
+ next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2]))
245
+ pos += 2
246
+ elif text[pos] == '<':
247
+ start = pos
248
+ try:
249
+ pos = text.index('>', pos) + 1
250
+ except ValueError as e:
251
+ raise ValueError(f'Unterminated hex string starting at {start}'
252
+ ) from e
253
+ if not hex_re.match(text[start:pos]):
254
+ raise ValueError(f'Malformed hex string starting at {start}')
255
+ next_binary = (yield _StringToken(pos, text[start:pos]))
256
+ else:
257
+ match = token_re.match(text, pos)
258
+ if match:
259
+ raw = match.group()
260
+ if raw.startswith('/'):
261
+ next_binary = (yield _NameToken(pos, raw))
262
+ elif match.group() in ('true', 'false'):
263
+ next_binary = (yield _BooleanToken(pos, raw))
264
+ else:
265
+ try:
266
+ float(raw)
267
+ next_binary = (yield _NumberToken(pos, raw))
268
+ except ValueError:
269
+ next_binary = (yield _KeywordToken(pos, raw))
270
+ pos = match.end()
271
+ else:
272
+ next_binary = (yield _DelimiterToken(pos, text[pos]))
273
+ pos += 1
274
+
275
+
276
+ class _BalancedExpression(_Token):
277
+ pass
278
+
279
+
280
+ def _expression(initial, tokens, data):
281
+ """
282
+ Consume some number of tokens and return a balanced PostScript expression.
283
+
284
+ Parameters
285
+ ----------
286
+ initial : _Token
287
+ The token that triggered parsing a balanced expression.
288
+ tokens : iterator of _Token
289
+ Following tokens.
290
+ data : bytes
291
+ Underlying data that the token positions point to.
292
+
293
+ Returns
294
+ -------
295
+ _BalancedExpression
296
+ """
297
+ delim_stack = []
298
+ token = initial
299
+ while True:
300
+ if token.is_delim():
301
+ if token.raw in ('[', '{'):
302
+ delim_stack.append(token)
303
+ elif token.raw in (']', '}'):
304
+ if not delim_stack:
305
+ raise RuntimeError(f"unmatched closing token {token}")
306
+ match = delim_stack.pop()
307
+ if match.raw != token.opposite():
308
+ raise RuntimeError(
309
+ f"opening token {match} closed by {token}"
310
+ )
311
+ if not delim_stack:
312
+ break
313
+ else:
314
+ raise RuntimeError(f'unknown delimiter {token}')
315
+ elif not delim_stack:
316
+ break
317
+ token = next(tokens)
318
+ return _BalancedExpression(
319
+ initial.pos,
320
+ data[initial.pos:token.endpos()].decode('ascii', 'replace')
321
+ )
322
+
323
+
324
+ class Type1Font:
325
+ """
326
+ A class representing a Type-1 font, for use by backends.
327
+
328
+ Attributes
329
+ ----------
330
+ parts : tuple
331
+ A 3-tuple of the cleartext part, the encrypted part, and the finale of
332
+ zeros.
333
+
334
+ decrypted : bytes
335
+ The decrypted form of ``parts[1]``.
336
+
337
+ prop : dict[str, Any]
338
+ A dictionary of font properties. Noteworthy keys include:
339
+
340
+ - FontName: PostScript name of the font
341
+ - Encoding: dict from numeric codes to glyph names
342
+ - FontMatrix: bytes object encoding a matrix
343
+ - UniqueID: optional font identifier, dropped when modifying the font
344
+ - CharStrings: dict from glyph names to byte code
345
+ - Subrs: array of byte code subroutines
346
+ - OtherSubrs: bytes object encoding some PostScript code
347
+ """
348
+ __slots__ = ('parts', 'decrypted', 'prop', '_pos', '_abbr')
349
+ # the _pos dict contains (begin, end) indices to parts[0] + decrypted
350
+ # so that they can be replaced when transforming the font;
351
+ # but since sometimes a definition appears in both parts[0] and decrypted,
352
+ # _pos[name] is an array of such pairs
353
+ #
354
+ # _abbr maps three standard abbreviations to their particular names in
355
+ # this font (e.g. 'RD' is named '-|' in some fonts)
356
+
357
+ def __init__(self, input):
358
+ """
359
+ Initialize a Type-1 font.
360
+
361
+ Parameters
362
+ ----------
363
+ input : str or 3-tuple
364
+ Either a pfb file name, or a 3-tuple of already-decoded Type-1
365
+ font `~.Type1Font.parts`.
366
+ """
367
+ if isinstance(input, tuple) and len(input) == 3:
368
+ self.parts = input
369
+ else:
370
+ with open(input, 'rb') as file:
371
+ data = self._read(file)
372
+ self.parts = self._split(data)
373
+
374
+ self.decrypted = self._decrypt(self.parts[1], 'eexec')
375
+ self._abbr = {'RD': 'RD', 'ND': 'ND', 'NP': 'NP'}
376
+ self._parse()
377
+
378
+ def _read(self, file):
379
+ """Read the font from a file, decoding into usable parts."""
380
+ rawdata = file.read()
381
+ if not rawdata.startswith(b'\x80'):
382
+ return rawdata
383
+
384
+ data = b''
385
+ while rawdata:
386
+ if not rawdata.startswith(b'\x80'):
387
+ raise RuntimeError('Broken pfb file (expected byte 128, '
388
+ 'got %d)' % rawdata[0])
389
+ type = rawdata[1]
390
+ if type in (1, 2):
391
+ length, = struct.unpack('<i', rawdata[2:6])
392
+ segment = rawdata[6:6 + length]
393
+ rawdata = rawdata[6 + length:]
394
+
395
+ if type == 1: # ASCII text: include verbatim
396
+ data += segment
397
+ elif type == 2: # binary data: encode in hexadecimal
398
+ data += binascii.hexlify(segment)
399
+ elif type == 3: # end of file
400
+ break
401
+ else:
402
+ raise RuntimeError('Unknown segment type %d in pfb file' % type)
403
+
404
+ return data
405
+
406
+ def _split(self, data):
407
+ """
408
+ Split the Type 1 font into its three main parts.
409
+
410
+ The three parts are: (1) the cleartext part, which ends in a
411
+ eexec operator; (2) the encrypted part; (3) the fixed part,
412
+ which contains 512 ASCII zeros possibly divided on various
413
+ lines, a cleartomark operator, and possibly something else.
414
+ """
415
+
416
+ # Cleartext part: just find the eexec and skip whitespace
417
+ idx = data.index(b'eexec')
418
+ idx += len(b'eexec')
419
+ while data[idx] in b' \t\r\n':
420
+ idx += 1
421
+ len1 = idx
422
+
423
+ # Encrypted part: find the cleartomark operator and count
424
+ # zeros backward
425
+ idx = data.rindex(b'cleartomark') - 1
426
+ zeros = 512
427
+ while zeros and data[idx] in b'0' or data[idx] in b'\r\n':
428
+ if data[idx] in b'0':
429
+ zeros -= 1
430
+ idx -= 1
431
+ if zeros:
432
+ # this may have been a problem on old implementations that
433
+ # used the zeros as necessary padding
434
+ _log.info('Insufficiently many zeros in Type 1 font')
435
+
436
+ # Convert encrypted part to binary (if we read a pfb file, we may end
437
+ # up converting binary to hexadecimal to binary again; but if we read
438
+ # a pfa file, this part is already in hex, and I am not quite sure if
439
+ # even the pfb format guarantees that it will be in binary).
440
+ idx1 = len1 + ((idx - len1 + 2) & ~1) # ensure an even number of bytes
441
+ binary = binascii.unhexlify(data[len1:idx1])
442
+
443
+ return data[:len1], binary, data[idx+1:]
444
+
445
+ @staticmethod
446
+ def _decrypt(ciphertext, key, ndiscard=4):
447
+ """
448
+ Decrypt ciphertext using the Type-1 font algorithm.
449
+
450
+ The algorithm is described in Adobe's "Adobe Type 1 Font Format".
451
+ The key argument can be an integer, or one of the strings
452
+ 'eexec' and 'charstring', which map to the key specified for the
453
+ corresponding part of Type-1 fonts.
454
+
455
+ The ndiscard argument should be an integer, usually 4.
456
+ That number of bytes is discarded from the beginning of plaintext.
457
+ """
458
+
459
+ key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key)
460
+ plaintext = []
461
+ for byte in ciphertext:
462
+ plaintext.append(byte ^ (key >> 8))
463
+ key = ((key+byte) * 52845 + 22719) & 0xffff
464
+
465
+ return bytes(plaintext[ndiscard:])
466
+
467
+ @staticmethod
468
+ def _encrypt(plaintext, key, ndiscard=4):
469
+ """
470
+ Encrypt plaintext using the Type-1 font algorithm.
471
+
472
+ The algorithm is described in Adobe's "Adobe Type 1 Font Format".
473
+ The key argument can be an integer, or one of the strings
474
+ 'eexec' and 'charstring', which map to the key specified for the
475
+ corresponding part of Type-1 fonts.
476
+
477
+ The ndiscard argument should be an integer, usually 4. That
478
+ number of bytes is prepended to the plaintext before encryption.
479
+ This function prepends NUL bytes for reproducibility, even though
480
+ the original algorithm uses random bytes, presumably to avoid
481
+ cryptanalysis.
482
+ """
483
+
484
+ key = _api.check_getitem({'eexec': 55665, 'charstring': 4330}, key=key)
485
+ ciphertext = []
486
+ for byte in b'\0' * ndiscard + plaintext:
487
+ c = byte ^ (key >> 8)
488
+ ciphertext.append(c)
489
+ key = ((key + c) * 52845 + 22719) & 0xffff
490
+
491
+ return bytes(ciphertext)
492
+
493
+ def _parse(self):
494
+ """
495
+ Find the values of various font properties. This limited kind
496
+ of parsing is described in Chapter 10 "Adobe Type Manager
497
+ Compatibility" of the Type-1 spec.
498
+ """
499
+ # Start with reasonable defaults
500
+ prop = {'Weight': 'Regular', 'ItalicAngle': 0.0, 'isFixedPitch': False,
501
+ 'UnderlinePosition': -100, 'UnderlineThickness': 50}
502
+ pos = {}
503
+ data = self.parts[0] + self.decrypted
504
+
505
+ source = _tokenize(data, True)
506
+ while True:
507
+ # See if there is a key to be assigned a value
508
+ # e.g. /FontName in /FontName /Helvetica def
509
+ try:
510
+ token = next(source)
511
+ except StopIteration:
512
+ break
513
+ if token.is_delim():
514
+ # skip over this - we want top-level keys only
515
+ _expression(token, source, data)
516
+ if token.is_slash_name():
517
+ key = token.value()
518
+ keypos = token.pos
519
+ else:
520
+ continue
521
+
522
+ # Some values need special parsing
523
+ if key in ('Subrs', 'CharStrings', 'Encoding', 'OtherSubrs'):
524
+ prop[key], endpos = {
525
+ 'Subrs': self._parse_subrs,
526
+ 'CharStrings': self._parse_charstrings,
527
+ 'Encoding': self._parse_encoding,
528
+ 'OtherSubrs': self._parse_othersubrs
529
+ }[key](source, data)
530
+ pos.setdefault(key, []).append((keypos, endpos))
531
+ continue
532
+
533
+ try:
534
+ token = next(source)
535
+ except StopIteration:
536
+ break
537
+
538
+ if isinstance(token, _KeywordToken):
539
+ # constructs like
540
+ # FontDirectory /Helvetica known {...} {...} ifelse
541
+ # mean the key was not really a key
542
+ continue
543
+
544
+ if token.is_delim():
545
+ value = _expression(token, source, data).raw
546
+ else:
547
+ value = token.value()
548
+
549
+ # look for a 'def' possibly preceded by access modifiers
550
+ try:
551
+ kw = next(
552
+ kw for kw in source
553
+ if not kw.is_keyword('readonly', 'noaccess', 'executeonly')
554
+ )
555
+ except StopIteration:
556
+ break
557
+
558
+ # sometimes noaccess def and readonly def are abbreviated
559
+ if kw.is_keyword('def', self._abbr['ND'], self._abbr['NP']):
560
+ prop[key] = value
561
+ pos.setdefault(key, []).append((keypos, kw.endpos()))
562
+
563
+ # detect the standard abbreviations
564
+ if value == '{noaccess def}':
565
+ self._abbr['ND'] = key
566
+ elif value == '{noaccess put}':
567
+ self._abbr['NP'] = key
568
+ elif value == '{string currentfile exch readstring pop}':
569
+ self._abbr['RD'] = key
570
+
571
+ # Fill in the various *Name properties
572
+ if 'FontName' not in prop:
573
+ prop['FontName'] = (prop.get('FullName') or
574
+ prop.get('FamilyName') or
575
+ 'Unknown')
576
+ if 'FullName' not in prop:
577
+ prop['FullName'] = prop['FontName']
578
+ if 'FamilyName' not in prop:
579
+ extras = ('(?i)([ -](regular|plain|italic|oblique|(semi)?bold|'
580
+ '(ultra)?light|extra|condensed))+$')
581
+ prop['FamilyName'] = re.sub(extras, '', prop['FullName'])
582
+ # Decrypt the encrypted parts
583
+ ndiscard = prop.get('lenIV', 4)
584
+ cs = prop['CharStrings']
585
+ for key, value in cs.items():
586
+ cs[key] = self._decrypt(value, 'charstring', ndiscard)
587
+ if 'Subrs' in prop:
588
+ prop['Subrs'] = [
589
+ self._decrypt(value, 'charstring', ndiscard)
590
+ for value in prop['Subrs']
591
+ ]
592
+
593
+ self.prop = prop
594
+ self._pos = pos
595
+
596
+ def _parse_subrs(self, tokens, _data):
597
+ count_token = next(tokens)
598
+ if not count_token.is_number():
599
+ raise RuntimeError(
600
+ f"Token following /Subrs must be a number, was {count_token}"
601
+ )
602
+ count = count_token.value()
603
+ array = [None] * count
604
+ next(t for t in tokens if t.is_keyword('array'))
605
+ for _ in range(count):
606
+ next(t for t in tokens if t.is_keyword('dup'))
607
+ index_token = next(tokens)
608
+ if not index_token.is_number():
609
+ raise RuntimeError(
610
+ "Token following dup in Subrs definition must be a "
611
+ f"number, was {index_token}"
612
+ )
613
+ nbytes_token = next(tokens)
614
+ if not nbytes_token.is_number():
615
+ raise RuntimeError(
616
+ "Second token following dup in Subrs definition must "
617
+ f"be a number, was {nbytes_token}"
618
+ )
619
+ token = next(tokens)
620
+ if not token.is_keyword(self._abbr['RD']):
621
+ raise RuntimeError(
622
+ f"Token preceding subr must be {self._abbr['RD']}, "
623
+ f"was {token}"
624
+ )
625
+ binary_token = tokens.send(1+nbytes_token.value())
626
+ array[index_token.value()] = binary_token.value()
627
+
628
+ return array, next(tokens).endpos()
629
+
630
+ @staticmethod
631
+ def _parse_charstrings(tokens, _data):
632
+ count_token = next(tokens)
633
+ if not count_token.is_number():
634
+ raise RuntimeError(
635
+ "Token following /CharStrings must be a number, "
636
+ f"was {count_token}"
637
+ )
638
+ count = count_token.value()
639
+ charstrings = {}
640
+ next(t for t in tokens if t.is_keyword('begin'))
641
+ while True:
642
+ token = next(t for t in tokens
643
+ if t.is_keyword('end') or t.is_slash_name())
644
+ if token.raw == 'end':
645
+ return charstrings, token.endpos()
646
+ glyphname = token.value()
647
+ nbytes_token = next(tokens)
648
+ if not nbytes_token.is_number():
649
+ raise RuntimeError(
650
+ f"Token following /{glyphname} in CharStrings definition "
651
+ f"must be a number, was {nbytes_token}"
652
+ )
653
+ next(tokens) # usually RD or |-
654
+ binary_token = tokens.send(1+nbytes_token.value())
655
+ charstrings[glyphname] = binary_token.value()
656
+
657
+ @staticmethod
658
+ def _parse_encoding(tokens, _data):
659
+ # this only works for encodings that follow the Adobe manual
660
+ # but some old fonts include non-compliant data - we log a warning
661
+ # and return a possibly incomplete encoding
662
+ encoding = {}
663
+ while True:
664
+ token = next(t for t in tokens
665
+ if t.is_keyword('StandardEncoding', 'dup', 'def'))
666
+ if token.is_keyword('StandardEncoding'):
667
+ return _StandardEncoding, token.endpos()
668
+ if token.is_keyword('def'):
669
+ return encoding, token.endpos()
670
+ index_token = next(tokens)
671
+ if not index_token.is_number():
672
+ _log.warning(
673
+ f"Parsing encoding: expected number, got {index_token}"
674
+ )
675
+ continue
676
+ name_token = next(tokens)
677
+ if not name_token.is_slash_name():
678
+ _log.warning(
679
+ f"Parsing encoding: expected slash-name, got {name_token}"
680
+ )
681
+ continue
682
+ encoding[index_token.value()] = name_token.value()
683
+
684
+ @staticmethod
685
+ def _parse_othersubrs(tokens, data):
686
+ init_pos = None
687
+ while True:
688
+ token = next(tokens)
689
+ if init_pos is None:
690
+ init_pos = token.pos
691
+ if token.is_delim():
692
+ _expression(token, tokens, data)
693
+ elif token.is_keyword('def', 'ND', '|-'):
694
+ return data[init_pos:token.endpos()], token.endpos()
695
+
696
+ def transform(self, effects):
697
+ """
698
+ Return a new font that is slanted and/or extended.
699
+
700
+ Parameters
701
+ ----------
702
+ effects : dict
703
+ A dict with optional entries:
704
+
705
+ - 'slant' : float, default: 0
706
+ Tangent of the angle that the font is to be slanted to the
707
+ right. Negative values slant to the left.
708
+ - 'extend' : float, default: 1
709
+ Scaling factor for the font width. Values less than 1 condense
710
+ the glyphs.
711
+
712
+ Returns
713
+ -------
714
+ `Type1Font`
715
+ """
716
+ fontname = self.prop['FontName']
717
+ italicangle = self.prop['ItalicAngle']
718
+
719
+ array = [
720
+ float(x) for x in (self.prop['FontMatrix']
721
+ .lstrip('[').rstrip(']').split())
722
+ ]
723
+ oldmatrix = np.eye(3, 3)
724
+ oldmatrix[0:3, 0] = array[::2]
725
+ oldmatrix[0:3, 1] = array[1::2]
726
+ modifier = np.eye(3, 3)
727
+
728
+ if 'slant' in effects:
729
+ slant = effects['slant']
730
+ fontname += f'_Slant_{int(1000 * slant)}'
731
+ italicangle = round(
732
+ float(italicangle) - np.arctan(slant) / np.pi * 180,
733
+ 5
734
+ )
735
+ modifier[1, 0] = slant
736
+
737
+ if 'extend' in effects:
738
+ extend = effects['extend']
739
+ fontname += f'_Extend_{int(1000 * extend)}'
740
+ modifier[0, 0] = extend
741
+
742
+ newmatrix = np.dot(modifier, oldmatrix)
743
+ array[::2] = newmatrix[0:3, 0]
744
+ array[1::2] = newmatrix[0:3, 1]
745
+ fontmatrix = (
746
+ f"[{' '.join(_format_approx(x, 6) for x in array)}]"
747
+ )
748
+ replacements = (
749
+ [(x, f'/FontName/{fontname} def')
750
+ for x in self._pos['FontName']]
751
+ + [(x, f'/ItalicAngle {italicangle} def')
752
+ for x in self._pos['ItalicAngle']]
753
+ + [(x, f'/FontMatrix {fontmatrix} readonly def')
754
+ for x in self._pos['FontMatrix']]
755
+ + [(x, '') for x in self._pos.get('UniqueID', [])]
756
+ )
757
+
758
+ data = bytearray(self.parts[0])
759
+ data.extend(self.decrypted)
760
+ len0 = len(self.parts[0])
761
+ for (pos0, pos1), value in sorted(replacements, reverse=True):
762
+ data[pos0:pos1] = value.encode('ascii', 'replace')
763
+ if pos0 < len(self.parts[0]):
764
+ if pos1 >= len(self.parts[0]):
765
+ raise RuntimeError(
766
+ f"text to be replaced with {value} spans "
767
+ "the eexec boundary"
768
+ )
769
+ len0 += len(value) - pos1 + pos0
770
+
771
+ data = bytes(data)
772
+ return Type1Font((
773
+ data[:len0],
774
+ self._encrypt(data[len0:], 'eexec'),
775
+ self.parts[2]
776
+ ))
777
+
778
+
779
+ _StandardEncoding = {
780
+ **{ord(letter): letter for letter in string.ascii_letters},
781
+ 0: '.notdef',
782
+ 32: 'space',
783
+ 33: 'exclam',
784
+ 34: 'quotedbl',
785
+ 35: 'numbersign',
786
+ 36: 'dollar',
787
+ 37: 'percent',
788
+ 38: 'ampersand',
789
+ 39: 'quoteright',
790
+ 40: 'parenleft',
791
+ 41: 'parenright',
792
+ 42: 'asterisk',
793
+ 43: 'plus',
794
+ 44: 'comma',
795
+ 45: 'hyphen',
796
+ 46: 'period',
797
+ 47: 'slash',
798
+ 48: 'zero',
799
+ 49: 'one',
800
+ 50: 'two',
801
+ 51: 'three',
802
+ 52: 'four',
803
+ 53: 'five',
804
+ 54: 'six',
805
+ 55: 'seven',
806
+ 56: 'eight',
807
+ 57: 'nine',
808
+ 58: 'colon',
809
+ 59: 'semicolon',
810
+ 60: 'less',
811
+ 61: 'equal',
812
+ 62: 'greater',
813
+ 63: 'question',
814
+ 64: 'at',
815
+ 91: 'bracketleft',
816
+ 92: 'backslash',
817
+ 93: 'bracketright',
818
+ 94: 'asciicircum',
819
+ 95: 'underscore',
820
+ 96: 'quoteleft',
821
+ 123: 'braceleft',
822
+ 124: 'bar',
823
+ 125: 'braceright',
824
+ 126: 'asciitilde',
825
+ 161: 'exclamdown',
826
+ 162: 'cent',
827
+ 163: 'sterling',
828
+ 164: 'fraction',
829
+ 165: 'yen',
830
+ 166: 'florin',
831
+ 167: 'section',
832
+ 168: 'currency',
833
+ 169: 'quotesingle',
834
+ 170: 'quotedblleft',
835
+ 171: 'guillemotleft',
836
+ 172: 'guilsinglleft',
837
+ 173: 'guilsinglright',
838
+ 174: 'fi',
839
+ 175: 'fl',
840
+ 177: 'endash',
841
+ 178: 'dagger',
842
+ 179: 'daggerdbl',
843
+ 180: 'periodcentered',
844
+ 182: 'paragraph',
845
+ 183: 'bullet',
846
+ 184: 'quotesinglbase',
847
+ 185: 'quotedblbase',
848
+ 186: 'quotedblright',
849
+ 187: 'guillemotright',
850
+ 188: 'ellipsis',
851
+ 189: 'perthousand',
852
+ 191: 'questiondown',
853
+ 193: 'grave',
854
+ 194: 'acute',
855
+ 195: 'circumflex',
856
+ 196: 'tilde',
857
+ 197: 'macron',
858
+ 198: 'breve',
859
+ 199: 'dotaccent',
860
+ 200: 'dieresis',
861
+ 202: 'ring',
862
+ 203: 'cedilla',
863
+ 205: 'hungarumlaut',
864
+ 206: 'ogonek',
865
+ 207: 'caron',
866
+ 208: 'emdash',
867
+ 225: 'AE',
868
+ 227: 'ordfeminine',
869
+ 232: 'Lslash',
870
+ 233: 'Oslash',
871
+ 234: 'OE',
872
+ 235: 'ordmasculine',
873
+ 241: 'ae',
874
+ 245: 'dotlessi',
875
+ 248: 'lslash',
876
+ 249: 'oslash',
877
+ 250: 'oe',
878
+ 251: 'germandbls',
879
+ }
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ version = "3.10.8"
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/animation.py ADDED
@@ -0,0 +1,1823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import base64
3
+ import contextlib
4
+ from io import BytesIO, TextIOWrapper
5
+ import itertools
6
+ import logging
7
+ from pathlib import Path
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from tempfile import TemporaryDirectory
12
+ import uuid
13
+ import warnings
14
+
15
+ import numpy as np
16
+ from PIL import Image
17
+
18
+ import matplotlib as mpl
19
+ from matplotlib._animation_data import (
20
+ DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
21
+ from matplotlib import _api, cbook
22
+ import matplotlib.colors as mcolors
23
+
24
+ _log = logging.getLogger(__name__)
25
+
26
+ # Process creation flag for subprocess to prevent it raising a terminal
27
+ # window. See for example https://stackoverflow.com/q/24130623/
28
+ subprocess_creation_flags = (
29
+ subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
30
+
31
+
32
+ def adjusted_figsize(w, h, dpi, n):
33
+ """
34
+ Compute figure size so that pixels are a multiple of n.
35
+
36
+ Parameters
37
+ ----------
38
+ w, h : float
39
+ Size in inches.
40
+
41
+ dpi : float
42
+ The dpi.
43
+
44
+ n : int
45
+ The target multiple.
46
+
47
+ Returns
48
+ -------
49
+ wnew, hnew : float
50
+ The new figure size in inches.
51
+ """
52
+
53
+ # this maybe simplified if / when we adopt consistent rounding for
54
+ # pixel size across the whole library
55
+ def correct_roundoff(x, dpi, n):
56
+ if int(x*dpi) % n != 0:
57
+ if int(np.nextafter(x, np.inf)*dpi) % n == 0:
58
+ x = np.nextafter(x, np.inf)
59
+ elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
60
+ x = np.nextafter(x, -np.inf)
61
+ return x
62
+
63
+ wnew = int(w * dpi / n) * n / dpi
64
+ hnew = int(h * dpi / n) * n / dpi
65
+ return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
66
+
67
+
68
+ class MovieWriterRegistry:
69
+ """Registry of available writer classes by human readable name."""
70
+
71
+ def __init__(self):
72
+ self._registered = dict()
73
+
74
+ def register(self, name):
75
+ """
76
+ Decorator for registering a class under a name.
77
+
78
+ Example use::
79
+
80
+ @registry.register(name)
81
+ class Foo:
82
+ pass
83
+ """
84
+ def wrapper(writer_cls):
85
+ self._registered[name] = writer_cls
86
+ return writer_cls
87
+ return wrapper
88
+
89
+ def is_available(self, name):
90
+ """
91
+ Check if given writer is available by name.
92
+
93
+ Parameters
94
+ ----------
95
+ name : str
96
+
97
+ Returns
98
+ -------
99
+ bool
100
+ """
101
+ try:
102
+ cls = self._registered[name]
103
+ except KeyError:
104
+ return False
105
+ return cls.isAvailable()
106
+
107
+ def __iter__(self):
108
+ """Iterate over names of available writer class."""
109
+ for name in self._registered:
110
+ if self.is_available(name):
111
+ yield name
112
+
113
+ def list(self):
114
+ """Get a list of available MovieWriters."""
115
+ return [*self]
116
+
117
+ def __getitem__(self, name):
118
+ """Get an available writer class from its name."""
119
+ if self.is_available(name):
120
+ return self._registered[name]
121
+ raise RuntimeError(f"Requested MovieWriter ({name}) not available")
122
+
123
+
124
+ writers = MovieWriterRegistry()
125
+
126
+
127
+ class AbstractMovieWriter(abc.ABC):
128
+ """
129
+ Abstract base class for writing movies, providing a way to grab frames by
130
+ calling `~AbstractMovieWriter.grab_frame`.
131
+
132
+ `setup` is called to start the process and `finish` is called afterwards.
133
+ `saving` is provided as a context manager to facilitate this process as ::
134
+
135
+ with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
136
+ # Iterate over frames
137
+ moviewriter.grab_frame(**savefig_kwargs)
138
+
139
+ The use of the context manager ensures that `setup` and `finish` are
140
+ performed as necessary.
141
+
142
+ An instance of a concrete subclass of this class can be given as the
143
+ ``writer`` argument of `Animation.save()`.
144
+ """
145
+
146
+ def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
147
+ self.fps = fps
148
+ self.metadata = metadata if metadata is not None else {}
149
+ self.codec = mpl._val_or_rc(codec, 'animation.codec')
150
+ self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate')
151
+
152
+ @abc.abstractmethod
153
+ def setup(self, fig, outfile, dpi=None):
154
+ """
155
+ Setup for writing the movie file.
156
+
157
+ Parameters
158
+ ----------
159
+ fig : `~matplotlib.figure.Figure`
160
+ The figure object that contains the information for frames.
161
+ outfile : str
162
+ The filename of the resulting movie file.
163
+ dpi : float, default: ``fig.dpi``
164
+ The DPI (or resolution) for the file. This controls the size
165
+ in pixels of the resulting movie file.
166
+ """
167
+ # Check that path is valid
168
+ Path(outfile).parent.resolve(strict=True)
169
+ self.outfile = outfile
170
+ self.fig = fig
171
+ if dpi is None:
172
+ dpi = self.fig.dpi
173
+ self.dpi = dpi
174
+
175
+ @property
176
+ def frame_size(self):
177
+ """A tuple ``(width, height)`` in pixels of a movie frame."""
178
+ w, h = self.fig.get_size_inches()
179
+ return int(w * self.dpi), int(h * self.dpi)
180
+
181
+ def _supports_transparency(self):
182
+ """
183
+ Whether this writer supports transparency.
184
+
185
+ Writers may consult output file type and codec to determine this at runtime.
186
+ """
187
+ return False
188
+
189
+ @abc.abstractmethod
190
+ def grab_frame(self, **savefig_kwargs):
191
+ """
192
+ Grab the image information from the figure and save as a movie frame.
193
+
194
+ All keyword arguments in *savefig_kwargs* are passed on to the
195
+ `~.Figure.savefig` call that saves the figure. However, several
196
+ keyword arguments that are supported by `~.Figure.savefig` may not be
197
+ passed as they are controlled by the MovieWriter:
198
+
199
+ - *dpi*, *bbox_inches*: These may not be passed because each frame of the
200
+ animation much be exactly the same size in pixels.
201
+ - *format*: This is controlled by the MovieWriter.
202
+ """
203
+
204
+ @abc.abstractmethod
205
+ def finish(self):
206
+ """Finish any processing for writing the movie."""
207
+
208
+ @contextlib.contextmanager
209
+ def saving(self, fig, outfile, dpi, *args, **kwargs):
210
+ """
211
+ Context manager to facilitate writing the movie file.
212
+
213
+ ``*args, **kw`` are any parameters that should be passed to `setup`.
214
+ """
215
+ if mpl.rcParams['savefig.bbox'] == 'tight':
216
+ _log.info("Disabling savefig.bbox = 'tight', as it may cause "
217
+ "frame size to vary, which is inappropriate for "
218
+ "animation.")
219
+
220
+ # This particular sequence is what contextlib.contextmanager wants
221
+ self.setup(fig, outfile, dpi, *args, **kwargs)
222
+ with mpl.rc_context({'savefig.bbox': None}):
223
+ try:
224
+ yield self
225
+ finally:
226
+ self.finish()
227
+
228
+
229
+ class MovieWriter(AbstractMovieWriter):
230
+ """
231
+ Base class for writing movies.
232
+
233
+ This is a base class for MovieWriter subclasses that write a movie frame
234
+ data to a pipe. You cannot instantiate this class directly.
235
+ See examples for how to use its subclasses.
236
+
237
+ Attributes
238
+ ----------
239
+ frame_format : str
240
+ The format used in writing frame data, defaults to 'rgba'.
241
+ fig : `~matplotlib.figure.Figure`
242
+ The figure to capture data from.
243
+ This must be provided by the subclasses.
244
+ """
245
+
246
+ # Builtin writer subclasses additionally define the _exec_key and _args_key
247
+ # attributes, which indicate the rcParams entries where the path to the
248
+ # executable and additional command-line arguments to the executable are
249
+ # stored. Third-party writers cannot meaningfully set these as they cannot
250
+ # extend rcParams with new keys.
251
+
252
+ # Pipe-based writers only support RGBA, but file-based ones support more
253
+ # formats.
254
+ supported_formats = ["rgba"]
255
+
256
+ def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
257
+ metadata=None):
258
+ """
259
+ Parameters
260
+ ----------
261
+ fps : int, default: 5
262
+ Movie frame rate (per second).
263
+ codec : str or None, default: :rc:`animation.codec`
264
+ The codec to use.
265
+ bitrate : int, default: :rc:`animation.bitrate`
266
+ The bitrate of the movie, in kilobits per second. Higher values
267
+ means higher quality movies, but increase the file size. A value
268
+ of -1 lets the underlying movie encoder select the bitrate.
269
+ extra_args : list of str or None, optional
270
+ Extra command-line arguments passed to the underlying movie encoder. These
271
+ arguments are passed last to the encoder, just before the filename. The
272
+ default, None, means to use :rc:`animation.[name-of-encoder]_args` for the
273
+ builtin writers.
274
+ metadata : dict[str, str], default: {}
275
+ A dictionary of keys and values for metadata to include in the
276
+ output file. Some keys that may be of use include:
277
+ title, artist, genre, subject, copyright, srcform, comment.
278
+ """
279
+ if type(self) is MovieWriter:
280
+ # TODO MovieWriter is still an abstract class and needs to be
281
+ # extended with a mixin. This should be clearer in naming
282
+ # and description. For now, just give a reasonable error
283
+ # message to users.
284
+ raise TypeError(
285
+ 'MovieWriter cannot be instantiated directly. Please use one '
286
+ 'of its subclasses.')
287
+
288
+ super().__init__(fps=fps, metadata=metadata, codec=codec,
289
+ bitrate=bitrate)
290
+ self.frame_format = self.supported_formats[0]
291
+ self.extra_args = extra_args
292
+
293
+ def _adjust_frame_size(self):
294
+ if self.codec == 'h264':
295
+ wo, ho = self.fig.get_size_inches()
296
+ w, h = adjusted_figsize(wo, ho, self.dpi, 2)
297
+ if (wo, ho) != (w, h):
298
+ self.fig.set_size_inches(w, h, forward=True)
299
+ _log.info('figure size in inches has been adjusted '
300
+ 'from %s x %s to %s x %s', wo, ho, w, h)
301
+ else:
302
+ w, h = self.fig.get_size_inches()
303
+ _log.debug('frame size in pixels is %s x %s', *self.frame_size)
304
+ return w, h
305
+
306
+ def setup(self, fig, outfile, dpi=None):
307
+ # docstring inherited
308
+ super().setup(fig, outfile, dpi=dpi)
309
+ self._w, self._h = self._adjust_frame_size()
310
+ # Run here so that grab_frame() can write the data to a pipe. This
311
+ # eliminates the need for temp files.
312
+ self._run()
313
+
314
+ def _run(self):
315
+ # Uses subprocess to call the program for assembling frames into a
316
+ # movie file. *args* returns the sequence of command line arguments
317
+ # from a few configuration options.
318
+ command = self._args()
319
+ _log.info('MovieWriter._run: running command: %s',
320
+ cbook._pformat_subprocess(command))
321
+ PIPE = subprocess.PIPE
322
+ self._proc = subprocess.Popen(
323
+ command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
324
+ creationflags=subprocess_creation_flags)
325
+
326
+ def finish(self):
327
+ """Finish any processing for writing the movie."""
328
+ out, err = self._proc.communicate()
329
+ # Use the encoding/errors that universal_newlines would use.
330
+ out = TextIOWrapper(BytesIO(out)).read()
331
+ err = TextIOWrapper(BytesIO(err)).read()
332
+ if out:
333
+ _log.log(
334
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
335
+ "MovieWriter stdout:\n%s", out)
336
+ if err:
337
+ _log.log(
338
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
339
+ "MovieWriter stderr:\n%s", err)
340
+ if self._proc.returncode:
341
+ raise subprocess.CalledProcessError(
342
+ self._proc.returncode, self._proc.args, out, err)
343
+
344
+ def grab_frame(self, **savefig_kwargs):
345
+ # docstring inherited
346
+ _validate_grabframe_kwargs(savefig_kwargs)
347
+ _log.debug('MovieWriter.grab_frame: Grabbing frame.')
348
+ # Readjust the figure size in case it has been changed by the user.
349
+ # All frames must have the same size to save the movie correctly.
350
+ self.fig.set_size_inches(self._w, self._h)
351
+ # Save the figure data to the sink, using the frame format and dpi.
352
+ self.fig.savefig(self._proc.stdin, format=self.frame_format,
353
+ dpi=self.dpi, **savefig_kwargs)
354
+
355
+ def _args(self):
356
+ """Assemble list of encoder-specific command-line arguments."""
357
+ return NotImplementedError("args needs to be implemented by subclass.")
358
+
359
+ @classmethod
360
+ def bin_path(cls):
361
+ """
362
+ Return the binary path to the commandline tool used by a specific
363
+ subclass. This is a class method so that the tool can be looked for
364
+ before making a particular MovieWriter subclass available.
365
+ """
366
+ return str(mpl.rcParams[cls._exec_key])
367
+
368
+ @classmethod
369
+ def isAvailable(cls):
370
+ """Return whether a MovieWriter subclass is actually available."""
371
+ return shutil.which(cls.bin_path()) is not None
372
+
373
+
374
+ class FileMovieWriter(MovieWriter):
375
+ """
376
+ `MovieWriter` for writing to individual files and stitching at the end.
377
+
378
+ This must be sub-classed to be useful.
379
+ """
380
+ def __init__(self, *args, **kwargs):
381
+ super().__init__(*args, **kwargs)
382
+ self.frame_format = mpl.rcParams['animation.frame_format']
383
+
384
+ def setup(self, fig, outfile, dpi=None, frame_prefix=None):
385
+ """
386
+ Setup for writing the movie file.
387
+
388
+ Parameters
389
+ ----------
390
+ fig : `~matplotlib.figure.Figure`
391
+ The figure to grab the rendered frames from.
392
+ outfile : str
393
+ The filename of the resulting movie file.
394
+ dpi : float, default: ``fig.dpi``
395
+ The dpi of the output file. This, with the figure size,
396
+ controls the size in pixels of the resulting movie file.
397
+ frame_prefix : str, optional
398
+ The filename prefix to use for temporary files. If *None* (the
399
+ default), files are written to a temporary directory which is
400
+ deleted by `finish`; if not *None*, no temporary files are
401
+ deleted.
402
+ """
403
+ # Check that path is valid
404
+ Path(outfile).parent.resolve(strict=True)
405
+ self.fig = fig
406
+ self.outfile = outfile
407
+ if dpi is None:
408
+ dpi = self.fig.dpi
409
+ self.dpi = dpi
410
+ self._adjust_frame_size()
411
+
412
+ if frame_prefix is None:
413
+ self._tmpdir = TemporaryDirectory()
414
+ self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
415
+ else:
416
+ self._tmpdir = None
417
+ self.temp_prefix = frame_prefix
418
+ self._frame_counter = 0 # used for generating sequential file names
419
+ self._temp_paths = list()
420
+ self.fname_format_str = '%s%%07d.%s'
421
+
422
+ def __del__(self):
423
+ if hasattr(self, '_tmpdir') and self._tmpdir:
424
+ self._tmpdir.cleanup()
425
+
426
+ @property
427
+ def frame_format(self):
428
+ """
429
+ Format (png, jpeg, etc.) to use for saving the frames, which can be
430
+ decided by the individual subclasses.
431
+ """
432
+ return self._frame_format
433
+
434
+ @frame_format.setter
435
+ def frame_format(self, frame_format):
436
+ if frame_format in self.supported_formats:
437
+ self._frame_format = frame_format
438
+ else:
439
+ _api.warn_external(
440
+ f"Ignoring file format {frame_format!r} which is not "
441
+ f"supported by {type(self).__name__}; using "
442
+ f"{self.supported_formats[0]} instead.")
443
+ self._frame_format = self.supported_formats[0]
444
+
445
+ def _base_temp_name(self):
446
+ # Generates a template name (without number) given the frame format
447
+ # for extension and the prefix.
448
+ return self.fname_format_str % (self.temp_prefix, self.frame_format)
449
+
450
+ def grab_frame(self, **savefig_kwargs):
451
+ # docstring inherited
452
+ # Creates a filename for saving using basename and counter.
453
+ _validate_grabframe_kwargs(savefig_kwargs)
454
+ path = Path(self._base_temp_name() % self._frame_counter)
455
+ self._temp_paths.append(path) # Record the filename for later use.
456
+ self._frame_counter += 1 # Ensures each created name is unique.
457
+ _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
458
+ self._frame_counter, path)
459
+ with open(path, 'wb') as sink: # Save figure to the sink.
460
+ self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
461
+ **savefig_kwargs)
462
+
463
+ def finish(self):
464
+ # Call run here now that all frame grabbing is done. All temp files
465
+ # are available to be assembled.
466
+ try:
467
+ self._run()
468
+ super().finish()
469
+ finally:
470
+ if self._tmpdir:
471
+ _log.debug(
472
+ 'MovieWriter: clearing temporary path=%s', self._tmpdir
473
+ )
474
+ self._tmpdir.cleanup()
475
+
476
+
477
+ @writers.register('pillow')
478
+ class PillowWriter(AbstractMovieWriter):
479
+ def _supports_transparency(self):
480
+ return True
481
+
482
+ @classmethod
483
+ def isAvailable(cls):
484
+ return True
485
+
486
+ def setup(self, fig, outfile, dpi=None):
487
+ super().setup(fig, outfile, dpi=dpi)
488
+ self._frames = []
489
+
490
+ def grab_frame(self, **savefig_kwargs):
491
+ _validate_grabframe_kwargs(savefig_kwargs)
492
+ buf = BytesIO()
493
+ self.fig.savefig(
494
+ buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
495
+ im = Image.frombuffer(
496
+ "RGBA", self.frame_size, buf.getbuffer(), "raw", "RGBA", 0, 1)
497
+ if im.getextrema()[3][0] < 255:
498
+ # This frame has transparency, so we'll just add it as is.
499
+ self._frames.append(im)
500
+ else:
501
+ # Without transparency, we switch to RGB mode, which converts to P mode a
502
+ # little better if needed (specifically, this helps with GIF output.)
503
+ self._frames.append(im.convert("RGB"))
504
+
505
+ def finish(self):
506
+ self._frames[0].save(
507
+ self.outfile, save_all=True, append_images=self._frames[1:],
508
+ duration=int(1000 / self.fps), loop=0)
509
+
510
+
511
+ # Base class of ffmpeg information. Has the config keys and the common set
512
+ # of arguments that controls the *output* side of things.
513
+ class FFMpegBase:
514
+ """
515
+ Mixin class for FFMpeg output.
516
+
517
+ This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
518
+ classes.
519
+ """
520
+
521
+ _exec_key = 'animation.ffmpeg_path'
522
+ _args_key = 'animation.ffmpeg_args'
523
+
524
+ def _supports_transparency(self):
525
+ suffix = Path(self.outfile).suffix
526
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
527
+ return True
528
+ # This list was found by going through `ffmpeg -codecs` for video encoders,
529
+ # running them with _support_transparency() forced to True, and checking that
530
+ # the "Pixel format" in Kdenlive included alpha. Note this is not a guarantee
531
+ # that transparency will work; you may also need to pass `-pix_fmt`, but we
532
+ # trust the user has done so if they are asking for these formats.
533
+ return self.codec in {
534
+ 'apng', 'avrp', 'bmp', 'cfhd', 'dpx', 'ffv1', 'ffvhuff', 'gif', 'huffyuv',
535
+ 'jpeg2000', 'ljpeg', 'png', 'prores', 'prores_aw', 'prores_ks', 'qtrle',
536
+ 'rawvideo', 'targa', 'tiff', 'utvideo', 'v408', }
537
+
538
+ @property
539
+ def output_args(self):
540
+ args = []
541
+ suffix = Path(self.outfile).suffix
542
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
543
+ self.codec = suffix[1:]
544
+ else:
545
+ args.extend(['-vcodec', self.codec])
546
+ extra_args = (self.extra_args if self.extra_args is not None
547
+ else mpl.rcParams[self._args_key])
548
+ # For h264, the default format is yuv444p, which is not compatible
549
+ # with quicktime (and others). Specifying yuv420p fixes playback on
550
+ # iOS, as well as HTML5 video in firefox and safari (on both Windows and
551
+ # macOS). Also fixes internet explorer. This is as of 2015/10/29.
552
+ if self.codec == 'h264' and '-pix_fmt' not in extra_args:
553
+ args.extend(['-pix_fmt', 'yuv420p'])
554
+ # For GIF, we're telling FFmpeg to split the video stream, to generate
555
+ # a palette, and then use it for encoding.
556
+ elif self.codec == 'gif' and '-filter_complex' not in extra_args:
557
+ args.extend(['-filter_complex',
558
+ 'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
559
+ # For AVIF, we're telling FFmpeg to split the video stream, extract the alpha,
560
+ # in order to place it in a secondary stream, as needed by AVIF-in-FFmpeg.
561
+ elif self.codec == 'avif' and '-filter_complex' not in extra_args:
562
+ args.extend(['-filter_complex',
563
+ 'split [rgb][rgba]; [rgba] alphaextract [alpha]',
564
+ '-map', '[rgb]', '-map', '[alpha]'])
565
+ if self.bitrate > 0:
566
+ args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
567
+ for k, v in self.metadata.items():
568
+ args.extend(['-metadata', f'{k}={v}'])
569
+ args.extend(extra_args)
570
+
571
+ return args + ['-y', self.outfile]
572
+
573
+
574
+ # Combine FFMpeg options with pipe-based writing
575
+ @writers.register('ffmpeg')
576
+ class FFMpegWriter(FFMpegBase, MovieWriter):
577
+ """
578
+ Pipe-based ffmpeg writer.
579
+
580
+ Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
581
+
582
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
583
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
584
+
585
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
586
+ """
587
+ def _args(self):
588
+ # Returns the command line parameters for subprocess to use
589
+ # ffmpeg to create a movie using a pipe.
590
+ args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
591
+ '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
592
+ '-framerate', str(self.fps)]
593
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
594
+ # If you have a lot of frames in your animation and set logging to
595
+ # DEBUG, you will have a buffer overrun.
596
+ if _log.getEffectiveLevel() > logging.DEBUG:
597
+ args += ['-loglevel', 'error']
598
+ args += ['-i', 'pipe:'] + self.output_args
599
+ return args
600
+
601
+
602
+ # Combine FFMpeg options with temp file-based writing
603
+ @writers.register('ffmpeg_file')
604
+ class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
605
+ """
606
+ File-based ffmpeg writer.
607
+
608
+ Frames are written to temporary files on disk and then stitched together at the end.
609
+
610
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
611
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
612
+
613
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
614
+ """
615
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
616
+
617
+ def _args(self):
618
+ # Returns the command line parameters for subprocess to use
619
+ # ffmpeg to create a movie using a collection of temp images
620
+ args = []
621
+ # For raw frames, we need to explicitly tell ffmpeg the metadata.
622
+ if self.frame_format in {'raw', 'rgba'}:
623
+ args += [
624
+ '-f', 'image2', '-vcodec', 'rawvideo',
625
+ '-video_size', '%dx%d' % self.frame_size,
626
+ '-pixel_format', 'rgba',
627
+ ]
628
+ args += ['-framerate', str(self.fps), '-i', self._base_temp_name()]
629
+ if not self._tmpdir:
630
+ args += ['-frames:v', str(self._frame_counter)]
631
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
632
+ # If you have a lot of frames in your animation and set logging to
633
+ # DEBUG, you will have a buffer overrun.
634
+ if _log.getEffectiveLevel() > logging.DEBUG:
635
+ args += ['-loglevel', 'error']
636
+ return [self.bin_path(), *args, *self.output_args]
637
+
638
+
639
+ # Base class for animated GIFs with ImageMagick
640
+ class ImageMagickBase:
641
+ """
642
+ Mixin class for ImageMagick output.
643
+
644
+ This is a base class for the concrete `ImageMagickWriter` and
645
+ `ImageMagickFileWriter` classes, which define an ``input_names`` attribute
646
+ (or property) specifying the input names passed to ImageMagick.
647
+ """
648
+
649
+ _exec_key = 'animation.convert_path'
650
+ _args_key = 'animation.convert_args'
651
+
652
+ def _supports_transparency(self):
653
+ suffix = Path(self.outfile).suffix
654
+ return suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}
655
+
656
+ def _args(self):
657
+ # ImageMagick does not recognize "raw".
658
+ fmt = "rgba" if self.frame_format == "raw" else self.frame_format
659
+ extra_args = (self.extra_args if self.extra_args is not None
660
+ else mpl.rcParams[self._args_key])
661
+ return [
662
+ self.bin_path(),
663
+ "-size", "%ix%i" % self.frame_size,
664
+ "-depth", "8",
665
+ "-delay", str(100 / self.fps),
666
+ "-loop", "0",
667
+ f"{fmt}:{self.input_names}",
668
+ *extra_args,
669
+ self.outfile,
670
+ ]
671
+
672
+ @classmethod
673
+ def bin_path(cls):
674
+ binpath = super().bin_path()
675
+ if binpath == 'convert':
676
+ binpath = mpl._get_executable_info('magick').executable
677
+ return binpath
678
+
679
+ @classmethod
680
+ def isAvailable(cls):
681
+ try:
682
+ return super().isAvailable()
683
+ except mpl.ExecutableNotFoundError as _enf:
684
+ # May be raised by get_executable_info.
685
+ _log.debug('ImageMagick unavailable due to: %s', _enf)
686
+ return False
687
+
688
+
689
+ # Combine ImageMagick options with pipe-based writing
690
+ @writers.register('imagemagick')
691
+ class ImageMagickWriter(ImageMagickBase, MovieWriter):
692
+ """
693
+ Pipe-based animated gif writer.
694
+
695
+ Frames are streamed directly to ImageMagick via a pipe and written
696
+ in a single pass.
697
+ """
698
+
699
+ input_names = "-" # stdin
700
+
701
+
702
+ # Combine ImageMagick options with temp file-based writing
703
+ @writers.register('imagemagick_file')
704
+ class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
705
+ """
706
+ File-based animated gif writer.
707
+
708
+ Frames are written to temporary files on disk and then stitched
709
+ together at the end.
710
+ """
711
+
712
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
713
+ input_names = property(
714
+ lambda self: f'{self.temp_prefix}*.{self.frame_format}')
715
+
716
+
717
+ # Taken directly from jakevdp's JSAnimation package at
718
+ # http://github.com/jakevdp/JSAnimation
719
+ def _included_frames(frame_count, frame_format, frame_dir):
720
+ return INCLUDED_FRAMES.format(Nframes=frame_count,
721
+ frame_dir=frame_dir,
722
+ frame_format=frame_format)
723
+
724
+
725
+ def _embedded_frames(frame_list, frame_format):
726
+ """frame_list should be a list of base64-encoded png files"""
727
+ if frame_format == 'svg':
728
+ # Fix MIME type for svg
729
+ frame_format = 'svg+xml'
730
+ template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
731
+ return "\n" + "".join(
732
+ template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
733
+ for i, frame_data in enumerate(frame_list))
734
+
735
+
736
+ @writers.register('html')
737
+ class HTMLWriter(FileMovieWriter):
738
+ """Writer for JavaScript-based HTML movies."""
739
+
740
+ supported_formats = ['png', 'jpeg', 'tiff', 'svg']
741
+
742
+ @classmethod
743
+ def isAvailable(cls):
744
+ return True
745
+
746
+ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
747
+ metadata=None, embed_frames=False, default_mode='loop',
748
+ embed_limit=None):
749
+
750
+ if extra_args:
751
+ _log.warning("HTMLWriter ignores 'extra_args'")
752
+ extra_args = () # Don't lookup nonexistent rcParam[args_key].
753
+ self.embed_frames = embed_frames
754
+ self.default_mode = default_mode.lower()
755
+ _api.check_in_list(['loop', 'once', 'reflect'],
756
+ default_mode=self.default_mode)
757
+
758
+ # Save embed limit, which is given in MB
759
+ self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
760
+ # Convert from MB to bytes
761
+ self._bytes_limit *= 1024 * 1024
762
+
763
+ super().__init__(fps, codec, bitrate, extra_args, metadata)
764
+
765
+ def setup(self, fig, outfile, dpi=None, frame_dir=None):
766
+ outfile = Path(outfile)
767
+ _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
768
+
769
+ self._saved_frames = []
770
+ self._total_bytes = 0
771
+ self._hit_limit = False
772
+
773
+ if not self.embed_frames:
774
+ if frame_dir is None:
775
+ frame_dir = outfile.with_name(outfile.stem + '_frames')
776
+ frame_dir.mkdir(parents=True, exist_ok=True)
777
+ frame_prefix = frame_dir / 'frame'
778
+ else:
779
+ frame_prefix = None
780
+
781
+ super().setup(fig, outfile, dpi, frame_prefix)
782
+ self._clear_temp = False
783
+
784
+ def grab_frame(self, **savefig_kwargs):
785
+ _validate_grabframe_kwargs(savefig_kwargs)
786
+ if self.embed_frames:
787
+ # Just stop processing if we hit the limit
788
+ if self._hit_limit:
789
+ return
790
+ f = BytesIO()
791
+ self.fig.savefig(f, format=self.frame_format,
792
+ dpi=self.dpi, **savefig_kwargs)
793
+ imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
794
+ self._total_bytes += len(imgdata64)
795
+ if self._total_bytes >= self._bytes_limit:
796
+ _log.warning(
797
+ "Animation size has reached %s bytes, exceeding the limit "
798
+ "of %s. If you're sure you want a larger animation "
799
+ "embedded, set the animation.embed_limit rc parameter to "
800
+ "a larger value (in MB). This and further frames will be "
801
+ "dropped.", self._total_bytes, self._bytes_limit)
802
+ self._hit_limit = True
803
+ else:
804
+ self._saved_frames.append(imgdata64)
805
+ else:
806
+ return super().grab_frame(**savefig_kwargs)
807
+
808
+ def finish(self):
809
+ # save the frames to an html file
810
+ if self.embed_frames:
811
+ fill_frames = _embedded_frames(self._saved_frames,
812
+ self.frame_format)
813
+ frame_count = len(self._saved_frames)
814
+ else:
815
+ # temp names is filled by FileMovieWriter
816
+ frame_count = len(self._temp_paths)
817
+ fill_frames = _included_frames(
818
+ frame_count, self.frame_format,
819
+ self._temp_paths[0].parent.relative_to(self.outfile.parent))
820
+ mode_dict = dict(once_checked='',
821
+ loop_checked='',
822
+ reflect_checked='')
823
+ mode_dict[self.default_mode + '_checked'] = 'checked'
824
+
825
+ interval = 1000 // self.fps
826
+
827
+ with open(self.outfile, 'w') as of:
828
+ of.write(JS_INCLUDE + STYLE_INCLUDE)
829
+ of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
830
+ Nframes=frame_count,
831
+ fill_frames=fill_frames,
832
+ interval=interval,
833
+ **mode_dict))
834
+
835
+ # Duplicate the temporary file clean up logic from
836
+ # FileMovieWriter.finish. We cannot call the inherited version of
837
+ # finish because it assumes that there is a subprocess that we either
838
+ # need to call to merge many frames together or that there is a
839
+ # subprocess call that we need to clean up.
840
+ if self._tmpdir:
841
+ _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
842
+ self._tmpdir.cleanup()
843
+
844
+
845
+ class Animation:
846
+ """
847
+ A base class for Animations.
848
+
849
+ This class is not usable as is, and should be subclassed to provide needed
850
+ behavior.
851
+
852
+ .. note::
853
+
854
+ You must store the created Animation in a variable that lives as long
855
+ as the animation should run. Otherwise, the Animation object will be
856
+ garbage-collected and the animation stops.
857
+
858
+ Parameters
859
+ ----------
860
+ fig : `~matplotlib.figure.Figure`
861
+ The figure object used to get needed events, such as draw or resize.
862
+
863
+ event_source : object, optional
864
+ A class that can run a callback when desired events
865
+ are generated, as well as be stopped and started.
866
+
867
+ Examples include timers (see `TimedAnimation`) and file
868
+ system notifications.
869
+
870
+ blit : bool, default: False
871
+ Whether blitting is used to optimize drawing. If the backend does not
872
+ support blitting, then this parameter has no effect.
873
+
874
+ See Also
875
+ --------
876
+ FuncAnimation, ArtistAnimation
877
+ """
878
+
879
+ def __init__(self, fig, event_source=None, blit=False):
880
+ self._draw_was_started = False
881
+
882
+ self._fig = fig
883
+ # Disables blitting for backends that don't support it. This
884
+ # allows users to request it if available, but still have a
885
+ # fallback that works if it is not.
886
+ self._blit = blit and fig.canvas.supports_blit
887
+
888
+ # These are the basics of the animation. The frame sequence represents
889
+ # information for each frame of the animation and depends on how the
890
+ # drawing is handled by the subclasses. The event source fires events
891
+ # that cause the frame sequence to be iterated.
892
+ self.frame_seq = self.new_frame_seq()
893
+ self.event_source = event_source
894
+
895
+ # Instead of starting the event source now, we connect to the figure's
896
+ # draw_event, so that we only start once the figure has been drawn.
897
+ self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
898
+
899
+ # Connect to the figure's close_event so that we don't continue to
900
+ # fire events and try to draw to a deleted figure.
901
+ self._close_id = self._fig.canvas.mpl_connect('close_event',
902
+ self._stop)
903
+ if self._blit:
904
+ self._setup_blit()
905
+
906
+ def __del__(self):
907
+ if not getattr(self, '_draw_was_started', True):
908
+ warnings.warn(
909
+ 'Animation was deleted without rendering anything. This is '
910
+ 'most likely not intended. To prevent deletion, assign the '
911
+ 'Animation to a variable, e.g. `anim`, that exists until you '
912
+ 'output the Animation using `plt.show()` or '
913
+ '`anim.save()`.'
914
+ )
915
+
916
+ def _start(self, *args):
917
+ """
918
+ Starts interactive animation. Adds the draw frame command to the GUI
919
+ handler, calls show to start the event loop.
920
+ """
921
+ # Do not start the event source if saving() it.
922
+ if self._fig.canvas.is_saving():
923
+ return
924
+ # First disconnect our draw event handler
925
+ self._fig.canvas.mpl_disconnect(self._first_draw_id)
926
+
927
+ # Now do any initial draw
928
+ self._init_draw()
929
+
930
+ # Add our callback for stepping the animation and
931
+ # actually start the event_source.
932
+ self.event_source.add_callback(self._step)
933
+ self.event_source.start()
934
+
935
+ def _stop(self, *args):
936
+ # On stop we disconnect all of our events.
937
+ if self._blit:
938
+ self._fig.canvas.mpl_disconnect(self._resize_id)
939
+ self._fig.canvas.mpl_disconnect(self._close_id)
940
+ self.event_source.remove_callback(self._step)
941
+ self.event_source = None
942
+
943
+ def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
944
+ bitrate=None, extra_args=None, metadata=None, extra_anim=None,
945
+ savefig_kwargs=None, *, progress_callback=None):
946
+ """
947
+ Save the animation as a movie file by drawing every frame.
948
+
949
+ Parameters
950
+ ----------
951
+ filename : str
952
+ The output filename, e.g., :file:`mymovie.mp4`.
953
+
954
+ writer : `MovieWriter` or str, default: :rc:`animation.writer`
955
+ A `MovieWriter` instance to use or a key that identifies a
956
+ class to use, such as 'ffmpeg'.
957
+
958
+ fps : int, optional
959
+ Movie frame rate (per second). If not set, the frame rate from the
960
+ animation's frame interval.
961
+
962
+ dpi : float, default: :rc:`savefig.dpi`
963
+ Controls the dots per inch for the movie frames. Together with
964
+ the figure's size in inches, this controls the size of the movie.
965
+
966
+ codec : str, default: :rc:`animation.codec`.
967
+ The video codec to use. Not all codecs are supported by a given
968
+ `MovieWriter`.
969
+
970
+ bitrate : int, default: :rc:`animation.bitrate`
971
+ The bitrate of the movie, in kilobits per second. Higher values
972
+ means higher quality movies, but increase the file size. A value
973
+ of -1 lets the underlying movie encoder select the bitrate.
974
+
975
+ extra_args : list of str or None, optional
976
+ Extra command-line arguments passed to the underlying movie encoder. These
977
+ arguments are passed last to the encoder, just before the output filename.
978
+ The default, None, means to use :rc:`animation.[name-of-encoder]_args` for
979
+ the builtin writers.
980
+
981
+ metadata : dict[str, str], default: {}
982
+ Dictionary of keys and values for metadata to include in
983
+ the output file. Some keys that may be of use include:
984
+ title, artist, genre, subject, copyright, srcform, comment.
985
+
986
+ extra_anim : list, default: []
987
+ Additional `Animation` objects that should be included
988
+ in the saved movie file. These need to be from the same
989
+ `.Figure` instance. Also, animation frames will
990
+ just be simply combined, so there should be a 1:1 correspondence
991
+ between the frames from the different animations.
992
+
993
+ savefig_kwargs : dict, default: {}
994
+ Keyword arguments passed to each `~.Figure.savefig` call used to
995
+ save the individual frames.
996
+
997
+ progress_callback : function, optional
998
+ A callback function that will be called for every frame to notify
999
+ the saving progress. It must have the signature ::
1000
+
1001
+ def func(current_frame: int, total_frames: int) -> Any
1002
+
1003
+ where *current_frame* is the current frame number and *total_frames* is the
1004
+ total number of frames to be saved. *total_frames* is set to None, if the
1005
+ total number of frames cannot be determined. Return values may exist but are
1006
+ ignored.
1007
+
1008
+ Example code to write the progress to stdout::
1009
+
1010
+ progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
1011
+
1012
+ Notes
1013
+ -----
1014
+ *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
1015
+ construct a `.MovieWriter` instance and can only be passed if
1016
+ *writer* is a string. If they are passed as non-*None* and *writer*
1017
+ is a `.MovieWriter`, a `RuntimeError` will be raised.
1018
+ """
1019
+
1020
+ all_anim = [self]
1021
+ if extra_anim is not None:
1022
+ all_anim.extend(anim for anim in extra_anim
1023
+ if anim._fig is self._fig)
1024
+
1025
+ # Disable "Animation was deleted without rendering" warning.
1026
+ for anim in all_anim:
1027
+ anim._draw_was_started = True
1028
+
1029
+ if writer is None:
1030
+ writer = mpl.rcParams['animation.writer']
1031
+ elif (not isinstance(writer, str) and
1032
+ any(arg is not None
1033
+ for arg in (fps, codec, bitrate, extra_args, metadata))):
1034
+ raise RuntimeError('Passing in values for arguments '
1035
+ 'fps, codec, bitrate, extra_args, or metadata '
1036
+ 'is not supported when writer is an existing '
1037
+ 'MovieWriter instance. These should instead be '
1038
+ 'passed as arguments when creating the '
1039
+ 'MovieWriter instance.')
1040
+
1041
+ if savefig_kwargs is None:
1042
+ savefig_kwargs = {}
1043
+ else:
1044
+ # we are going to mutate this below
1045
+ savefig_kwargs = dict(savefig_kwargs)
1046
+
1047
+ if fps is None and hasattr(self, '_interval'):
1048
+ # Convert interval in ms to frames per second
1049
+ fps = 1000. / self._interval
1050
+
1051
+ # Reuse the savefig DPI for ours if none is given.
1052
+ dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
1053
+ if dpi == 'figure':
1054
+ dpi = self._fig.dpi
1055
+
1056
+ writer_kwargs = {}
1057
+ if codec is not None:
1058
+ writer_kwargs['codec'] = codec
1059
+ if bitrate is not None:
1060
+ writer_kwargs['bitrate'] = bitrate
1061
+ if extra_args is not None:
1062
+ writer_kwargs['extra_args'] = extra_args
1063
+ if metadata is not None:
1064
+ writer_kwargs['metadata'] = metadata
1065
+
1066
+ # If we have the name of a writer, instantiate an instance of the
1067
+ # registered class.
1068
+ if isinstance(writer, str):
1069
+ try:
1070
+ writer_cls = writers[writer]
1071
+ except RuntimeError: # Raised if not available.
1072
+ writer_cls = PillowWriter # Always available.
1073
+ _log.warning("MovieWriter %s unavailable; using Pillow "
1074
+ "instead.", writer)
1075
+ writer = writer_cls(fps, **writer_kwargs)
1076
+ _log.info('Animation.save using %s', type(writer))
1077
+
1078
+ if 'bbox_inches' in savefig_kwargs:
1079
+ _log.warning("Warning: discarding the 'bbox_inches' argument in "
1080
+ "'savefig_kwargs' as it may cause frame size "
1081
+ "to vary, which is inappropriate for animation.")
1082
+ savefig_kwargs.pop('bbox_inches')
1083
+
1084
+ # Create a new sequence of frames for saved data. This is different
1085
+ # from new_frame_seq() to give the ability to save 'live' generated
1086
+ # frame information to be saved later.
1087
+ # TODO: Right now, after closing the figure, saving a movie won't work
1088
+ # since GUI widgets are gone. Either need to remove extra code to
1089
+ # allow for this non-existent use case or find a way to make it work.
1090
+
1091
+ def _pre_composite_to_white(color):
1092
+ r, g, b, a = mcolors.to_rgba(color)
1093
+ return a * np.array([r, g, b]) + 1 - a
1094
+
1095
+ # canvas._is_saving = True makes the draw_event animation-starting
1096
+ # callback a no-op; canvas.manager = None prevents resizing the GUI
1097
+ # widget (both are likewise done in savefig()).
1098
+ with (writer.saving(self._fig, filename, dpi),
1099
+ cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
1100
+ if not writer._supports_transparency():
1101
+ facecolor = savefig_kwargs.get('facecolor',
1102
+ mpl.rcParams['savefig.facecolor'])
1103
+ if facecolor == 'auto':
1104
+ facecolor = self._fig.get_facecolor()
1105
+ savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
1106
+ savefig_kwargs['transparent'] = False # just to be safe!
1107
+
1108
+ for anim in all_anim:
1109
+ anim._init_draw() # Clear the initial frame
1110
+ frame_number = 0
1111
+ # TODO: Currently only FuncAnimation has a save_count
1112
+ # attribute. Can we generalize this to all Animations?
1113
+ save_count_list = [getattr(a, '_save_count', None)
1114
+ for a in all_anim]
1115
+ if None in save_count_list:
1116
+ total_frames = None
1117
+ else:
1118
+ total_frames = sum(save_count_list)
1119
+ for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
1120
+ for anim, d in zip(all_anim, data):
1121
+ # TODO: See if turning off blit is really necessary
1122
+ anim._draw_next_frame(d, blit=False)
1123
+ if progress_callback is not None:
1124
+ progress_callback(frame_number, total_frames)
1125
+ frame_number += 1
1126
+ writer.grab_frame(**savefig_kwargs)
1127
+
1128
+ def _step(self, *args):
1129
+ """
1130
+ Handler for getting events. By default, gets the next frame in the
1131
+ sequence and hands the data off to be drawn.
1132
+ """
1133
+ # Returns True to indicate that the event source should continue to
1134
+ # call _step, until the frame sequence reaches the end of iteration,
1135
+ # at which point False will be returned.
1136
+ try:
1137
+ framedata = next(self.frame_seq)
1138
+ self._draw_next_frame(framedata, self._blit)
1139
+ return True
1140
+ except StopIteration:
1141
+ return False
1142
+
1143
+ def new_frame_seq(self):
1144
+ """Return a new sequence of frame information."""
1145
+ # Default implementation is just an iterator over self._framedata
1146
+ return iter(self._framedata)
1147
+
1148
+ def new_saved_frame_seq(self):
1149
+ """Return a new sequence of saved/cached frame information."""
1150
+ # Default is the same as the regular frame sequence
1151
+ return self.new_frame_seq()
1152
+
1153
+ def _draw_next_frame(self, framedata, blit):
1154
+ # Breaks down the drawing of the next frame into steps of pre- and
1155
+ # post- draw, as well as the drawing of the frame itself.
1156
+ self._pre_draw(framedata, blit)
1157
+ self._draw_frame(framedata)
1158
+ self._post_draw(framedata, blit)
1159
+
1160
+ def _init_draw(self):
1161
+ # Initial draw to clear the frame. Also used by the blitting code
1162
+ # when a clean base is required.
1163
+ self._draw_was_started = True
1164
+
1165
+ def _pre_draw(self, framedata, blit):
1166
+ # Perform any cleaning or whatnot before the drawing of the frame.
1167
+ # This default implementation allows blit to clear the frame.
1168
+ if blit:
1169
+ self._blit_clear(self._drawn_artists)
1170
+
1171
+ def _draw_frame(self, framedata):
1172
+ # Performs actual drawing of the frame.
1173
+ raise NotImplementedError('Needs to be implemented by subclasses to'
1174
+ ' actually make an animation.')
1175
+
1176
+ def _post_draw(self, framedata, blit):
1177
+ # After the frame is rendered, this handles the actual flushing of
1178
+ # the draw, which can be a direct draw_idle() or make use of the
1179
+ # blitting.
1180
+ if blit and self._drawn_artists:
1181
+ self._blit_draw(self._drawn_artists)
1182
+ else:
1183
+ self._fig.canvas.draw_idle()
1184
+
1185
+ # The rest of the code in this class is to facilitate easy blitting
1186
+ def _blit_draw(self, artists):
1187
+ # Handles blitted drawing, which renders only the artists given instead
1188
+ # of the entire figure.
1189
+ updated_ax = {a.axes for a in artists}
1190
+ # Enumerate artists to cache Axes backgrounds. We do not draw
1191
+ # artists yet to not cache foreground from plots with shared Axes
1192
+ for ax in updated_ax:
1193
+ # If we haven't cached the background for the current view of this
1194
+ # Axes object, do so now. This might not always be reliable, but
1195
+ # it's an attempt to automate the process.
1196
+ cur_view = ax._get_view()
1197
+ view, bg = self._blit_cache.get(ax, (object(), None))
1198
+ if cur_view != view:
1199
+ self._blit_cache[ax] = (
1200
+ cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
1201
+ # Make a separate pass to draw foreground.
1202
+ for a in artists:
1203
+ a.axes.draw_artist(a)
1204
+ # After rendering all the needed artists, blit each Axes individually.
1205
+ for ax in updated_ax:
1206
+ ax.figure.canvas.blit(ax.bbox)
1207
+
1208
+ def _blit_clear(self, artists):
1209
+ # Get a list of the Axes that need clearing from the artists that
1210
+ # have been drawn. Grab the appropriate saved background from the
1211
+ # cache and restore.
1212
+ axes = {a.axes for a in artists}
1213
+ for ax in axes:
1214
+ try:
1215
+ view, bg = self._blit_cache[ax]
1216
+ except KeyError:
1217
+ continue
1218
+ if ax._get_view() == view:
1219
+ ax.figure.canvas.restore_region(bg)
1220
+ else:
1221
+ self._blit_cache.pop(ax)
1222
+
1223
+ def _setup_blit(self):
1224
+ # Setting up the blit requires: a cache of the background for the Axes
1225
+ self._blit_cache = dict()
1226
+ self._drawn_artists = []
1227
+ # _post_draw needs to be called first to initialize the renderer
1228
+ self._post_draw(None, self._blit)
1229
+ # Then we need to clear the Frame for the initial draw
1230
+ # This is typically handled in _on_resize because QT and Tk
1231
+ # emit a resize event on launch, but the macosx backend does not,
1232
+ # thus we force it here for everyone for consistency
1233
+ self._init_draw()
1234
+ # Connect to future resize events
1235
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
1236
+ self._on_resize)
1237
+
1238
+ def _on_resize(self, event):
1239
+ # On resize, we need to disable the resize event handling so we don't
1240
+ # get too many events. Also stop the animation events, so that
1241
+ # we're paused. Reset the cache and re-init. Set up an event handler
1242
+ # to catch once the draw has actually taken place.
1243
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1244
+ self.event_source.stop()
1245
+ self._blit_cache.clear()
1246
+ self._init_draw()
1247
+ self._resize_id = self._fig.canvas.mpl_connect('draw_event',
1248
+ self._end_redraw)
1249
+
1250
+ def _end_redraw(self, event):
1251
+ # Now that the redraw has happened, do the post draw flushing and
1252
+ # blit handling. Then re-enable all of the original events.
1253
+ self._post_draw(None, False)
1254
+ self.event_source.start()
1255
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1256
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
1257
+ self._on_resize)
1258
+
1259
+ def to_html5_video(self, embed_limit=None):
1260
+ """
1261
+ Convert the animation to an HTML5 ``<video>`` tag.
1262
+
1263
+ This saves the animation as an h264 video, encoded in base64
1264
+ directly into the HTML5 video tag. This respects :rc:`animation.writer`
1265
+ and :rc:`animation.bitrate`. This also makes use of the
1266
+ *interval* to control the speed, and uses the *repeat*
1267
+ parameter to decide whether to loop.
1268
+
1269
+ Parameters
1270
+ ----------
1271
+ embed_limit : float, optional
1272
+ Limit, in MB, of the returned animation. No animation is created
1273
+ if the limit is exceeded.
1274
+ Defaults to :rc:`animation.embed_limit` = 20.0.
1275
+
1276
+ Returns
1277
+ -------
1278
+ str
1279
+ An HTML5 video tag with the animation embedded as base64 encoded
1280
+ h264 video.
1281
+ If the *embed_limit* is exceeded, this returns the string
1282
+ "Video too large to embed."
1283
+ """
1284
+ VIDEO_TAG = r'''<video {size} {options}>
1285
+ <source type="video/mp4" src="data:video/mp4;base64,{video}">
1286
+ Your browser does not support the video tag.
1287
+ </video>'''
1288
+ # Cache the rendering of the video as HTML
1289
+ if not hasattr(self, '_base64_video'):
1290
+ # Save embed limit, which is given in MB
1291
+ embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
1292
+
1293
+ # Convert from MB to bytes
1294
+ embed_limit *= 1024 * 1024
1295
+
1296
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
1297
+ # TemporaryDirectory instead.
1298
+ with TemporaryDirectory() as tmpdir:
1299
+ path = Path(tmpdir, "temp.m4v")
1300
+ # We create a writer manually so that we can get the
1301
+ # appropriate size for the tag
1302
+ Writer = writers[mpl.rcParams['animation.writer']]
1303
+ writer = Writer(codec='h264',
1304
+ bitrate=mpl.rcParams['animation.bitrate'],
1305
+ fps=1000. / self._interval)
1306
+ self.save(str(path), writer=writer)
1307
+ # Now open and base64 encode.
1308
+ vid64 = base64.encodebytes(path.read_bytes())
1309
+
1310
+ vid_len = len(vid64)
1311
+ if vid_len >= embed_limit:
1312
+ _log.warning(
1313
+ "Animation movie is %s bytes, exceeding the limit of %s. "
1314
+ "If you're sure you want a large animation embedded, set "
1315
+ "the animation.embed_limit rc parameter to a larger value "
1316
+ "(in MB).", vid_len, embed_limit)
1317
+ else:
1318
+ self._base64_video = vid64.decode('ascii')
1319
+ self._video_size = 'width="{}" height="{}"'.format(
1320
+ *writer.frame_size)
1321
+
1322
+ # If we exceeded the size, this attribute won't exist
1323
+ if hasattr(self, '_base64_video'):
1324
+ # Default HTML5 options are to autoplay and display video controls
1325
+ options = ['controls', 'autoplay']
1326
+
1327
+ # If we're set to repeat, make it loop
1328
+ if getattr(self, '_repeat', False):
1329
+ options.append('loop')
1330
+
1331
+ return VIDEO_TAG.format(video=self._base64_video,
1332
+ size=self._video_size,
1333
+ options=' '.join(options))
1334
+ else:
1335
+ return 'Video too large to embed.'
1336
+
1337
+ def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
1338
+ """
1339
+ Generate HTML representation of the animation.
1340
+
1341
+ Parameters
1342
+ ----------
1343
+ fps : int, optional
1344
+ Movie frame rate (per second). If not set, the frame rate from
1345
+ the animation's frame interval.
1346
+ embed_frames : bool, optional
1347
+ default_mode : str, optional
1348
+ What to do when the animation ends. Must be one of ``{'loop',
1349
+ 'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
1350
+ parameter is True, otherwise ``'once'``.
1351
+
1352
+ Returns
1353
+ -------
1354
+ str
1355
+ An HTML representation of the animation embedded as a js object as
1356
+ produced with the `.HTMLWriter`.
1357
+ """
1358
+ if fps is None and hasattr(self, '_interval'):
1359
+ # Convert interval in ms to frames per second
1360
+ fps = 1000 / self._interval
1361
+
1362
+ # If we're not given a default mode, choose one base on the value of
1363
+ # the _repeat attribute
1364
+ if default_mode is None:
1365
+ default_mode = 'loop' if getattr(self, '_repeat',
1366
+ False) else 'once'
1367
+
1368
+ if not hasattr(self, "_html_representation"):
1369
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
1370
+ # TemporaryDirectory instead.
1371
+ with TemporaryDirectory() as tmpdir:
1372
+ path = Path(tmpdir, "temp.html")
1373
+ writer = HTMLWriter(fps=fps,
1374
+ embed_frames=embed_frames,
1375
+ default_mode=default_mode)
1376
+ self.save(str(path), writer=writer)
1377
+ self._html_representation = path.read_text()
1378
+
1379
+ return self._html_representation
1380
+
1381
+ def _repr_html_(self):
1382
+ """IPython display hook for rendering."""
1383
+ fmt = mpl.rcParams['animation.html']
1384
+ if fmt == 'html5':
1385
+ return self.to_html5_video()
1386
+ elif fmt == 'jshtml':
1387
+ return self.to_jshtml()
1388
+
1389
+ def pause(self):
1390
+ """Pause the animation."""
1391
+ self.event_source.stop()
1392
+ if self._blit:
1393
+ for artist in self._drawn_artists:
1394
+ artist.set_animated(False)
1395
+
1396
+ def resume(self):
1397
+ """Resume the animation."""
1398
+ self.event_source.start()
1399
+ if self._blit:
1400
+ for artist in self._drawn_artists:
1401
+ artist.set_animated(True)
1402
+
1403
+
1404
+ class TimedAnimation(Animation):
1405
+ """
1406
+ `Animation` subclass for time-based animation.
1407
+
1408
+ A new frame is drawn every *interval* milliseconds.
1409
+
1410
+ .. note::
1411
+
1412
+ You must store the created Animation in a variable that lives as long
1413
+ as the animation should run. Otherwise, the Animation object will be
1414
+ garbage-collected and the animation stops.
1415
+
1416
+ Parameters
1417
+ ----------
1418
+ fig : `~matplotlib.figure.Figure`
1419
+ The figure object used to get needed events, such as draw or resize.
1420
+ interval : int, default: 200
1421
+ Delay between frames in milliseconds.
1422
+ repeat_delay : int, default: 0
1423
+ The delay in milliseconds between consecutive animation runs, if
1424
+ *repeat* is True.
1425
+ repeat : bool, default: True
1426
+ Whether the animation repeats when the sequence of frames is completed.
1427
+ blit : bool, default: False
1428
+ Whether blitting is used to optimize drawing.
1429
+ """
1430
+ def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
1431
+ event_source=None, *args, **kwargs):
1432
+ self._interval = interval
1433
+ # Undocumented support for repeat_delay = None as backcompat.
1434
+ self._repeat_delay = repeat_delay if repeat_delay is not None else 0
1435
+ self._repeat = repeat
1436
+ # If we're not given an event source, create a new timer. This permits
1437
+ # sharing timers between animation objects for syncing animations.
1438
+ if event_source is None:
1439
+ event_source = fig.canvas.new_timer(interval=self._interval)
1440
+ super().__init__(fig, event_source=event_source, *args, **kwargs)
1441
+
1442
+ def _step(self, *args):
1443
+ """Handler for getting events."""
1444
+ # Extends the _step() method for the Animation class. If
1445
+ # Animation._step signals that it reached the end and we want to
1446
+ # repeat, we refresh the frame sequence and return True. If
1447
+ # _repeat_delay is set, change the event_source's interval to our loop
1448
+ # delay and set the callback to one which will then set the interval
1449
+ # back.
1450
+ still_going = super()._step(*args)
1451
+ if not still_going:
1452
+ if self._repeat:
1453
+ # Restart the draw loop
1454
+ self._init_draw()
1455
+ self.frame_seq = self.new_frame_seq()
1456
+ self.event_source.interval = self._repeat_delay
1457
+ return True
1458
+ else:
1459
+ # We are done with the animation. Call pause to remove
1460
+ # animated flags from artists that were using blitting
1461
+ self.pause()
1462
+ if self._blit:
1463
+ # Remove the resize callback if we were blitting
1464
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1465
+ self._fig.canvas.mpl_disconnect(self._close_id)
1466
+ self.event_source = None
1467
+ return False
1468
+
1469
+ self.event_source.interval = self._interval
1470
+ return True
1471
+
1472
+
1473
+ class ArtistAnimation(TimedAnimation):
1474
+ """
1475
+ `TimedAnimation` subclass that creates an animation by using a fixed
1476
+ set of `.Artist` objects.
1477
+
1478
+ Before creating an instance, all plotting should have taken place
1479
+ and the relevant artists saved.
1480
+
1481
+ .. note::
1482
+
1483
+ You must store the created Animation in a variable that lives as long
1484
+ as the animation should run. Otherwise, the Animation object will be
1485
+ garbage-collected and the animation stops.
1486
+
1487
+ Parameters
1488
+ ----------
1489
+ fig : `~matplotlib.figure.Figure`
1490
+ The figure object used to get needed events, such as draw or resize.
1491
+ artists : list
1492
+ Each list entry is a collection of `.Artist` objects that are made
1493
+ visible on the corresponding frame. Other artists are made invisible.
1494
+ interval : int, default: 200
1495
+ Delay between frames in milliseconds.
1496
+ repeat_delay : int, default: 0
1497
+ The delay in milliseconds between consecutive animation runs, if
1498
+ *repeat* is True.
1499
+ repeat : bool, default: True
1500
+ Whether the animation repeats when the sequence of frames is completed.
1501
+ blit : bool, default: False
1502
+ Whether blitting is used to optimize drawing.
1503
+ """
1504
+
1505
+ def __init__(self, fig, artists, *args, **kwargs):
1506
+ # Internal list of artists drawn in the most recent frame.
1507
+ self._drawn_artists = []
1508
+
1509
+ # Use the list of artists as the framedata, which will be iterated
1510
+ # over by the machinery.
1511
+ self._framedata = artists
1512
+ super().__init__(fig, *args, **kwargs)
1513
+
1514
+ def _init_draw(self):
1515
+ super()._init_draw()
1516
+ # Make all the artists involved in *any* frame invisible
1517
+ figs = set()
1518
+ for f in self.new_frame_seq():
1519
+ for artist in f:
1520
+ artist.set_visible(False)
1521
+ artist.set_animated(self._blit)
1522
+ # Assemble a list of unique figures that need flushing
1523
+ if artist.get_figure() not in figs:
1524
+ figs.add(artist.get_figure())
1525
+
1526
+ # Flush the needed figures
1527
+ for fig in figs:
1528
+ fig.canvas.draw_idle()
1529
+
1530
+ def _pre_draw(self, framedata, blit):
1531
+ """Clears artists from the last frame."""
1532
+ if blit:
1533
+ # Let blit handle clearing
1534
+ self._blit_clear(self._drawn_artists)
1535
+ else:
1536
+ # Otherwise, make all the artists from the previous frame invisible
1537
+ for artist in self._drawn_artists:
1538
+ artist.set_visible(False)
1539
+
1540
+ def _draw_frame(self, artists):
1541
+ # Save the artists that were passed in as framedata for the other
1542
+ # steps (esp. blitting) to use.
1543
+ self._drawn_artists = artists
1544
+
1545
+ # Make all the artists from the current frame visible
1546
+ for artist in artists:
1547
+ artist.set_visible(True)
1548
+
1549
+
1550
+ class FuncAnimation(TimedAnimation):
1551
+ """
1552
+ `TimedAnimation` subclass that makes an animation by repeatedly calling
1553
+ a function *func*.
1554
+
1555
+ .. note::
1556
+
1557
+ You must store the created Animation in a variable that lives as long
1558
+ as the animation should run. Otherwise, the Animation object will be
1559
+ garbage-collected and the animation stops.
1560
+
1561
+ Parameters
1562
+ ----------
1563
+ fig : `~matplotlib.figure.Figure`
1564
+ The figure object used to get needed events, such as draw or resize.
1565
+
1566
+ func : callable
1567
+ The function to call at each frame. The first argument will
1568
+ be the next value in *frames*. Any additional positional
1569
+ arguments can be supplied using `functools.partial` or via the *fargs*
1570
+ parameter.
1571
+
1572
+ The required signature is::
1573
+
1574
+ def func(frame, *fargs) -> iterable_of_artists
1575
+
1576
+ It is often more convenient to provide the arguments using
1577
+ `functools.partial`. In this way it is also possible to pass keyword
1578
+ arguments. To pass a function with both positional and keyword
1579
+ arguments, set all arguments as keyword arguments, just leaving the
1580
+ *frame* argument unset::
1581
+
1582
+ def func(frame, art, *, y=None):
1583
+ ...
1584
+
1585
+ ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
1586
+
1587
+ If ``blit == True``, *func* must return an iterable of all artists
1588
+ that were modified or created. This information is used by the blitting
1589
+ algorithm to determine which parts of the figure have to be updated.
1590
+ The return value is unused if ``blit == False`` and may be omitted in
1591
+ that case.
1592
+
1593
+ frames : iterable, int, generator function, or None, optional
1594
+ Source of data to pass *func* and each frame of the animation
1595
+
1596
+ - If an iterable, then simply use the values provided. If the
1597
+ iterable has a length, it will override the *save_count* kwarg.
1598
+
1599
+ - If an integer, then equivalent to passing ``range(frames)``
1600
+
1601
+ - If a generator function, then must have the signature::
1602
+
1603
+ def gen_function() -> obj
1604
+
1605
+ - If *None*, then equivalent to passing ``itertools.count``.
1606
+
1607
+ In all of these cases, the values in *frames* is simply passed through
1608
+ to the user-supplied *func* and thus can be of any type.
1609
+
1610
+ init_func : callable, optional
1611
+ A function used to draw a clear frame. If not given, the results of
1612
+ drawing from the first item in the frames sequence will be used. This
1613
+ function will be called once before the first frame.
1614
+
1615
+ The required signature is::
1616
+
1617
+ def init_func() -> iterable_of_artists
1618
+
1619
+ If ``blit == True``, *init_func* must return an iterable of artists
1620
+ to be re-drawn. This information is used by the blitting algorithm to
1621
+ determine which parts of the figure have to be updated. The return
1622
+ value is unused if ``blit == False`` and may be omitted in that case.
1623
+
1624
+ fargs : tuple or None, optional
1625
+ Additional arguments to pass to each call to *func*. Note: the use of
1626
+ `functools.partial` is preferred over *fargs*. See *func* for details.
1627
+
1628
+ save_count : int, optional
1629
+ Fallback for the number of values from *frames* to cache. This is
1630
+ only used if the number of frames cannot be inferred from *frames*,
1631
+ i.e. when it's an iterator without length or a generator.
1632
+
1633
+ interval : int, default: 200
1634
+ Delay between frames in milliseconds.
1635
+
1636
+ repeat_delay : int, default: 0
1637
+ The delay in milliseconds between consecutive animation runs, if
1638
+ *repeat* is True.
1639
+
1640
+ repeat : bool, default: True
1641
+ Whether the animation repeats when the sequence of frames is completed.
1642
+
1643
+ blit : bool, default: False
1644
+ Whether blitting is used to optimize drawing. Note: when using
1645
+ blitting, any animated artists will be drawn according to their zorder;
1646
+ however, they will be drawn on top of any previous artists, regardless
1647
+ of their zorder.
1648
+
1649
+ cache_frame_data : bool, default: True
1650
+ Whether frame data is cached. Disabling cache might be helpful when
1651
+ frames contain large objects.
1652
+ """
1653
+ def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
1654
+ save_count=None, *, cache_frame_data=True, **kwargs):
1655
+ if fargs:
1656
+ self._args = fargs
1657
+ else:
1658
+ self._args = ()
1659
+ self._func = func
1660
+ self._init_func = init_func
1661
+
1662
+ # Amount of framedata to keep around for saving movies. This is only
1663
+ # used if we don't know how many frames there will be: in the case
1664
+ # of no generator or in the case of a callable.
1665
+ self._save_count = save_count
1666
+ # Set up a function that creates a new iterable when needed. If nothing
1667
+ # is passed in for frames, just use itertools.count, which will just
1668
+ # keep counting from 0. A callable passed in for frames is assumed to
1669
+ # be a generator. An iterable will be used as is, and anything else
1670
+ # will be treated as a number of frames.
1671
+ if frames is None:
1672
+ self._iter_gen = itertools.count
1673
+ elif callable(frames):
1674
+ self._iter_gen = frames
1675
+ elif np.iterable(frames):
1676
+ if kwargs.get('repeat', True):
1677
+ self._tee_from = frames
1678
+ def iter_frames(frames=frames):
1679
+ this, self._tee_from = itertools.tee(self._tee_from, 2)
1680
+ yield from this
1681
+ self._iter_gen = iter_frames
1682
+ else:
1683
+ self._iter_gen = lambda: iter(frames)
1684
+ if hasattr(frames, '__len__'):
1685
+ self._save_count = len(frames)
1686
+ if save_count is not None:
1687
+ _api.warn_external(
1688
+ f"You passed in an explicit {save_count=} "
1689
+ "which is being ignored in favor of "
1690
+ f"{len(frames)=}."
1691
+ )
1692
+ else:
1693
+ self._iter_gen = lambda: iter(range(frames))
1694
+ self._save_count = frames
1695
+ if save_count is not None:
1696
+ _api.warn_external(
1697
+ f"You passed in an explicit {save_count=} which is being "
1698
+ f"ignored in favor of {frames=}."
1699
+ )
1700
+ if self._save_count is None and cache_frame_data:
1701
+ _api.warn_external(
1702
+ f"{frames=!r} which we can infer the length of, "
1703
+ "did not pass an explicit *save_count* "
1704
+ f"and passed {cache_frame_data=}. To avoid a possibly "
1705
+ "unbounded cache, frame data caching has been disabled. "
1706
+ "To suppress this warning either pass "
1707
+ "`cache_frame_data=False` or `save_count=MAX_FRAMES`."
1708
+ )
1709
+ cache_frame_data = False
1710
+
1711
+ self._cache_frame_data = cache_frame_data
1712
+
1713
+ # Needs to be initialized so the draw functions work without checking
1714
+ self._save_seq = []
1715
+
1716
+ super().__init__(fig, **kwargs)
1717
+
1718
+ # Need to reset the saved seq, since right now it will contain data
1719
+ # for a single frame from init, which is not what we want.
1720
+ self._save_seq = []
1721
+
1722
+ def new_frame_seq(self):
1723
+ # Use the generating function to generate a new frame sequence
1724
+ return self._iter_gen()
1725
+
1726
+ def new_saved_frame_seq(self):
1727
+ # Generate an iterator for the sequence of saved data. If there are
1728
+ # no saved frames, generate a new frame sequence and take the first
1729
+ # save_count entries in it.
1730
+ if self._save_seq:
1731
+ # While iterating we are going to update _save_seq
1732
+ # so make a copy to safely iterate over
1733
+ self._old_saved_seq = list(self._save_seq)
1734
+ return iter(self._old_saved_seq)
1735
+ else:
1736
+ if self._save_count is None:
1737
+ frame_seq = self.new_frame_seq()
1738
+
1739
+ def gen():
1740
+ try:
1741
+ while True:
1742
+ yield next(frame_seq)
1743
+ except StopIteration:
1744
+ pass
1745
+ return gen()
1746
+ else:
1747
+ return itertools.islice(self.new_frame_seq(), self._save_count)
1748
+
1749
+ def _init_draw(self):
1750
+ super()._init_draw()
1751
+ # Initialize the drawing either using the given init_func or by
1752
+ # calling the draw function with the first item of the frame sequence.
1753
+ # For blitting, the init_func should return a sequence of modified
1754
+ # artists.
1755
+ if self._init_func is None:
1756
+ try:
1757
+ frame_data = next(self.new_frame_seq())
1758
+ except StopIteration:
1759
+ # we can't start the iteration, it may have already been
1760
+ # exhausted by a previous save or just be 0 length.
1761
+ # warn and bail.
1762
+ warnings.warn(
1763
+ "Can not start iterating the frames for the initial draw. "
1764
+ "This can be caused by passing in a 0 length sequence "
1765
+ "for *frames*.\n\n"
1766
+ "If you passed *frames* as a generator "
1767
+ "it may be exhausted due to a previous display or save."
1768
+ )
1769
+ return
1770
+ self._draw_frame(frame_data)
1771
+ else:
1772
+ self._drawn_artists = self._init_func()
1773
+ if self._blit:
1774
+ if self._drawn_artists is None:
1775
+ raise RuntimeError('The init_func must return a '
1776
+ 'sequence of Artist objects.')
1777
+ for a in self._drawn_artists:
1778
+ a.set_animated(self._blit)
1779
+ self._save_seq = []
1780
+
1781
+ def _draw_frame(self, framedata):
1782
+ if self._cache_frame_data:
1783
+ # Save the data for potential saving of movies.
1784
+ self._save_seq.append(framedata)
1785
+ self._save_seq = self._save_seq[-self._save_count:]
1786
+
1787
+ # Call the func with framedata and args. If blitting is desired,
1788
+ # func needs to return a sequence of any artists that were modified.
1789
+ self._drawn_artists = self._func(framedata, *self._args)
1790
+
1791
+ if self._blit:
1792
+
1793
+ err = RuntimeError('The animation function must return a sequence '
1794
+ 'of Artist objects.')
1795
+ try:
1796
+ # check if a sequence
1797
+ iter(self._drawn_artists)
1798
+ except TypeError:
1799
+ raise err from None
1800
+
1801
+ # check each item if it's artist
1802
+ for i in self._drawn_artists:
1803
+ if not isinstance(i, mpl.artist.Artist):
1804
+ raise err
1805
+
1806
+ self._drawn_artists = sorted(self._drawn_artists,
1807
+ key=lambda x: x.get_zorder())
1808
+
1809
+ for a in self._drawn_artists:
1810
+ a.set_animated(self._blit)
1811
+
1812
+
1813
+ def _validate_grabframe_kwargs(savefig_kwargs):
1814
+ if mpl.rcParams['savefig.bbox'] == 'tight':
1815
+ raise ValueError(
1816
+ f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "
1817
+ "may cause frame size to vary, which is inappropriate for animation."
1818
+ )
1819
+ for k in ('dpi', 'bbox_inches', 'format'):
1820
+ if k in savefig_kwargs:
1821
+ raise TypeError(
1822
+ f"grab_frame got an unexpected keyword argument {k!r}"
1823
+ )
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/animation.pyi ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from collections.abc import Callable, Collection, Iterable, Sequence, Generator
3
+ import contextlib
4
+ from pathlib import Path
5
+ from matplotlib.artist import Artist
6
+ from matplotlib.backend_bases import TimerBase
7
+ from matplotlib.figure import Figure
8
+
9
+ from typing import Any
10
+
11
+ subprocess_creation_flags: int
12
+
13
+ def adjusted_figsize(w: float, h: float, dpi: float, n: int) -> tuple[float, float]: ...
14
+
15
+ class MovieWriterRegistry:
16
+ def __init__(self) -> None: ...
17
+ def register(
18
+ self, name: str
19
+ ) -> Callable[[type[AbstractMovieWriter]], type[AbstractMovieWriter]]: ...
20
+ def is_available(self, name: str) -> bool: ...
21
+ def __iter__(self) -> Generator[str, None, None]: ...
22
+ def list(self) -> list[str]: ...
23
+ def __getitem__(self, name: str) -> type[AbstractMovieWriter]: ...
24
+
25
+ writers: MovieWriterRegistry
26
+
27
+ class AbstractMovieWriter(abc.ABC, metaclass=abc.ABCMeta):
28
+ fps: int
29
+ metadata: dict[str, str]
30
+ codec: str
31
+ bitrate: int
32
+ def __init__(
33
+ self,
34
+ fps: int = ...,
35
+ metadata: dict[str, str] | None = ...,
36
+ codec: str | None = ...,
37
+ bitrate: int | None = ...,
38
+ ) -> None: ...
39
+ outfile: str | Path
40
+ fig: Figure
41
+ dpi: float
42
+
43
+ @abc.abstractmethod
44
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
45
+ @property
46
+ def frame_size(self) -> tuple[int, int]: ...
47
+ @abc.abstractmethod
48
+ def grab_frame(self, **savefig_kwargs) -> None: ...
49
+ @abc.abstractmethod
50
+ def finish(self) -> None: ...
51
+ @contextlib.contextmanager
52
+ def saving(
53
+ self, fig: Figure, outfile: str | Path, dpi: float | None, *args, **kwargs
54
+ ) -> Generator[AbstractMovieWriter, None, None]: ...
55
+
56
+ class MovieWriter(AbstractMovieWriter):
57
+ supported_formats: list[str]
58
+ frame_format: str
59
+ extra_args: list[str] | None
60
+ def __init__(
61
+ self,
62
+ fps: int = ...,
63
+ codec: str | None = ...,
64
+ bitrate: int | None = ...,
65
+ extra_args: list[str] | None = ...,
66
+ metadata: dict[str, str] | None = ...,
67
+ ) -> None: ...
68
+ def setup(self, fig: Figure, outfile: str | Path, dpi: float | None = ...) -> None: ...
69
+ def grab_frame(self, **savefig_kwargs) -> None: ...
70
+ def finish(self) -> None: ...
71
+ @classmethod
72
+ def bin_path(cls) -> str: ...
73
+ @classmethod
74
+ def isAvailable(cls) -> bool: ...
75
+
76
+ class FileMovieWriter(MovieWriter):
77
+ fig: Figure
78
+ outfile: str | Path
79
+ dpi: float
80
+ temp_prefix: str
81
+ fname_format_str: str
82
+ def setup(
83
+ self,
84
+ fig: Figure,
85
+ outfile: str | Path,
86
+ dpi: float | None = ...,
87
+ frame_prefix: str | Path | None = ...,
88
+ ) -> None: ...
89
+ def __del__(self) -> None: ...
90
+ @property
91
+ def frame_format(self) -> str: ...
92
+ @frame_format.setter
93
+ def frame_format(self, frame_format: str) -> None: ...
94
+
95
+ class PillowWriter(AbstractMovieWriter):
96
+ @classmethod
97
+ def isAvailable(cls) -> bool: ...
98
+ def setup(
99
+ self, fig: Figure, outfile: str | Path, dpi: float | None = ...
100
+ ) -> None: ...
101
+ def grab_frame(self, **savefig_kwargs) -> None: ...
102
+ def finish(self) -> None: ...
103
+
104
+ class FFMpegBase:
105
+ codec: str
106
+ @property
107
+ def output_args(self) -> list[str]: ...
108
+
109
+ class FFMpegWriter(FFMpegBase, MovieWriter): ...
110
+
111
+ class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
112
+ supported_formats: list[str]
113
+
114
+ class ImageMagickBase:
115
+ @classmethod
116
+ def bin_path(cls) -> str: ...
117
+ @classmethod
118
+ def isAvailable(cls) -> bool: ...
119
+
120
+ class ImageMagickWriter(ImageMagickBase, MovieWriter):
121
+ input_names: str
122
+
123
+ class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
124
+ supported_formats: list[str]
125
+ @property
126
+ def input_names(self) -> str: ...
127
+
128
+ class HTMLWriter(FileMovieWriter):
129
+ supported_formats: list[str]
130
+ @classmethod
131
+ def isAvailable(cls) -> bool: ...
132
+ embed_frames: bool
133
+ default_mode: str
134
+ def __init__(
135
+ self,
136
+ fps: int = ...,
137
+ codec: str | None = ...,
138
+ bitrate: int | None = ...,
139
+ extra_args: list[str] | None = ...,
140
+ metadata: dict[str, str] | None = ...,
141
+ embed_frames: bool = ...,
142
+ default_mode: str = ...,
143
+ embed_limit: float | None = ...,
144
+ ) -> None: ...
145
+ def setup(
146
+ self,
147
+ fig: Figure,
148
+ outfile: str | Path,
149
+ dpi: float | None = ...,
150
+ frame_dir: str | Path | None = ...,
151
+ ) -> None: ...
152
+ def grab_frame(self, **savefig_kwargs): ...
153
+ def finish(self) -> None: ...
154
+
155
+ class Animation:
156
+ frame_seq: Iterable[Artist]
157
+ event_source: Any
158
+ def __init__(
159
+ self, fig: Figure, event_source: Any | None = ..., blit: bool = ...
160
+ ) -> None: ...
161
+ def __del__(self) -> None: ...
162
+ def save(
163
+ self,
164
+ filename: str | Path,
165
+ writer: AbstractMovieWriter | str | None = ...,
166
+ fps: int | None = ...,
167
+ dpi: float | None = ...,
168
+ codec: str | None = ...,
169
+ bitrate: int | None = ...,
170
+ extra_args: list[str] | None = ...,
171
+ metadata: dict[str, str] | None = ...,
172
+ extra_anim: list[Animation] | None = ...,
173
+ savefig_kwargs: dict[str, Any] | None = ...,
174
+ *,
175
+ progress_callback: Callable[[int, int], Any] | None = ...
176
+ ) -> None: ...
177
+ def new_frame_seq(self) -> Iterable[Artist]: ...
178
+ def new_saved_frame_seq(self) -> Iterable[Artist]: ...
179
+ def to_html5_video(self, embed_limit: float | None = ...) -> str: ...
180
+ def to_jshtml(
181
+ self,
182
+ fps: int | None = ...,
183
+ embed_frames: bool = ...,
184
+ default_mode: str | None = ...,
185
+ ) -> str: ...
186
+ def _repr_html_(self) -> str: ...
187
+ def pause(self) -> None: ...
188
+ def resume(self) -> None: ...
189
+
190
+ class TimedAnimation(Animation):
191
+ def __init__(
192
+ self,
193
+ fig: Figure,
194
+ interval: int = ...,
195
+ repeat_delay: int = ...,
196
+ repeat: bool = ...,
197
+ event_source: TimerBase | None = ...,
198
+ *args,
199
+ **kwargs
200
+ ) -> None: ...
201
+
202
+ class ArtistAnimation(TimedAnimation):
203
+ def __init__(self, fig: Figure, artists: Sequence[Collection[Artist]], *args, **kwargs) -> None: ...
204
+
205
+ class FuncAnimation(TimedAnimation):
206
+ def __init__(
207
+ self,
208
+ fig: Figure,
209
+ func: Callable[..., Iterable[Artist]],
210
+ frames: Iterable | int | Callable[[], Generator] | None = ...,
211
+ init_func: Callable[[], Iterable[Artist]] | None = ...,
212
+ fargs: tuple[Any, ...] | None = ...,
213
+ save_count: int | None = ...,
214
+ *,
215
+ cache_frame_data: bool = ...,
216
+ **kwargs
217
+ ) -> None: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/artist.py ADDED
@@ -0,0 +1,1855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import namedtuple
2
+ import contextlib
3
+ from functools import cache, reduce, wraps
4
+ import inspect
5
+ from inspect import Signature, Parameter
6
+ import logging
7
+ from numbers import Number, Real
8
+ import operator
9
+ import re
10
+ import warnings
11
+
12
+ import numpy as np
13
+
14
+ import matplotlib as mpl
15
+ from . import _api, cbook
16
+ from .path import Path
17
+ from .transforms import (BboxBase, Bbox, IdentityTransform, Transform, TransformedBbox,
18
+ TransformedPatchPath, TransformedPath)
19
+
20
+ _log = logging.getLogger(__name__)
21
+
22
+
23
+ def _prevent_rasterization(draw):
24
+ # We assume that by default artists are not allowed to rasterize (unless
25
+ # its draw method is explicitly decorated). If it is being drawn after a
26
+ # rasterized artist and it has reached a raster_depth of 0, we stop
27
+ # rasterization so that it does not affect the behavior of normal artist
28
+ # (e.g., change in dpi).
29
+
30
+ @wraps(draw)
31
+ def draw_wrapper(artist, renderer, *args, **kwargs):
32
+ if renderer._raster_depth == 0 and renderer._rasterizing:
33
+ # Only stop when we are not in a rasterized parent
34
+ # and something has been rasterized since last stop.
35
+ renderer.stop_rasterizing()
36
+ renderer._rasterizing = False
37
+
38
+ return draw(artist, renderer, *args, **kwargs)
39
+
40
+ draw_wrapper._supports_rasterization = False
41
+ return draw_wrapper
42
+
43
+
44
+ def allow_rasterization(draw):
45
+ """
46
+ Decorator for Artist.draw method. Provides routines
47
+ that run before and after the draw call. The before and after functions
48
+ are useful for changing artist-dependent renderer attributes or making
49
+ other setup function calls, such as starting and flushing a mixed-mode
50
+ renderer.
51
+ """
52
+
53
+ @wraps(draw)
54
+ def draw_wrapper(artist, renderer):
55
+ try:
56
+ if artist.get_rasterized():
57
+ if renderer._raster_depth == 0 and not renderer._rasterizing:
58
+ renderer.start_rasterizing()
59
+ renderer._rasterizing = True
60
+ renderer._raster_depth += 1
61
+ else:
62
+ if renderer._raster_depth == 0 and renderer._rasterizing:
63
+ # Only stop when we are not in a rasterized parent
64
+ # and something has be rasterized since last stop
65
+ renderer.stop_rasterizing()
66
+ renderer._rasterizing = False
67
+
68
+ if artist.get_agg_filter() is not None:
69
+ renderer.start_filter()
70
+
71
+ return draw(artist, renderer)
72
+ finally:
73
+ if artist.get_agg_filter() is not None:
74
+ renderer.stop_filter(artist.get_agg_filter())
75
+ if artist.get_rasterized():
76
+ renderer._raster_depth -= 1
77
+ if (renderer._rasterizing and (fig := artist.get_figure(root=True)) and
78
+ fig.suppressComposite):
79
+ # restart rasterizing to prevent merging
80
+ renderer.stop_rasterizing()
81
+ renderer.start_rasterizing()
82
+
83
+ draw_wrapper._supports_rasterization = True
84
+ return draw_wrapper
85
+
86
+
87
+ def _finalize_rasterization(draw):
88
+ """
89
+ Decorator for Artist.draw method. Needed on the outermost artist, i.e.
90
+ Figure, to finish up if the render is still in rasterized mode.
91
+ """
92
+ @wraps(draw)
93
+ def draw_wrapper(artist, renderer, *args, **kwargs):
94
+ result = draw(artist, renderer, *args, **kwargs)
95
+ if renderer._rasterizing:
96
+ renderer.stop_rasterizing()
97
+ renderer._rasterizing = False
98
+ return result
99
+ return draw_wrapper
100
+
101
+
102
+ def _stale_axes_callback(self, val):
103
+ if self.axes:
104
+ self.axes.stale = val
105
+
106
+
107
+ _XYPair = namedtuple("_XYPair", "x y")
108
+
109
+
110
+ class _Unset:
111
+ def __repr__(self):
112
+ return "<UNSET>"
113
+ _UNSET = _Unset()
114
+
115
+
116
+ class Artist:
117
+ """
118
+ Abstract base class for objects that render into a FigureCanvas.
119
+
120
+ Typically, all visible elements in a figure are subclasses of Artist.
121
+ """
122
+
123
+ zorder = 0
124
+
125
+ def __init_subclass__(cls):
126
+
127
+ # Decorate draw() method so that all artists are able to stop
128
+ # rastrization when necessary. If the artist's draw method is already
129
+ # decorated (has a `_supports_rasterization` attribute), it won't be
130
+ # decorated.
131
+
132
+ if not hasattr(cls.draw, "_supports_rasterization"):
133
+ cls.draw = _prevent_rasterization(cls.draw)
134
+
135
+ # Inject custom set() methods into the subclass with signature and
136
+ # docstring based on the subclasses' properties.
137
+
138
+ if not hasattr(cls.set, '_autogenerated_signature'):
139
+ # Don't overwrite cls.set if the subclass or one of its parents
140
+ # has defined a set method set itself.
141
+ # If there was no explicit definition, cls.set is inherited from
142
+ # the hierarchy of auto-generated set methods, which hold the
143
+ # flag _autogenerated_signature.
144
+ return
145
+
146
+ cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)
147
+ cls.set.__name__ = "set"
148
+ cls.set.__qualname__ = f"{cls.__qualname__}.set"
149
+ cls._update_set_signature_and_docstring()
150
+
151
+ _PROPERTIES_EXCLUDED_FROM_SET = [
152
+ 'navigate_mode', # not a user-facing function
153
+ 'figure', # changing the figure is such a profound operation
154
+ # that we don't want this in set()
155
+ '3d_properties', # cannot be used as a keyword due to leading digit
156
+ ]
157
+
158
+ @classmethod
159
+ def _update_set_signature_and_docstring(cls):
160
+ """
161
+ Update the signature of the set function to list all properties
162
+ as keyword arguments.
163
+
164
+ Property aliases are not listed in the signature for brevity, but
165
+ are still accepted as keyword arguments.
166
+ """
167
+ cls.set.__signature__ = Signature(
168
+ [Parameter("self", Parameter.POSITIONAL_OR_KEYWORD),
169
+ *[Parameter(prop, Parameter.KEYWORD_ONLY, default=_UNSET)
170
+ for prop in ArtistInspector(cls).get_setters()
171
+ if prop not in Artist._PROPERTIES_EXCLUDED_FROM_SET]])
172
+ cls.set._autogenerated_signature = True
173
+
174
+ cls.set.__doc__ = (
175
+ "Set multiple properties at once.\n\n"
176
+ "Supported properties are\n\n"
177
+ + kwdoc(cls))
178
+
179
+ def __init__(self):
180
+ self._stale = True
181
+ self.stale_callback = None
182
+ self._axes = None
183
+ self._parent_figure = None
184
+
185
+ self._transform = None
186
+ self._transformSet = False
187
+ self._visible = True
188
+ self._animated = False
189
+ self._alpha = None
190
+ self.clipbox = None
191
+ self._clippath = None
192
+ self._clipon = True
193
+ self._label = ''
194
+ self._picker = None
195
+ self._rasterized = False
196
+ self._agg_filter = None
197
+ # Normally, artist classes need to be queried for mouseover info if and
198
+ # only if they override get_cursor_data.
199
+ self._mouseover = type(self).get_cursor_data != Artist.get_cursor_data
200
+ self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
201
+ try:
202
+ self.axes = None
203
+ except AttributeError:
204
+ # Handle self.axes as a read-only property, as in Figure.
205
+ pass
206
+ self._remove_method = None
207
+ self._url = None
208
+ self._gid = None
209
+ self._snap = None
210
+ self._sketch = mpl.rcParams['path.sketch']
211
+ self._path_effects = mpl.rcParams['path.effects']
212
+ self._sticky_edges = _XYPair([], [])
213
+ self._in_layout = True
214
+
215
+ def __getstate__(self):
216
+ d = self.__dict__.copy()
217
+ d['stale_callback'] = None
218
+ return d
219
+
220
+ def remove(self):
221
+ """
222
+ Remove the artist from the figure if possible.
223
+
224
+ The effect will not be visible until the figure is redrawn, e.g.,
225
+ with `.FigureCanvasBase.draw_idle`. Call `~.axes.Axes.relim` to
226
+ update the Axes limits if desired.
227
+
228
+ Note: `~.axes.Axes.relim` will not see collections even if the
229
+ collection was added to the Axes with *autolim* = True.
230
+
231
+ Note: there is no support for removing the artist's legend entry.
232
+ """
233
+
234
+ # There is no method to set the callback. Instead, the parent should
235
+ # set the _remove_method attribute directly. This would be a
236
+ # protected attribute if Python supported that sort of thing. The
237
+ # callback has one parameter, which is the child to be removed.
238
+ if self._remove_method is not None:
239
+ self._remove_method(self)
240
+ # clear stale callback
241
+ self.stale_callback = None
242
+ _ax_flag = False
243
+ if hasattr(self, 'axes') and self.axes:
244
+ # remove from the mouse hit list
245
+ self.axes._mouseover_set.discard(self)
246
+ self.axes.stale = True
247
+ self.axes = None # decouple the artist from the Axes
248
+ _ax_flag = True
249
+
250
+ if (fig := self.get_figure(root=False)) is not None:
251
+ if not _ax_flag:
252
+ fig.stale = True
253
+ self._parent_figure = None
254
+
255
+ else:
256
+ raise NotImplementedError('cannot remove artist')
257
+ # TODO: the fix for the collections relim problem is to move the
258
+ # limits calculation into the artist itself, including the property of
259
+ # whether or not the artist should affect the limits. Then there will
260
+ # be no distinction between axes.add_line, axes.add_patch, etc.
261
+ # TODO: add legend support
262
+
263
+ def have_units(self):
264
+ """Return whether units are set on any axis."""
265
+ ax = self.axes
266
+ return ax and any(axis.have_units() for axis in ax._axis_map.values())
267
+
268
+ def convert_xunits(self, x):
269
+ """
270
+ Convert *x* using the unit type of the xaxis.
271
+
272
+ If the artist is not contained in an Axes or if the xaxis does not
273
+ have units, *x* itself is returned.
274
+ """
275
+ ax = getattr(self, 'axes', None)
276
+ if ax is None or ax.xaxis is None:
277
+ return x
278
+ return ax.xaxis.convert_units(x)
279
+
280
+ def convert_yunits(self, y):
281
+ """
282
+ Convert *y* using the unit type of the yaxis.
283
+
284
+ If the artist is not contained in an Axes or if the yaxis does not
285
+ have units, *y* itself is returned.
286
+ """
287
+ ax = getattr(self, 'axes', None)
288
+ if ax is None or ax.yaxis is None:
289
+ return y
290
+ return ax.yaxis.convert_units(y)
291
+
292
+ @property
293
+ def axes(self):
294
+ """The `~.axes.Axes` instance the artist resides in, or *None*."""
295
+ return self._axes
296
+
297
+ @axes.setter
298
+ def axes(self, new_axes):
299
+ if (new_axes is not None and self._axes is not None
300
+ and new_axes != self._axes):
301
+ raise ValueError("Can not reset the Axes. You are probably trying to reuse "
302
+ "an artist in more than one Axes which is not supported")
303
+ self._axes = new_axes
304
+ if new_axes is not None and new_axes is not self:
305
+ self.stale_callback = _stale_axes_callback
306
+
307
+ @property
308
+ def stale(self):
309
+ """
310
+ Whether the artist is 'stale' and needs to be re-drawn for the output
311
+ to match the internal state of the artist.
312
+ """
313
+ return self._stale
314
+
315
+ @stale.setter
316
+ def stale(self, val):
317
+ self._stale = val
318
+
319
+ # if the artist is animated it does not take normal part in the
320
+ # draw stack and is not expected to be drawn as part of the normal
321
+ # draw loop (when not saving) so do not propagate this change
322
+ if self._animated:
323
+ return
324
+
325
+ if val and self.stale_callback is not None:
326
+ self.stale_callback(self, val)
327
+
328
+ def get_window_extent(self, renderer=None):
329
+ """
330
+ Get the artist's bounding box in display space.
331
+
332
+ The bounding box' width and height are nonnegative.
333
+
334
+ Subclasses should override for inclusion in the bounding box
335
+ "tight" calculation. Default is to return an empty bounding
336
+ box at 0, 0.
337
+
338
+ Be careful when using this function, the results will not update
339
+ if the artist window extent of the artist changes. The extent
340
+ can change due to any changes in the transform stack, such as
341
+ changing the Axes limits, the figure size, or the canvas used
342
+ (as is done when saving a figure). This can lead to unexpected
343
+ behavior where interactive figures will look fine on the screen,
344
+ but will save incorrectly.
345
+ """
346
+ return Bbox([[0, 0], [0, 0]])
347
+
348
+ def get_tightbbox(self, renderer=None):
349
+ """
350
+ Like `.Artist.get_window_extent`, but includes any clipping.
351
+
352
+ Parameters
353
+ ----------
354
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional
355
+ renderer that will be used to draw the figures (i.e.
356
+ ``fig.canvas.get_renderer()``)
357
+
358
+ Returns
359
+ -------
360
+ `.Bbox` or None
361
+ The enclosing bounding box (in figure pixel coordinates).
362
+ Returns None if clipping results in no intersection.
363
+ """
364
+ bbox = self.get_window_extent(renderer)
365
+ if self.get_clip_on():
366
+ clip_box = self.get_clip_box()
367
+ if clip_box is not None:
368
+ bbox = Bbox.intersection(bbox, clip_box)
369
+ clip_path = self.get_clip_path()
370
+ if clip_path is not None and bbox is not None:
371
+ clip_path = clip_path.get_fully_transformed_path()
372
+ bbox = Bbox.intersection(bbox, clip_path.get_extents())
373
+ return bbox
374
+
375
+ def add_callback(self, func):
376
+ """
377
+ Add a callback function that will be called whenever one of the
378
+ `.Artist`'s properties changes.
379
+
380
+ Parameters
381
+ ----------
382
+ func : callable
383
+ The callback function. It must have the signature::
384
+
385
+ def func(artist: Artist) -> Any
386
+
387
+ where *artist* is the calling `.Artist`. Return values may exist
388
+ but are ignored.
389
+
390
+ Returns
391
+ -------
392
+ int
393
+ The observer id associated with the callback. This id can be
394
+ used for removing the callback with `.remove_callback` later.
395
+
396
+ See Also
397
+ --------
398
+ remove_callback
399
+ """
400
+ # Wrapping func in a lambda ensures it can be connected multiple times
401
+ # and never gets weakref-gc'ed.
402
+ return self._callbacks.connect("pchanged", lambda: func(self))
403
+
404
+ def remove_callback(self, oid):
405
+ """
406
+ Remove a callback based on its observer id.
407
+
408
+ See Also
409
+ --------
410
+ add_callback
411
+ """
412
+ self._callbacks.disconnect(oid)
413
+
414
+ def pchanged(self):
415
+ """
416
+ Call all of the registered callbacks.
417
+
418
+ This function is triggered internally when a property is changed.
419
+
420
+ See Also
421
+ --------
422
+ add_callback
423
+ remove_callback
424
+ """
425
+ self._callbacks.process("pchanged")
426
+
427
+ def is_transform_set(self):
428
+ """
429
+ Return whether the Artist has an explicitly set transform.
430
+
431
+ This is *True* after `.set_transform` has been called.
432
+ """
433
+ return self._transformSet
434
+
435
+ def set_transform(self, t):
436
+ """
437
+ Set the artist transform.
438
+
439
+ Parameters
440
+ ----------
441
+ t : `~matplotlib.transforms.Transform`
442
+ """
443
+ self._transform = t
444
+ self._transformSet = True
445
+ self.pchanged()
446
+ self.stale = True
447
+
448
+ def get_transform(self):
449
+ """Return the `.Transform` instance used by this artist."""
450
+ if self._transform is None:
451
+ self._transform = IdentityTransform()
452
+ elif (not isinstance(self._transform, Transform)
453
+ and hasattr(self._transform, '_as_mpl_transform')):
454
+ self._transform = self._transform._as_mpl_transform(self.axes)
455
+ return self._transform
456
+
457
+ def get_children(self):
458
+ r"""Return a list of the child `.Artist`\s of this `.Artist`."""
459
+ return []
460
+
461
+ def _different_canvas(self, event):
462
+ """
463
+ Check whether an *event* occurred on a canvas other that this artist's canvas.
464
+
465
+ If this method returns True, the event definitely occurred on a different
466
+ canvas; if it returns False, either it occurred on the same canvas, or we may
467
+ not have enough information to know.
468
+
469
+ Subclasses should start their definition of `contains` as follows::
470
+
471
+ if self._different_canvas(mouseevent):
472
+ return False, {}
473
+ # subclass-specific implementation follows
474
+ """
475
+ return (getattr(event, "canvas", None) is not None
476
+ and (fig := self.get_figure(root=True)) is not None
477
+ and event.canvas is not fig.canvas)
478
+
479
+ def contains(self, mouseevent):
480
+ """
481
+ Test whether the artist contains the mouse event.
482
+
483
+ Parameters
484
+ ----------
485
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
486
+
487
+ Returns
488
+ -------
489
+ contains : bool
490
+ Whether any values are within the radius.
491
+ details : dict
492
+ An artist-specific dictionary of details of the event context,
493
+ such as which points are contained in the pick radius. See the
494
+ individual Artist subclasses for details.
495
+ """
496
+ _log.warning("%r needs 'contains' method", self.__class__.__name__)
497
+ return False, {}
498
+
499
+ def pickable(self):
500
+ """
501
+ Return whether the artist is pickable.
502
+
503
+ See Also
504
+ --------
505
+ .Artist.set_picker, .Artist.get_picker, .Artist.pick
506
+ """
507
+ return self.get_figure(root=False) is not None and self._picker is not None
508
+
509
+ def pick(self, mouseevent):
510
+ """
511
+ Process a pick event.
512
+
513
+ Each child artist will fire a pick event if *mouseevent* is over
514
+ the artist and the artist has picker set.
515
+
516
+ See Also
517
+ --------
518
+ .Artist.set_picker, .Artist.get_picker, .Artist.pickable
519
+ """
520
+ from .backend_bases import PickEvent # Circular import.
521
+ # Pick self
522
+ if self.pickable():
523
+ picker = self.get_picker()
524
+ if callable(picker):
525
+ inside, prop = picker(self, mouseevent)
526
+ else:
527
+ inside, prop = self.contains(mouseevent)
528
+ if inside:
529
+ PickEvent("pick_event", self.get_figure(root=True).canvas,
530
+ mouseevent, self, **prop)._process()
531
+
532
+ # Pick children
533
+ for a in self.get_children():
534
+ # make sure the event happened in the same Axes
535
+ ax = getattr(a, 'axes', None)
536
+ if (isinstance(a, mpl.figure.SubFigure)
537
+ or mouseevent.inaxes is None or ax is None
538
+ or mouseevent.inaxes == ax):
539
+ # we need to check if mouseevent.inaxes is None
540
+ # because some objects associated with an Axes (e.g., a
541
+ # tick label) can be outside the bounding box of the
542
+ # Axes and inaxes will be None
543
+ # also check that ax is None so that it traverse objects
544
+ # which do not have an axes property but children might
545
+ a.pick(mouseevent)
546
+
547
+ def set_picker(self, picker):
548
+ """
549
+ Define the picking behavior of the artist.
550
+
551
+ Parameters
552
+ ----------
553
+ picker : None or bool or float or callable
554
+ This can be one of the following:
555
+
556
+ - *None*: Picking is disabled for this artist (default).
557
+
558
+ - A boolean: If *True* then picking will be enabled and the
559
+ artist will fire a pick event if the mouse event is over
560
+ the artist.
561
+
562
+ - A float: If picker is a number it is interpreted as an
563
+ epsilon tolerance in points and the artist will fire
564
+ off an event if its data is within epsilon of the mouse
565
+ event. For some artists like lines and patch collections,
566
+ the artist may provide additional data to the pick event
567
+ that is generated, e.g., the indices of the data within
568
+ epsilon of the pick event
569
+
570
+ - A function: If picker is callable, it is a user supplied
571
+ function which determines whether the artist is hit by the
572
+ mouse event::
573
+
574
+ hit, props = picker(artist, mouseevent)
575
+
576
+ to determine the hit test. if the mouse event is over the
577
+ artist, return *hit=True* and props is a dictionary of
578
+ properties you want added to the PickEvent attributes.
579
+ """
580
+ self._picker = picker
581
+
582
+ def get_picker(self):
583
+ """
584
+ Return the picking behavior of the artist.
585
+
586
+ The possible values are described in `.Artist.set_picker`.
587
+
588
+ See Also
589
+ --------
590
+ .Artist.set_picker, .Artist.pickable, .Artist.pick
591
+ """
592
+ return self._picker
593
+
594
+ def get_url(self):
595
+ """Return the url."""
596
+ return self._url
597
+
598
+ def set_url(self, url):
599
+ """
600
+ Set the url for the artist.
601
+
602
+ Parameters
603
+ ----------
604
+ url : str
605
+ """
606
+ self._url = url
607
+
608
+ def get_gid(self):
609
+ """Return the group id."""
610
+ return self._gid
611
+
612
+ def set_gid(self, gid):
613
+ """
614
+ Set the (group) id for the artist.
615
+
616
+ Parameters
617
+ ----------
618
+ gid : str
619
+ """
620
+ self._gid = gid
621
+
622
+ def get_snap(self):
623
+ """
624
+ Return the snap setting.
625
+
626
+ See `.set_snap` for details.
627
+ """
628
+ if mpl.rcParams['path.snap']:
629
+ return self._snap
630
+ else:
631
+ return False
632
+
633
+ def set_snap(self, snap):
634
+ """
635
+ Set the snapping behavior.
636
+
637
+ Snapping aligns positions with the pixel grid, which results in
638
+ clearer images. For example, if a black line of 1px width was
639
+ defined at a position in between two pixels, the resulting image
640
+ would contain the interpolated value of that line in the pixel grid,
641
+ which would be a grey value on both adjacent pixel positions. In
642
+ contrast, snapping will move the line to the nearest integer pixel
643
+ value, so that the resulting image will really contain a 1px wide
644
+ black line.
645
+
646
+ Snapping is currently only supported by the Agg and MacOSX backends.
647
+
648
+ Parameters
649
+ ----------
650
+ snap : bool or None
651
+ Possible values:
652
+
653
+ - *True*: Snap vertices to the nearest pixel center.
654
+ - *False*: Do not modify vertex positions.
655
+ - *None*: (auto) If the path contains only rectilinear line
656
+ segments, round to the nearest pixel center.
657
+ """
658
+ self._snap = snap
659
+ self.stale = True
660
+
661
+ def get_sketch_params(self):
662
+ """
663
+ Return the sketch parameters for the artist.
664
+
665
+ Returns
666
+ -------
667
+ tuple or None
668
+
669
+ A 3-tuple with the following elements:
670
+
671
+ - *scale*: The amplitude of the wiggle perpendicular to the
672
+ source line.
673
+ - *length*: The length of the wiggle along the line.
674
+ - *randomness*: The scale factor by which the length is
675
+ shrunken or expanded.
676
+
677
+ Returns *None* if no sketch parameters were set.
678
+ """
679
+ return self._sketch
680
+
681
+ def set_sketch_params(self, scale=None, length=None, randomness=None):
682
+ """
683
+ Set the sketch parameters.
684
+
685
+ Parameters
686
+ ----------
687
+ scale : float, optional
688
+ The amplitude of the wiggle perpendicular to the source
689
+ line, in pixels. If scale is `None`, or not provided, no
690
+ sketch filter will be provided.
691
+ length : float, optional
692
+ The length of the wiggle along the line, in pixels
693
+ (default 128.0)
694
+ randomness : float, optional
695
+ The scale factor by which the length is shrunken or
696
+ expanded (default 16.0)
697
+
698
+ The PGF backend uses this argument as an RNG seed and not as
699
+ described above. Using the same seed yields the same random shape.
700
+
701
+ .. ACCEPTS: (scale: float, length: float, randomness: float)
702
+ """
703
+ if scale is None:
704
+ self._sketch = None
705
+ else:
706
+ self._sketch = (scale, length or 128.0, randomness or 16.0)
707
+ self.stale = True
708
+
709
+ def set_path_effects(self, path_effects):
710
+ """
711
+ Set the path effects.
712
+
713
+ Parameters
714
+ ----------
715
+ path_effects : list of `.AbstractPathEffect`
716
+ """
717
+ self._path_effects = path_effects
718
+ self.stale = True
719
+
720
+ def get_path_effects(self):
721
+ return self._path_effects
722
+
723
+ def get_figure(self, root=False):
724
+ """
725
+ Return the `.Figure` or `.SubFigure` instance the artist belongs to.
726
+
727
+ Parameters
728
+ ----------
729
+ root : bool, default=False
730
+ If False, return the (Sub)Figure this artist is on. If True,
731
+ return the root Figure for a nested tree of SubFigures.
732
+ """
733
+ if root and self._parent_figure is not None:
734
+ return self._parent_figure.get_figure(root=True)
735
+
736
+ return self._parent_figure
737
+
738
+ def set_figure(self, fig):
739
+ """
740
+ Set the `.Figure` or `.SubFigure` instance the artist belongs to.
741
+
742
+ Parameters
743
+ ----------
744
+ fig : `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure`
745
+ """
746
+ # if this is a no-op just return
747
+ if self._parent_figure is fig:
748
+ return
749
+ # if we currently have a figure (the case of both `self.figure`
750
+ # and *fig* being none is taken care of above) we then user is
751
+ # trying to change the figure an artist is associated with which
752
+ # is not allowed for the same reason as adding the same instance
753
+ # to more than one Axes
754
+ if self._parent_figure is not None:
755
+ raise RuntimeError("Can not put single artist in "
756
+ "more than one figure")
757
+ self._parent_figure = fig
758
+ if self._parent_figure and self._parent_figure is not self:
759
+ self.pchanged()
760
+ self.stale = True
761
+
762
+ figure = property(get_figure, set_figure,
763
+ doc=("The (Sub)Figure that the artist is on. For more "
764
+ "control, use the `get_figure` method."))
765
+
766
+ def set_clip_box(self, clipbox):
767
+ """
768
+ Set the artist's clip `.Bbox`.
769
+
770
+ Parameters
771
+ ----------
772
+ clipbox : `~matplotlib.transforms.BboxBase` or None
773
+ Will typically be created from a `.TransformedBbox`. For instance,
774
+ ``TransformedBbox(Bbox([[0, 0], [1, 1]]), ax.transAxes)`` is the default
775
+ clipping for an artist added to an Axes.
776
+
777
+ """
778
+ _api.check_isinstance((BboxBase, None), clipbox=clipbox)
779
+ if clipbox != self.clipbox:
780
+ self.clipbox = clipbox
781
+ self.pchanged()
782
+ self.stale = True
783
+
784
+ def set_clip_path(self, path, transform=None):
785
+ """
786
+ Set the artist's clip path.
787
+
788
+ Parameters
789
+ ----------
790
+ path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath` or None
791
+ The clip path. If given a `.Path`, *transform* must be provided as
792
+ well. If *None*, a previously set clip path is removed.
793
+ transform : `~matplotlib.transforms.Transform`, optional
794
+ Only used if *path* is a `.Path`, in which case the given `.Path`
795
+ is converted to a `.TransformedPath` using *transform*.
796
+
797
+ Notes
798
+ -----
799
+ For efficiency, if *path* is a `.Rectangle` this method will set the
800
+ clipping box to the corresponding rectangle and set the clipping path
801
+ to ``None``.
802
+
803
+ For technical reasons (support of `~.Artist.set`), a tuple
804
+ (*path*, *transform*) is also accepted as a single positional
805
+ parameter.
806
+
807
+ .. ACCEPTS: Patch or (Path, Transform) or None
808
+ """
809
+ from matplotlib.patches import Patch, Rectangle
810
+
811
+ success = False
812
+ if transform is None:
813
+ if isinstance(path, Rectangle):
814
+ self.clipbox = TransformedBbox(Bbox.unit(),
815
+ path.get_transform())
816
+ self._clippath = None
817
+ success = True
818
+ elif isinstance(path, Patch):
819
+ self._clippath = TransformedPatchPath(path)
820
+ success = True
821
+ elif isinstance(path, tuple):
822
+ path, transform = path
823
+
824
+ if path is None:
825
+ self._clippath = None
826
+ success = True
827
+ elif isinstance(path, Path):
828
+ self._clippath = TransformedPath(path, transform)
829
+ success = True
830
+ elif isinstance(path, TransformedPatchPath):
831
+ self._clippath = path
832
+ success = True
833
+ elif isinstance(path, TransformedPath):
834
+ self._clippath = path
835
+ success = True
836
+
837
+ if not success:
838
+ raise TypeError(
839
+ "Invalid arguments to set_clip_path, of type "
840
+ f"{type(path).__name__} and {type(transform).__name__}")
841
+ # This may result in the callbacks being hit twice, but guarantees they
842
+ # will be hit at least once.
843
+ self.pchanged()
844
+ self.stale = True
845
+
846
+ def get_alpha(self):
847
+ """
848
+ Return the alpha value used for blending - not supported on all
849
+ backends.
850
+ """
851
+ return self._alpha
852
+
853
+ def get_visible(self):
854
+ """Return the visibility."""
855
+ return self._visible
856
+
857
+ def get_animated(self):
858
+ """Return whether the artist is animated."""
859
+ return self._animated
860
+
861
+ def get_in_layout(self):
862
+ """
863
+ Return boolean flag, ``True`` if artist is included in layout
864
+ calculations.
865
+
866
+ E.g. :ref:`constrainedlayout_guide`,
867
+ `.Figure.tight_layout()`, and
868
+ ``fig.savefig(fname, bbox_inches='tight')``.
869
+ """
870
+ return self._in_layout
871
+
872
+ def _fully_clipped_to_axes(self):
873
+ """
874
+ Return a boolean flag, ``True`` if the artist is clipped to the Axes
875
+ and can thus be skipped in layout calculations. Requires `get_clip_on`
876
+ is True, one of `clip_box` or `clip_path` is set, ``clip_box.extents``
877
+ is equivalent to ``ax.bbox.extents`` (if set), and ``clip_path._patch``
878
+ is equivalent to ``ax.patch`` (if set).
879
+ """
880
+ # Note that ``clip_path.get_fully_transformed_path().get_extents()``
881
+ # cannot be directly compared to ``axes.bbox.extents`` because the
882
+ # extents may be undefined (i.e. equivalent to ``Bbox.null()``)
883
+ # before the associated artist is drawn, and this method is meant
884
+ # to determine whether ``axes.get_tightbbox()`` may bypass drawing
885
+ clip_box = self.get_clip_box()
886
+ clip_path = self.get_clip_path()
887
+ return (self.axes is not None
888
+ and self.get_clip_on()
889
+ and (clip_box is not None or clip_path is not None)
890
+ and (clip_box is None
891
+ or np.all(clip_box.extents == self.axes.bbox.extents))
892
+ and (clip_path is None
893
+ or isinstance(clip_path, TransformedPatchPath)
894
+ and clip_path._patch is self.axes.patch))
895
+
896
+ def get_clip_on(self):
897
+ """Return whether the artist uses clipping."""
898
+ return self._clipon
899
+
900
+ def get_clip_box(self):
901
+ """Return the clipbox."""
902
+ return self.clipbox
903
+
904
+ def get_clip_path(self):
905
+ """Return the clip path."""
906
+ return self._clippath
907
+
908
+ def get_transformed_clip_path_and_affine(self):
909
+ """
910
+ Return the clip path with the non-affine part of its
911
+ transformation applied, and the remaining affine part of its
912
+ transformation.
913
+ """
914
+ if self._clippath is not None:
915
+ return self._clippath.get_transformed_path_and_affine()
916
+ return None, None
917
+
918
+ def set_clip_on(self, b):
919
+ """
920
+ Set whether the artist uses clipping.
921
+
922
+ When False, artists will be visible outside the Axes which
923
+ can lead to unexpected results.
924
+
925
+ Parameters
926
+ ----------
927
+ b : bool
928
+ """
929
+ self._clipon = b
930
+ # This may result in the callbacks being hit twice, but ensures they
931
+ # are hit at least once
932
+ self.pchanged()
933
+ self.stale = True
934
+
935
+ def _set_gc_clip(self, gc):
936
+ """Set the clip properly for the gc."""
937
+ if self._clipon:
938
+ if self.clipbox is not None:
939
+ gc.set_clip_rectangle(self.clipbox)
940
+ gc.set_clip_path(self._clippath)
941
+ else:
942
+ gc.set_clip_rectangle(None)
943
+ gc.set_clip_path(None)
944
+
945
+ def get_rasterized(self):
946
+ """Return whether the artist is to be rasterized."""
947
+ return self._rasterized
948
+
949
+ def set_rasterized(self, rasterized):
950
+ """
951
+ Force rasterized (bitmap) drawing for vector graphics output.
952
+
953
+ Rasterized drawing is not supported by all artists. If you try to
954
+ enable this on an artist that does not support it, the command has no
955
+ effect and a warning will be issued.
956
+
957
+ This setting is ignored for pixel-based output.
958
+
959
+ See also :doc:`/gallery/misc/rasterization_demo`.
960
+
961
+ Parameters
962
+ ----------
963
+ rasterized : bool
964
+ """
965
+ supports_rasterization = getattr(self.draw,
966
+ "_supports_rasterization", False)
967
+ if rasterized and not supports_rasterization:
968
+ _api.warn_external(f"Rasterization of '{self}' will be ignored")
969
+
970
+ self._rasterized = rasterized
971
+
972
+ def get_agg_filter(self):
973
+ """Return filter function to be used for agg filter."""
974
+ return self._agg_filter
975
+
976
+ def set_agg_filter(self, filter_func):
977
+ """
978
+ Set the agg filter.
979
+
980
+ Parameters
981
+ ----------
982
+ filter_func : callable
983
+ A filter function, which takes a (m, n, depth) float array
984
+ and a dpi value, and returns a (m, n, depth) array and two
985
+ offsets from the bottom left corner of the image
986
+
987
+ .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
988
+ and a dpi value, and returns a (m, n, 3) array and two offsets
989
+ from the bottom left corner of the image
990
+ """
991
+ self._agg_filter = filter_func
992
+ self.stale = True
993
+
994
+ def draw(self, renderer):
995
+ """
996
+ Draw the Artist (and its children) using the given renderer.
997
+
998
+ This has no effect if the artist is not visible (`.Artist.get_visible`
999
+ returns False).
1000
+
1001
+ Parameters
1002
+ ----------
1003
+ renderer : `~matplotlib.backend_bases.RendererBase` subclass.
1004
+
1005
+ Notes
1006
+ -----
1007
+ This method is overridden in the Artist subclasses.
1008
+ """
1009
+ if not self.get_visible():
1010
+ return
1011
+ self.stale = False
1012
+
1013
+ def set_alpha(self, alpha):
1014
+ """
1015
+ Set the alpha value used for blending - not supported on all backends.
1016
+
1017
+ Parameters
1018
+ ----------
1019
+ alpha : float or None
1020
+ *alpha* must be within the 0-1 range, inclusive.
1021
+ """
1022
+ if alpha is not None and not isinstance(alpha, Real):
1023
+ raise TypeError(
1024
+ f'alpha must be numeric or None, not {type(alpha)}')
1025
+ if alpha is not None and not (0 <= alpha <= 1):
1026
+ raise ValueError(f'alpha ({alpha}) is outside 0-1 range')
1027
+ if alpha != self._alpha:
1028
+ self._alpha = alpha
1029
+ self.pchanged()
1030
+ self.stale = True
1031
+
1032
+ def _set_alpha_for_array(self, alpha):
1033
+ """
1034
+ Set the alpha value used for blending - not supported on all backends.
1035
+
1036
+ Parameters
1037
+ ----------
1038
+ alpha : array-like or float or None
1039
+ All values must be within the 0-1 range, inclusive.
1040
+ Masked values and nans are not supported.
1041
+ """
1042
+ if isinstance(alpha, str):
1043
+ raise TypeError("alpha must be numeric or None, not a string")
1044
+ if not np.iterable(alpha):
1045
+ Artist.set_alpha(self, alpha)
1046
+ return
1047
+ alpha = np.asarray(alpha)
1048
+ if not (0 <= alpha.min() and alpha.max() <= 1):
1049
+ raise ValueError('alpha must be between 0 and 1, inclusive, '
1050
+ f'but min is {alpha.min()}, max is {alpha.max()}')
1051
+ self._alpha = alpha
1052
+ self.pchanged()
1053
+ self.stale = True
1054
+
1055
+ def set_visible(self, b):
1056
+ """
1057
+ Set the artist's visibility.
1058
+
1059
+ Parameters
1060
+ ----------
1061
+ b : bool
1062
+ """
1063
+ if b != self._visible:
1064
+ self._visible = b
1065
+ self.pchanged()
1066
+ self.stale = True
1067
+
1068
+ def set_animated(self, b):
1069
+ """
1070
+ Set whether the artist is intended to be used in an animation.
1071
+
1072
+ If True, the artist is excluded from regular drawing of the figure.
1073
+ You have to call `.Figure.draw_artist` / `.Axes.draw_artist`
1074
+ explicitly on the artist. This approach is used to speed up animations
1075
+ using blitting.
1076
+
1077
+ See also `matplotlib.animation` and
1078
+ :ref:`blitting`.
1079
+
1080
+ Parameters
1081
+ ----------
1082
+ b : bool
1083
+ """
1084
+ if self._animated != b:
1085
+ self._animated = b
1086
+ self.pchanged()
1087
+
1088
+ def set_in_layout(self, in_layout):
1089
+ """
1090
+ Set if artist is to be included in layout calculations,
1091
+ E.g. :ref:`constrainedlayout_guide`,
1092
+ `.Figure.tight_layout()`, and
1093
+ ``fig.savefig(fname, bbox_inches='tight')``.
1094
+
1095
+ Parameters
1096
+ ----------
1097
+ in_layout : bool
1098
+ """
1099
+ self._in_layout = in_layout
1100
+
1101
+ def get_label(self):
1102
+ """Return the label used for this artist in the legend."""
1103
+ return self._label
1104
+
1105
+ def set_label(self, s):
1106
+ """
1107
+ Set a label that will be displayed in the legend.
1108
+
1109
+ Parameters
1110
+ ----------
1111
+ s : object
1112
+ *s* will be converted to a string by calling `str`.
1113
+ """
1114
+ label = str(s) if s is not None else None
1115
+ if label != self._label:
1116
+ self._label = label
1117
+ self.pchanged()
1118
+ self.stale = True
1119
+
1120
+ def get_zorder(self):
1121
+ """Return the artist's zorder."""
1122
+ return self.zorder
1123
+
1124
+ def set_zorder(self, level):
1125
+ """
1126
+ Set the zorder for the artist. Artists with lower zorder
1127
+ values are drawn first.
1128
+
1129
+ Parameters
1130
+ ----------
1131
+ level : float
1132
+ """
1133
+ if level is None:
1134
+ level = self.__class__.zorder
1135
+ if level != self.zorder:
1136
+ self.zorder = level
1137
+ self.pchanged()
1138
+ self.stale = True
1139
+
1140
+ @property
1141
+ def sticky_edges(self):
1142
+ """
1143
+ ``x`` and ``y`` sticky edge lists for autoscaling.
1144
+
1145
+ When performing autoscaling, if a data limit coincides with a value in
1146
+ the corresponding sticky_edges list, then no margin will be added--the
1147
+ view limit "sticks" to the edge. A typical use case is histograms,
1148
+ where one usually expects no margin on the bottom edge (0) of the
1149
+ histogram.
1150
+
1151
+ Moreover, margin expansion "bumps" against sticky edges and cannot
1152
+ cross them. For example, if the upper data limit is 1.0, the upper
1153
+ view limit computed by simple margin application is 1.2, but there is a
1154
+ sticky edge at 1.1, then the actual upper view limit will be 1.1.
1155
+
1156
+ This attribute cannot be assigned to; however, the ``x`` and ``y``
1157
+ lists can be modified in place as needed.
1158
+
1159
+ Examples
1160
+ --------
1161
+ >>> artist.sticky_edges.x[:] = (xmin, xmax)
1162
+ >>> artist.sticky_edges.y[:] = (ymin, ymax)
1163
+
1164
+ """
1165
+ return self._sticky_edges
1166
+
1167
+ def update_from(self, other):
1168
+ """Copy properties from *other* to *self*."""
1169
+ self._transform = other._transform
1170
+ self._transformSet = other._transformSet
1171
+ self._visible = other._visible
1172
+ self._alpha = other._alpha
1173
+ self.clipbox = other.clipbox
1174
+ self._clipon = other._clipon
1175
+ self._clippath = other._clippath
1176
+ self._label = other._label
1177
+ self._sketch = other._sketch
1178
+ self._path_effects = other._path_effects
1179
+ self.sticky_edges.x[:] = other.sticky_edges.x.copy()
1180
+ self.sticky_edges.y[:] = other.sticky_edges.y.copy()
1181
+ self.pchanged()
1182
+ self.stale = True
1183
+
1184
+ def properties(self):
1185
+ """Return a dictionary of all the properties of the artist."""
1186
+ return ArtistInspector(self).properties()
1187
+
1188
+ def _update_props(self, props, errfmt):
1189
+ """
1190
+ Helper for `.Artist.set` and `.Artist.update`.
1191
+
1192
+ *errfmt* is used to generate error messages for invalid property
1193
+ names; it gets formatted with ``type(self)`` for "{cls}" and the
1194
+ property name for "{prop_name}".
1195
+ """
1196
+ ret = []
1197
+ with cbook._setattr_cm(self, eventson=False):
1198
+ for k, v in props.items():
1199
+ # Allow attributes we want to be able to update through
1200
+ # art.update, art.set, setp.
1201
+ if k == "axes":
1202
+ ret.append(setattr(self, k, v))
1203
+ else:
1204
+ func = getattr(self, f"set_{k}", None)
1205
+ if not callable(func):
1206
+ raise AttributeError(
1207
+ errfmt.format(cls=type(self), prop_name=k),
1208
+ name=k)
1209
+ ret.append(func(v))
1210
+ if ret:
1211
+ self.pchanged()
1212
+ self.stale = True
1213
+ return ret
1214
+
1215
+ def update(self, props):
1216
+ """
1217
+ Update this artist's properties from the dict *props*.
1218
+
1219
+ Parameters
1220
+ ----------
1221
+ props : dict
1222
+ """
1223
+ return self._update_props(
1224
+ props, "{cls.__name__!r} object has no property {prop_name!r}")
1225
+
1226
+ def _internal_update(self, kwargs):
1227
+ """
1228
+ Update artist properties without prenormalizing them, but generating
1229
+ errors as if calling `set`.
1230
+
1231
+ The lack of prenormalization is to maintain backcompatibility.
1232
+ """
1233
+ return self._update_props(
1234
+ kwargs, "{cls.__name__}.set() got an unexpected keyword argument "
1235
+ "{prop_name!r}")
1236
+
1237
+ def set(self, **kwargs):
1238
+ # docstring and signature are auto-generated via
1239
+ # Artist._update_set_signature_and_docstring() at the end of the
1240
+ # module.
1241
+ return self._internal_update(cbook.normalize_kwargs(kwargs, self))
1242
+
1243
+ @contextlib.contextmanager
1244
+ def _cm_set(self, **kwargs):
1245
+ """
1246
+ `.Artist.set` context-manager that restores original values at exit.
1247
+ """
1248
+ orig_vals = {k: getattr(self, f"get_{k}")() for k in kwargs}
1249
+ try:
1250
+ self.set(**kwargs)
1251
+ yield
1252
+ finally:
1253
+ self.set(**orig_vals)
1254
+
1255
+ def findobj(self, match=None, include_self=True):
1256
+ """
1257
+ Find artist objects.
1258
+
1259
+ Recursively find all `.Artist` instances contained in the artist.
1260
+
1261
+ Parameters
1262
+ ----------
1263
+ match
1264
+ A filter criterion for the matches. This can be
1265
+
1266
+ - *None*: Return all objects contained in artist.
1267
+ - A function with signature ``def match(artist: Artist) -> bool``.
1268
+ The result will only contain artists for which the function
1269
+ returns *True*.
1270
+ - A class instance: e.g., `.Line2D`. The result will only contain
1271
+ artists of this class or its subclasses (``isinstance`` check).
1272
+
1273
+ include_self : bool
1274
+ Include *self* in the list to be checked for a match.
1275
+
1276
+ Returns
1277
+ -------
1278
+ list of `.Artist`
1279
+
1280
+ """
1281
+ if match is None: # always return True
1282
+ def matchfunc(x):
1283
+ return True
1284
+ elif isinstance(match, type) and issubclass(match, Artist):
1285
+ def matchfunc(x):
1286
+ return isinstance(x, match)
1287
+ elif callable(match):
1288
+ matchfunc = match
1289
+ else:
1290
+ raise ValueError('match must be None, a matplotlib.artist.Artist '
1291
+ 'subclass, or a callable')
1292
+
1293
+ artists = reduce(operator.iadd,
1294
+ [c.findobj(matchfunc) for c in self.get_children()], [])
1295
+ if include_self and matchfunc(self):
1296
+ artists.append(self)
1297
+ return artists
1298
+
1299
+ def get_cursor_data(self, event):
1300
+ """
1301
+ Return the cursor data for a given event.
1302
+
1303
+ .. note::
1304
+ This method is intended to be overridden by artist subclasses.
1305
+ As an end-user of Matplotlib you will most likely not call this
1306
+ method yourself.
1307
+
1308
+ Cursor data can be used by Artists to provide additional context
1309
+ information for a given event. The default implementation just returns
1310
+ *None*.
1311
+
1312
+ Subclasses can override the method and return arbitrary data. However,
1313
+ when doing so, they must ensure that `.format_cursor_data` can convert
1314
+ the data to a string representation.
1315
+
1316
+ The only current use case is displaying the z-value of an `.AxesImage`
1317
+ in the status bar of a plot window, while moving the mouse.
1318
+
1319
+ Parameters
1320
+ ----------
1321
+ event : `~matplotlib.backend_bases.MouseEvent`
1322
+
1323
+ See Also
1324
+ --------
1325
+ format_cursor_data
1326
+
1327
+ """
1328
+ return None
1329
+
1330
+ def format_cursor_data(self, data):
1331
+ """
1332
+ Return a string representation of *data*.
1333
+
1334
+ .. note::
1335
+ This method is intended to be overridden by artist subclasses.
1336
+ As an end-user of Matplotlib you will most likely not call this
1337
+ method yourself.
1338
+
1339
+ The default implementation converts ints and floats and arrays of ints
1340
+ and floats into a comma-separated string enclosed in square brackets,
1341
+ unless the artist has an associated colorbar, in which case scalar
1342
+ values are formatted using the colorbar's formatter.
1343
+
1344
+ See Also
1345
+ --------
1346
+ get_cursor_data
1347
+ """
1348
+ if np.ndim(data) == 0 and hasattr(self, "_format_cursor_data_override"):
1349
+ # workaround for ScalarMappable to be able to define its own
1350
+ # format_cursor_data(). See ScalarMappable._format_cursor_data_override
1351
+ # for details.
1352
+ return self._format_cursor_data_override(data)
1353
+ else:
1354
+ try:
1355
+ data[0]
1356
+ except (TypeError, IndexError):
1357
+ data = [data]
1358
+ data_str = ', '.join(f'{item:0.3g}' for item in data
1359
+ if isinstance(item, Number))
1360
+ return "[" + data_str + "]"
1361
+
1362
+ def get_mouseover(self):
1363
+ """
1364
+ Return whether this artist is queried for custom context information
1365
+ when the mouse cursor moves over it.
1366
+ """
1367
+ return self._mouseover
1368
+
1369
+ def set_mouseover(self, mouseover):
1370
+ """
1371
+ Set whether this artist is queried for custom context information when
1372
+ the mouse cursor moves over it.
1373
+
1374
+ Parameters
1375
+ ----------
1376
+ mouseover : bool
1377
+
1378
+ See Also
1379
+ --------
1380
+ get_cursor_data
1381
+ .ToolCursorPosition
1382
+ .NavigationToolbar2
1383
+ """
1384
+ self._mouseover = bool(mouseover)
1385
+ ax = self.axes
1386
+ if ax:
1387
+ if self._mouseover:
1388
+ ax._mouseover_set.add(self)
1389
+ else:
1390
+ ax._mouseover_set.discard(self)
1391
+
1392
+ mouseover = property(get_mouseover, set_mouseover) # backcompat.
1393
+
1394
+
1395
+ def _get_tightbbox_for_layout_only(obj, *args, **kwargs):
1396
+ """
1397
+ Matplotlib's `.Axes.get_tightbbox` and `.Axis.get_tightbbox` support a
1398
+ *for_layout_only* kwarg; this helper tries to use the kwarg but skips it
1399
+ when encountering third-party subclasses that do not support it.
1400
+ """
1401
+ try:
1402
+ return obj.get_tightbbox(*args, **{**kwargs, "for_layout_only": True})
1403
+ except TypeError:
1404
+ return obj.get_tightbbox(*args, **kwargs)
1405
+
1406
+
1407
+ class ArtistInspector:
1408
+ """
1409
+ A helper class to inspect an `~matplotlib.artist.Artist` and return
1410
+ information about its settable properties and their current values.
1411
+ """
1412
+
1413
+ def __init__(self, o):
1414
+ r"""
1415
+ Initialize the artist inspector with an `Artist` or an iterable of
1416
+ `Artist`\s. If an iterable is used, we assume it is a homogeneous
1417
+ sequence (all `Artist`\s are of the same type) and it is your
1418
+ responsibility to make sure this is so.
1419
+ """
1420
+ if not isinstance(o, Artist):
1421
+ if np.iterable(o):
1422
+ o = list(o)
1423
+ if len(o):
1424
+ o = o[0]
1425
+
1426
+ self.oorig = o
1427
+ if not isinstance(o, type):
1428
+ o = type(o)
1429
+ self.o = o
1430
+
1431
+ self.aliasd = self.get_aliases()
1432
+
1433
+ def get_aliases(self):
1434
+ """
1435
+ Get a dict mapping property fullnames to sets of aliases for each alias
1436
+ in the :class:`~matplotlib.artist.ArtistInspector`.
1437
+
1438
+ e.g., for lines::
1439
+
1440
+ {'markerfacecolor': {'mfc'},
1441
+ 'linewidth' : {'lw'},
1442
+ }
1443
+ """
1444
+ names = [name for name in dir(self.o)
1445
+ if name.startswith(('set_', 'get_'))
1446
+ and callable(getattr(self.o, name))]
1447
+ aliases = {}
1448
+ for name in names:
1449
+ func = getattr(self.o, name)
1450
+ if not self.is_alias(func):
1451
+ continue
1452
+ propname = re.search(f"`({name[:4]}.*)`", # get_.*/set_.*
1453
+ inspect.getdoc(func)).group(1)
1454
+ aliases.setdefault(propname[4:], set()).add(name[4:])
1455
+ return aliases
1456
+
1457
+ _get_valid_values_regex = re.compile(
1458
+ r"\n\s*(?:\.\.\s+)?ACCEPTS:\s*((?:.|\n)*?)(?:$|(?:\n\n))"
1459
+ )
1460
+
1461
+ def get_valid_values(self, attr):
1462
+ """
1463
+ Get the legal arguments for the setter associated with *attr*.
1464
+
1465
+ This is done by querying the docstring of the setter for a line that
1466
+ begins with "ACCEPTS:" or ".. ACCEPTS:", and then by looking for a
1467
+ numpydoc-style documentation for the setter's first argument.
1468
+ """
1469
+
1470
+ name = 'set_%s' % attr
1471
+ if not hasattr(self.o, name):
1472
+ raise AttributeError(f'{self.o} has no function {name}')
1473
+ func = getattr(self.o, name)
1474
+
1475
+ if hasattr(func, '_kwarg_doc'):
1476
+ return func._kwarg_doc
1477
+
1478
+ docstring = inspect.getdoc(func)
1479
+ if docstring is None:
1480
+ return 'unknown'
1481
+
1482
+ if docstring.startswith('Alias for '):
1483
+ return None
1484
+
1485
+ match = self._get_valid_values_regex.search(docstring)
1486
+ if match is not None:
1487
+ return re.sub("\n *", " ", match.group(1))
1488
+
1489
+ # Much faster than list(inspect.signature(func).parameters)[1],
1490
+ # although barely relevant wrt. matplotlib's total import time.
1491
+ param_name = func.__code__.co_varnames[1]
1492
+ # We could set the presence * based on whether the parameter is a
1493
+ # varargs (it can't be a varkwargs) but it's not really worth it.
1494
+ match = re.search(fr"(?m)^ *\*?{param_name} : (.+)", docstring)
1495
+ if match:
1496
+ return match.group(1)
1497
+
1498
+ return 'unknown'
1499
+
1500
+ def _replace_path(self, source_class):
1501
+ """
1502
+ Changes the full path to the public API path that is used
1503
+ in sphinx. This is needed for links to work.
1504
+ """
1505
+ replace_dict = {'_base._AxesBase': 'Axes',
1506
+ '_axes.Axes': 'Axes'}
1507
+ for key, value in replace_dict.items():
1508
+ source_class = source_class.replace(key, value)
1509
+ return source_class
1510
+
1511
+ def get_setters(self):
1512
+ """
1513
+ Get the attribute strings with setters for object.
1514
+
1515
+ For example, for a line, return ``['markerfacecolor', 'linewidth',
1516
+ ....]``.
1517
+ """
1518
+ setters = []
1519
+ for name in dir(self.o):
1520
+ if not name.startswith('set_'):
1521
+ continue
1522
+ func = getattr(self.o, name)
1523
+ if (not callable(func)
1524
+ or self.number_of_parameters(func) < 2
1525
+ or self.is_alias(func)):
1526
+ continue
1527
+ setters.append(name[4:])
1528
+ return setters
1529
+
1530
+ @staticmethod
1531
+ @cache
1532
+ def number_of_parameters(func):
1533
+ """Return number of parameters of the callable *func*."""
1534
+ return len(inspect.signature(func).parameters)
1535
+
1536
+ @staticmethod
1537
+ @cache
1538
+ def is_alias(method):
1539
+ """
1540
+ Return whether the object *method* is an alias for another method.
1541
+ """
1542
+
1543
+ ds = inspect.getdoc(method)
1544
+ if ds is None:
1545
+ return False
1546
+
1547
+ return ds.startswith('Alias for ')
1548
+
1549
+ def aliased_name(self, s):
1550
+ """
1551
+ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME'.
1552
+
1553
+ For example, for the line markerfacecolor property, which has an
1554
+ alias, return 'markerfacecolor or mfc' and for the transform
1555
+ property, which does not, return 'transform'.
1556
+ """
1557
+ aliases = ''.join(' or %s' % x for x in sorted(self.aliasd.get(s, [])))
1558
+ return s + aliases
1559
+
1560
+ _NOT_LINKABLE = {
1561
+ # A set of property setter methods that are not available in our
1562
+ # current docs. This is a workaround used to prevent trying to link
1563
+ # these setters which would lead to "target reference not found"
1564
+ # warnings during doc build.
1565
+ 'matplotlib.image._ImageBase.set_alpha',
1566
+ 'matplotlib.image._ImageBase.set_array',
1567
+ 'matplotlib.image._ImageBase.set_data',
1568
+ 'matplotlib.image._ImageBase.set_filternorm',
1569
+ 'matplotlib.image._ImageBase.set_filterrad',
1570
+ 'matplotlib.image._ImageBase.set_interpolation',
1571
+ 'matplotlib.image._ImageBase.set_interpolation_stage',
1572
+ 'matplotlib.image._ImageBase.set_resample',
1573
+ 'matplotlib.text._AnnotationBase.set_annotation_clip',
1574
+ }
1575
+
1576
+ def aliased_name_rest(self, s, target):
1577
+ """
1578
+ Return 'PROPNAME or alias' if *s* has an alias, else return 'PROPNAME',
1579
+ formatted for reST.
1580
+
1581
+ For example, for the line markerfacecolor property, which has an
1582
+ alias, return 'markerfacecolor or mfc' and for the transform
1583
+ property, which does not, return 'transform'.
1584
+ """
1585
+ # workaround to prevent "reference target not found"
1586
+ if target in self._NOT_LINKABLE:
1587
+ return f'``{s}``'
1588
+
1589
+ aliases = ''.join(
1590
+ f' or :meth:`{a} <{target}>`' for a in sorted(self.aliasd.get(s, [])))
1591
+ return f':meth:`{s} <{target}>`{aliases}'
1592
+
1593
+ def pprint_setters(self, prop=None, leadingspace=2):
1594
+ """
1595
+ If *prop* is *None*, return a list of strings of all settable
1596
+ properties and their valid values.
1597
+
1598
+ If *prop* is not *None*, it is a valid property name and that
1599
+ property will be returned as a string of property : valid
1600
+ values.
1601
+ """
1602
+ if leadingspace:
1603
+ pad = ' ' * leadingspace
1604
+ else:
1605
+ pad = ''
1606
+ if prop is not None:
1607
+ accepts = self.get_valid_values(prop)
1608
+ return f'{pad}{prop}: {accepts}'
1609
+
1610
+ lines = []
1611
+ for prop in sorted(self.get_setters()):
1612
+ accepts = self.get_valid_values(prop)
1613
+ name = self.aliased_name(prop)
1614
+ lines.append(f'{pad}{name}: {accepts}')
1615
+ return lines
1616
+
1617
+ def pprint_setters_rest(self, prop=None, leadingspace=4):
1618
+ """
1619
+ If *prop* is *None*, return a list of reST-formatted strings of all
1620
+ settable properties and their valid values.
1621
+
1622
+ If *prop* is not *None*, it is a valid property name and that
1623
+ property will be returned as a string of "property : valid"
1624
+ values.
1625
+ """
1626
+ if leadingspace:
1627
+ pad = ' ' * leadingspace
1628
+ else:
1629
+ pad = ''
1630
+ if prop is not None:
1631
+ accepts = self.get_valid_values(prop)
1632
+ return f'{pad}{prop}: {accepts}'
1633
+
1634
+ prop_and_qualnames = []
1635
+ for prop in sorted(self.get_setters()):
1636
+ # Find the parent method which actually provides the docstring.
1637
+ for cls in self.o.__mro__:
1638
+ method = getattr(cls, f"set_{prop}", None)
1639
+ if method and method.__doc__ is not None:
1640
+ break
1641
+ else: # No docstring available.
1642
+ method = getattr(self.o, f"set_{prop}")
1643
+ prop_and_qualnames.append(
1644
+ (prop, f"{method.__module__}.{method.__qualname__}"))
1645
+
1646
+ names = [self.aliased_name_rest(prop, target)
1647
+ .replace('_base._AxesBase', 'Axes')
1648
+ .replace('_axes.Axes', 'Axes')
1649
+ for prop, target in prop_and_qualnames]
1650
+ accepts = [self.get_valid_values(prop)
1651
+ for prop, _ in prop_and_qualnames]
1652
+
1653
+ col0_len = max(len(n) for n in names)
1654
+ col1_len = max(len(a) for a in accepts)
1655
+ table_formatstr = pad + ' ' + '=' * col0_len + ' ' + '=' * col1_len
1656
+
1657
+ return [
1658
+ '',
1659
+ pad + '.. table::',
1660
+ pad + ' :class: property-table',
1661
+ '',
1662
+ table_formatstr,
1663
+ pad + ' ' + 'Property'.ljust(col0_len)
1664
+ + ' ' + 'Description'.ljust(col1_len),
1665
+ table_formatstr,
1666
+ *[pad + ' ' + n.ljust(col0_len) + ' ' + a.ljust(col1_len)
1667
+ for n, a in zip(names, accepts)],
1668
+ table_formatstr,
1669
+ '',
1670
+ ]
1671
+
1672
+ def properties(self):
1673
+ """Return a dictionary mapping property name -> value."""
1674
+ o = self.oorig
1675
+ getters = [name for name in dir(o)
1676
+ if name.startswith('get_') and callable(getattr(o, name))]
1677
+ getters.sort()
1678
+ d = {}
1679
+ for name in getters:
1680
+ func = getattr(o, name)
1681
+ if self.is_alias(func):
1682
+ continue
1683
+ try:
1684
+ with warnings.catch_warnings():
1685
+ warnings.simplefilter('ignore')
1686
+ val = func()
1687
+ except Exception:
1688
+ continue
1689
+ else:
1690
+ d[name[4:]] = val
1691
+ return d
1692
+
1693
+ def pprint_getters(self):
1694
+ """Return the getters and actual values as list of strings."""
1695
+ lines = []
1696
+ for name, val in sorted(self.properties().items()):
1697
+ if getattr(val, 'shape', ()) != () and len(val) > 6:
1698
+ s = str(val[:6]) + '...'
1699
+ else:
1700
+ s = str(val)
1701
+ s = s.replace('\n', ' ')
1702
+ if len(s) > 50:
1703
+ s = s[:50] + '...'
1704
+ name = self.aliased_name(name)
1705
+ lines.append(f' {name} = {s}')
1706
+ return lines
1707
+
1708
+
1709
+ def getp(obj, property=None):
1710
+ """
1711
+ Return the value of an `.Artist`'s *property*, or print all of them.
1712
+
1713
+ Parameters
1714
+ ----------
1715
+ obj : `~matplotlib.artist.Artist`
1716
+ The queried artist; e.g., a `.Line2D`, a `.Text`, or an `~.axes.Axes`.
1717
+
1718
+ property : str or None, default: None
1719
+ If *property* is 'somename', this function returns
1720
+ ``obj.get_somename()``.
1721
+
1722
+ If it's None (or unset), it *prints* all gettable properties from
1723
+ *obj*. Many properties have aliases for shorter typing, e.g. 'lw' is
1724
+ an alias for 'linewidth'. In the output, aliases and full property
1725
+ names will be listed as:
1726
+
1727
+ property or alias = value
1728
+
1729
+ e.g.:
1730
+
1731
+ linewidth or lw = 2
1732
+
1733
+ See Also
1734
+ --------
1735
+ setp
1736
+ """
1737
+ if property is None:
1738
+ insp = ArtistInspector(obj)
1739
+ ret = insp.pprint_getters()
1740
+ print('\n'.join(ret))
1741
+ return
1742
+ return getattr(obj, 'get_' + property)()
1743
+
1744
+ # alias
1745
+ get = getp
1746
+
1747
+
1748
+ def setp(obj, *args, file=None, **kwargs):
1749
+ """
1750
+ Set one or more properties on an `.Artist`, or list allowed values.
1751
+
1752
+ Parameters
1753
+ ----------
1754
+ obj : `~matplotlib.artist.Artist` or list of `.Artist`
1755
+ The artist(s) whose properties are being set or queried. When setting
1756
+ properties, all artists are affected; when querying the allowed values,
1757
+ only the first instance in the sequence is queried.
1758
+
1759
+ For example, two lines can be made thicker and red with a single call:
1760
+
1761
+ >>> x = arange(0, 1, 0.01)
1762
+ >>> lines = plot(x, sin(2*pi*x), x, sin(4*pi*x))
1763
+ >>> setp(lines, linewidth=2, color='r')
1764
+
1765
+ file : file-like, default: `sys.stdout`
1766
+ Where `setp` writes its output when asked to list allowed values.
1767
+
1768
+ >>> with open('output.log') as file:
1769
+ ... setp(line, file=file)
1770
+
1771
+ The default, ``None``, means `sys.stdout`.
1772
+
1773
+ *args, **kwargs
1774
+ The properties to set. The following combinations are supported:
1775
+
1776
+ - Set the linestyle of a line to be dashed:
1777
+
1778
+ >>> line, = plot([1, 2, 3])
1779
+ >>> setp(line, linestyle='--')
1780
+
1781
+ - Set multiple properties at once:
1782
+
1783
+ >>> setp(line, linewidth=2, color='r')
1784
+
1785
+ - List allowed values for a line's linestyle:
1786
+
1787
+ >>> setp(line, 'linestyle')
1788
+ linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
1789
+
1790
+ - List all properties that can be set, and their allowed values:
1791
+
1792
+ >>> setp(line)
1793
+ agg_filter: a filter function, ...
1794
+ [long output listing omitted]
1795
+
1796
+ `setp` also supports MATLAB style string/value pairs. For example, the
1797
+ following are equivalent:
1798
+
1799
+ >>> setp(lines, 'linewidth', 2, 'color', 'r') # MATLAB style
1800
+ >>> setp(lines, linewidth=2, color='r') # Python style
1801
+
1802
+ See Also
1803
+ --------
1804
+ getp
1805
+ """
1806
+
1807
+ if isinstance(obj, Artist):
1808
+ objs = [obj]
1809
+ else:
1810
+ objs = list(cbook.flatten(obj))
1811
+
1812
+ if not objs:
1813
+ return
1814
+
1815
+ insp = ArtistInspector(objs[0])
1816
+
1817
+ if not kwargs and len(args) < 2:
1818
+ if args:
1819
+ print(insp.pprint_setters(prop=args[0]), file=file)
1820
+ else:
1821
+ print('\n'.join(insp.pprint_setters()), file=file)
1822
+ return
1823
+
1824
+ if len(args) % 2:
1825
+ raise ValueError('The set args must be string, value pairs')
1826
+
1827
+ funcvals = dict(zip(args[::2], args[1::2]))
1828
+ ret = [o.update(funcvals) for o in objs] + [o.set(**kwargs) for o in objs]
1829
+ return list(cbook.flatten(ret))
1830
+
1831
+
1832
+ def kwdoc(artist):
1833
+ r"""
1834
+ Inspect an `~matplotlib.artist.Artist` class (using `.ArtistInspector`) and
1835
+ return information about its settable properties and their current values.
1836
+
1837
+ Parameters
1838
+ ----------
1839
+ artist : `~matplotlib.artist.Artist` or an iterable of `Artist`\s
1840
+
1841
+ Returns
1842
+ -------
1843
+ str
1844
+ The settable properties of *artist*, as plain text if
1845
+ :rc:`docstring.hardcopy` is False and as a rst table (intended for
1846
+ use in Sphinx) if it is True.
1847
+ """
1848
+ ai = ArtistInspector(artist)
1849
+ return ('\n'.join(ai.pprint_setters_rest(leadingspace=4))
1850
+ if mpl.rcParams['docstring.hardcopy'] else
1851
+ 'Properties:\n' + '\n'.join(ai.pprint_setters(leadingspace=4)))
1852
+
1853
+ # We defer this to the end of them module, because it needs ArtistInspector
1854
+ # to be defined.
1855
+ Artist._update_set_signature_and_docstring()
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/artist.pyi ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .axes._base import _AxesBase
2
+ from .backend_bases import RendererBase, MouseEvent
3
+ from .figure import Figure, SubFigure
4
+ from .path import Path
5
+ from .patches import Patch
6
+ from .patheffects import AbstractPathEffect
7
+ from .transforms import (
8
+ BboxBase,
9
+ Bbox,
10
+ Transform,
11
+ TransformedPatchPath,
12
+ TransformedPath,
13
+ )
14
+
15
+ import numpy as np
16
+
17
+ from collections.abc import Callable, Iterable
18
+ from typing import Any, Literal, NamedTuple, TextIO, overload, TypeVar
19
+ from numpy.typing import ArrayLike
20
+
21
+ _T_Artist = TypeVar("_T_Artist", bound=Artist)
22
+
23
+ def allow_rasterization(draw): ...
24
+
25
+ class _XYPair(NamedTuple):
26
+ x: ArrayLike
27
+ y: ArrayLike
28
+
29
+ class _Unset: ...
30
+
31
+ class Artist:
32
+ zorder: float
33
+ stale_callback: Callable[[Artist, bool], None] | None
34
+ @property
35
+ def figure(self) -> Figure | SubFigure: ...
36
+ clipbox: BboxBase | None
37
+ def __init__(self) -> None: ...
38
+ def remove(self) -> None: ...
39
+ def have_units(self) -> bool: ...
40
+ # TODO units
41
+ def convert_xunits(self, x): ...
42
+ def convert_yunits(self, y): ...
43
+ @property
44
+ def axes(self) -> _AxesBase | None: ...
45
+ @axes.setter
46
+ def axes(self, new_axes: _AxesBase | None) -> None: ...
47
+ @property
48
+ def stale(self) -> bool: ...
49
+ @stale.setter
50
+ def stale(self, val: bool) -> None: ...
51
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
52
+ def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ...
53
+ def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
54
+ def remove_callback(self, oid: int) -> None: ...
55
+ def pchanged(self) -> None: ...
56
+ def is_transform_set(self) -> bool: ...
57
+ def set_transform(self, t: Transform | None) -> None: ...
58
+ def get_transform(self) -> Transform: ...
59
+ def get_children(self) -> list[Artist]: ...
60
+ # TODO can these dicts be type narrowed? e.g. str keys
61
+ def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ...
62
+ def pickable(self) -> bool: ...
63
+ def pick(self, mouseevent: MouseEvent) -> None: ...
64
+ def set_picker(
65
+ self,
66
+ picker: None
67
+ | bool
68
+ | float
69
+ | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]],
70
+ ) -> None: ...
71
+ def get_picker(
72
+ self,
73
+ ) -> None | bool | float | Callable[
74
+ [Artist, MouseEvent], tuple[bool, dict[Any, Any]]
75
+ ]: ...
76
+ def get_url(self) -> str | None: ...
77
+ def set_url(self, url: str | None) -> None: ...
78
+ def get_gid(self) -> str | None: ...
79
+ def set_gid(self, gid: str | None) -> None: ...
80
+ def get_snap(self) -> bool | None: ...
81
+ def set_snap(self, snap: bool | None) -> None: ...
82
+ def get_sketch_params(self) -> tuple[float, float, float] | None: ...
83
+ def set_sketch_params(
84
+ self,
85
+ scale: float | None = ...,
86
+ length: float | None = ...,
87
+ randomness: float | None = ...,
88
+ ) -> None: ...
89
+ def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ...
90
+ def get_path_effects(self) -> list[AbstractPathEffect]: ...
91
+ @overload
92
+ def get_figure(self, root: Literal[True]) -> Figure | None: ...
93
+ @overload
94
+ def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ...
95
+ @overload
96
+ def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ...
97
+ def set_figure(self, fig: Figure | SubFigure) -> None: ...
98
+ def set_clip_box(self, clipbox: BboxBase | None) -> None: ...
99
+ def set_clip_path(
100
+ self,
101
+ path: Patch | Path | TransformedPath | TransformedPatchPath | None,
102
+ transform: Transform | None = ...,
103
+ ) -> None: ...
104
+ def get_alpha(self) -> float | None: ...
105
+ def get_visible(self) -> bool: ...
106
+ def get_animated(self) -> bool: ...
107
+ def get_in_layout(self) -> bool: ...
108
+ def get_clip_on(self) -> bool: ...
109
+ def get_clip_box(self) -> Bbox | None: ...
110
+ def get_clip_path(
111
+ self,
112
+ ) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ...
113
+ def get_transformed_clip_path_and_affine(
114
+ self,
115
+ ) -> tuple[None, None] | tuple[Path, Transform]: ...
116
+ def set_clip_on(self, b: bool) -> None: ...
117
+ def get_rasterized(self) -> bool: ...
118
+ def set_rasterized(self, rasterized: bool) -> None: ...
119
+ def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ...
120
+ def set_agg_filter(
121
+ self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None
122
+ ) -> None: ...
123
+ def draw(self, renderer: RendererBase) -> None: ...
124
+ def set_alpha(self, alpha: float | None) -> None: ...
125
+ def set_visible(self, b: bool) -> None: ...
126
+ def set_animated(self, b: bool) -> None: ...
127
+ def set_in_layout(self, in_layout: bool) -> None: ...
128
+ def get_label(self) -> object: ...
129
+ def set_label(self, s: object) -> None: ...
130
+ def get_zorder(self) -> float: ...
131
+ def set_zorder(self, level: float) -> None: ...
132
+ @property
133
+ def sticky_edges(self) -> _XYPair: ...
134
+ def update_from(self, other: Artist) -> None: ...
135
+ def properties(self) -> dict[str, Any]: ...
136
+ def update(self, props: dict[str, Any]) -> list[Any]: ...
137
+ def _internal_update(self, kwargs: Any) -> list[Any]: ...
138
+ def set(self, **kwargs: Any) -> list[Any]: ...
139
+
140
+ @overload
141
+ def findobj(
142
+ self,
143
+ match: None | Callable[[Artist], bool] = ...,
144
+ include_self: bool = ...,
145
+ ) -> list[Artist]: ...
146
+
147
+ @overload
148
+ def findobj(
149
+ self,
150
+ match: type[_T_Artist],
151
+ include_self: bool = ...,
152
+ ) -> list[_T_Artist]: ...
153
+
154
+ def get_cursor_data(self, event: MouseEvent) -> Any: ...
155
+ def format_cursor_data(self, data: Any) -> str: ...
156
+ def get_mouseover(self) -> bool: ...
157
+ def set_mouseover(self, mouseover: bool) -> None: ...
158
+ @property
159
+ def mouseover(self) -> bool: ...
160
+ @mouseover.setter
161
+ def mouseover(self, mouseover: bool) -> None: ...
162
+
163
+ class ArtistInspector:
164
+ oorig: Artist | type[Artist]
165
+ o: type[Artist]
166
+ aliasd: dict[str, set[str]]
167
+ def __init__(
168
+ self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]]
169
+ ) -> None: ...
170
+ def get_aliases(self) -> dict[str, set[str]]: ...
171
+ def get_valid_values(self, attr: str) -> str | None: ...
172
+ def get_setters(self) -> list[str]: ...
173
+ @staticmethod
174
+ def number_of_parameters(func: Callable) -> int: ...
175
+ @staticmethod
176
+ def is_alias(method: Callable) -> bool: ...
177
+ def aliased_name(self, s: str) -> str: ...
178
+ def aliased_name_rest(self, s: str, target: str) -> str: ...
179
+ @overload
180
+ def pprint_setters(
181
+ self, prop: None = ..., leadingspace: int = ...
182
+ ) -> list[str]: ...
183
+ @overload
184
+ def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ...
185
+ @overload
186
+ def pprint_setters_rest(
187
+ self, prop: None = ..., leadingspace: int = ...
188
+ ) -> list[str]: ...
189
+ @overload
190
+ def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ...
191
+ def properties(self) -> dict[str, Any]: ...
192
+ def pprint_getters(self) -> list[str]: ...
193
+
194
+ def getp(obj: Artist, property: str | None = ...) -> Any: ...
195
+
196
+ get = getp
197
+
198
+ def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ...
199
+ def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _base
2
+ from ._axes import Axes
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
workspace/outputs/audit_venv/lib/python3.11/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]: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_axes.py ADDED
The diff for this file is too large to render. See raw diff
 
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_axes.pyi ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ FillBetweenPolyCollection,
9
+ LineCollection,
10
+ PathCollection,
11
+ PolyCollection,
12
+ EventCollection,
13
+ QuadMesh,
14
+ )
15
+ from matplotlib.colorizer import Colorizer
16
+ from matplotlib.colors import Colormap, Normalize
17
+ from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
18
+ from matplotlib.contour import ContourSet, QuadContourSet
19
+ from matplotlib.image import AxesImage, PcolorImage
20
+ from matplotlib.inset import InsetIndicator
21
+ from matplotlib.legend import Legend
22
+ from matplotlib.legend_handler import HandlerBase
23
+ from matplotlib.lines import Line2D, AxLine
24
+ from matplotlib.mlab import GaussianKDE
25
+ from matplotlib.patches import Rectangle, FancyArrow, Polygon, StepPatch, Wedge
26
+ from matplotlib.quiver import Quiver, QuiverKey, Barbs
27
+ from matplotlib.text import Annotation, Text
28
+ from matplotlib.transforms import Transform
29
+ from matplotlib.typing import CoordsType
30
+ import matplotlib.tri as mtri
31
+ import matplotlib.table as mtable
32
+ import matplotlib.stackplot as mstack
33
+ import matplotlib.streamplot as mstream
34
+
35
+ import datetime
36
+ import PIL.Image
37
+ from collections.abc import Callable, Iterable, Sequence
38
+ from typing import Any, Literal, overload
39
+ import numpy as np
40
+ from numpy.typing import ArrayLike
41
+ from matplotlib.typing import ColorType, MarkerType, LineStyleType
42
+
43
+ class Axes(_AxesBase):
44
+ def get_title(self, loc: Literal["left", "center", "right"] = ...) -> str: ...
45
+ def set_title(
46
+ self,
47
+ label: str,
48
+ fontdict: dict[str, Any] | None = ...,
49
+ loc: Literal["left", "center", "right"] | None = ...,
50
+ pad: float | None = ...,
51
+ *,
52
+ y: float | None = ...,
53
+ **kwargs
54
+ ) -> Text: ...
55
+ def get_legend_handles_labels(
56
+ self, legend_handler_map: dict[type, HandlerBase] | None = ...
57
+ ) -> tuple[list[Artist], list[Any]]: ...
58
+ legend_: Legend | None
59
+
60
+ @overload
61
+ def legend(self) -> Legend: ...
62
+ @overload
63
+ def legend(self, handles: Iterable[Artist | tuple[Artist, ...]], labels: Iterable[str], **kwargs) -> Legend: ...
64
+ @overload
65
+ def legend(self, *, handles: Iterable[Artist | tuple[Artist, ...]], **kwargs) -> Legend: ...
66
+ @overload
67
+ def legend(self, labels: Iterable[str], **kwargs) -> Legend: ...
68
+ @overload
69
+ def legend(self, **kwargs) -> Legend: ...
70
+
71
+ def inset_axes(
72
+ self,
73
+ bounds: tuple[float, float, float, float],
74
+ *,
75
+ transform: Transform | None = ...,
76
+ zorder: float = ...,
77
+ **kwargs
78
+ ) -> Axes: ...
79
+ def indicate_inset(
80
+ self,
81
+ bounds: tuple[float, float, float, float] | None = ...,
82
+ inset_ax: Axes | None = ...,
83
+ *,
84
+ transform: Transform | None = ...,
85
+ facecolor: ColorType = ...,
86
+ edgecolor: ColorType = ...,
87
+ alpha: float = ...,
88
+ zorder: float | None = ...,
89
+ **kwargs
90
+ ) -> InsetIndicator: ...
91
+ def indicate_inset_zoom(self, inset_ax: Axes, **kwargs) -> InsetIndicator: ...
92
+ def secondary_xaxis(
93
+ self,
94
+ location: Literal["top", "bottom"] | float,
95
+ functions: tuple[
96
+ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
97
+ ]
98
+ | Transform
99
+ | None = ...,
100
+ *,
101
+ transform: Transform | None = ...,
102
+ **kwargs
103
+ ) -> SecondaryAxis: ...
104
+ def secondary_yaxis(
105
+ self,
106
+ location: Literal["left", "right"] | float,
107
+ functions: tuple[
108
+ Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]
109
+ ]
110
+ | Transform
111
+ | None = ...,
112
+ *,
113
+ transform: Transform | None = ...,
114
+ **kwargs
115
+ ) -> SecondaryAxis: ...
116
+ def text(
117
+ self,
118
+ x: float,
119
+ y: float,
120
+ s: str,
121
+ fontdict: dict[str, Any] | None = ...,
122
+ **kwargs
123
+ ) -> Text: ...
124
+ def annotate(
125
+ self,
126
+ text: str,
127
+ xy: tuple[float, float],
128
+ xytext: tuple[float, float] | None = ...,
129
+ xycoords: CoordsType = ...,
130
+ textcoords: CoordsType | None = ...,
131
+ arrowprops: dict[str, Any] | None = ...,
132
+ annotation_clip: bool | None = ...,
133
+ **kwargs
134
+ ) -> Annotation: ...
135
+ def axhline(
136
+ self, y: float = ..., xmin: float = ..., xmax: float = ..., **kwargs
137
+ ) -> Line2D: ...
138
+ def axvline(
139
+ self, x: float = ..., ymin: float = ..., ymax: float = ..., **kwargs
140
+ ) -> Line2D: ...
141
+
142
+ # TODO: Could separate the xy2 and slope signatures
143
+ def axline(
144
+ self,
145
+ xy1: tuple[float, float],
146
+ xy2: tuple[float, float] | None = ...,
147
+ *,
148
+ slope: float | None = ...,
149
+ **kwargs
150
+ ) -> AxLine: ...
151
+ def axhspan(
152
+ self, ymin: float, ymax: float, xmin: float = ..., xmax: float = ..., **kwargs
153
+ ) -> Rectangle: ...
154
+ def axvspan(
155
+ self, xmin: float, xmax: float, ymin: float = ..., ymax: float = ..., **kwargs
156
+ ) -> Rectangle: ...
157
+ def hlines(
158
+ self,
159
+ y: float | ArrayLike,
160
+ xmin: float | ArrayLike,
161
+ xmax: float | ArrayLike,
162
+ colors: ColorType | Sequence[ColorType] | None = ...,
163
+ linestyles: LineStyleType = ...,
164
+ *,
165
+ label: str = ...,
166
+ data=...,
167
+ **kwargs
168
+ ) -> LineCollection: ...
169
+ def vlines(
170
+ self,
171
+ x: float | ArrayLike,
172
+ ymin: float | ArrayLike,
173
+ ymax: float | ArrayLike,
174
+ colors: ColorType | Sequence[ColorType] | None = ...,
175
+ linestyles: LineStyleType = ...,
176
+ *,
177
+ label: str = ...,
178
+ data=...,
179
+ **kwargs
180
+ ) -> LineCollection: ...
181
+ def eventplot(
182
+ self,
183
+ positions: ArrayLike | Sequence[ArrayLike],
184
+ *,
185
+ orientation: Literal["horizontal", "vertical"] = ...,
186
+ lineoffsets: float | Sequence[float] = ...,
187
+ linelengths: float | Sequence[float] = ...,
188
+ linewidths: float | Sequence[float] | None = ...,
189
+ colors: ColorType | Sequence[ColorType] | None = ...,
190
+ alpha: float | Sequence[float] | None = ...,
191
+ linestyles: LineStyleType | Sequence[LineStyleType] = ...,
192
+ data=...,
193
+ **kwargs
194
+ ) -> EventCollection: ...
195
+ def plot(
196
+ self,
197
+ *args: float | ArrayLike | str,
198
+ scalex: bool = ...,
199
+ scaley: bool = ...,
200
+ data=...,
201
+ **kwargs
202
+ ) -> list[Line2D]: ...
203
+ def plot_date(
204
+ self,
205
+ x: ArrayLike,
206
+ y: ArrayLike,
207
+ fmt: str = ...,
208
+ tz: str | datetime.tzinfo | None = ...,
209
+ xdate: bool = ...,
210
+ ydate: bool = ...,
211
+ *,
212
+ data=...,
213
+ **kwargs
214
+ ) -> list[Line2D]: ...
215
+ def loglog(self, *args, **kwargs) -> list[Line2D]: ...
216
+ def semilogx(self, *args, **kwargs) -> list[Line2D]: ...
217
+ def semilogy(self, *args, **kwargs) -> list[Line2D]: ...
218
+ def acorr(
219
+ self, x: ArrayLike, *, data=..., **kwargs
220
+ ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
221
+ def xcorr(
222
+ self,
223
+ x: ArrayLike,
224
+ y: ArrayLike,
225
+ *,
226
+ normed: bool = ...,
227
+ detrend: Callable[[ArrayLike], ArrayLike] = ...,
228
+ usevlines: bool = ...,
229
+ maxlags: int = ...,
230
+ data=...,
231
+ **kwargs
232
+ ) -> tuple[np.ndarray, np.ndarray, LineCollection | Line2D, Line2D | None]: ...
233
+ def step(
234
+ self,
235
+ x: ArrayLike,
236
+ y: ArrayLike,
237
+ *args,
238
+ where: Literal["pre", "post", "mid"] = ...,
239
+ data=...,
240
+ **kwargs
241
+ ) -> list[Line2D]: ...
242
+ def bar(
243
+ self,
244
+ x: float | ArrayLike,
245
+ height: float | ArrayLike,
246
+ width: float | ArrayLike = ...,
247
+ bottom: float | ArrayLike | None = ...,
248
+ *,
249
+ align: Literal["center", "edge"] = ...,
250
+ data=...,
251
+ **kwargs
252
+ ) -> BarContainer: ...
253
+ def barh(
254
+ self,
255
+ y: float | ArrayLike,
256
+ width: float | ArrayLike,
257
+ height: float | ArrayLike = ...,
258
+ left: float | ArrayLike | None = ...,
259
+ *,
260
+ align: Literal["center", "edge"] = ...,
261
+ data=...,
262
+ **kwargs
263
+ ) -> BarContainer: ...
264
+ def bar_label(
265
+ self,
266
+ container: BarContainer,
267
+ labels: ArrayLike | None = ...,
268
+ *,
269
+ fmt: str | Callable[[float], str] = ...,
270
+ label_type: Literal["center", "edge"] = ...,
271
+ padding: float = ...,
272
+ **kwargs
273
+ ) -> list[Annotation]: ...
274
+ def broken_barh(
275
+ self,
276
+ xranges: Sequence[tuple[float, float]],
277
+ yrange: tuple[float, float],
278
+ *,
279
+ data=...,
280
+ **kwargs
281
+ ) -> PolyCollection: ...
282
+ def stem(
283
+ self,
284
+ *args: ArrayLike | str,
285
+ linefmt: str | None = ...,
286
+ markerfmt: str | None = ...,
287
+ basefmt: str | None = ...,
288
+ bottom: float = ...,
289
+ label: str | None = ...,
290
+ orientation: Literal["vertical", "horizontal"] = ...,
291
+ data=...,
292
+ ) -> StemContainer: ...
293
+
294
+ # TODO: data kwarg preprocessor?
295
+ def pie(
296
+ self,
297
+ x: ArrayLike,
298
+ *,
299
+ explode: ArrayLike | None = ...,
300
+ labels: Sequence[str] | None = ...,
301
+ colors: ColorType | Sequence[ColorType] | None = ...,
302
+ autopct: str | Callable[[float], str] | None = ...,
303
+ pctdistance: float = ...,
304
+ shadow: bool = ...,
305
+ labeldistance: float | None = ...,
306
+ startangle: float = ...,
307
+ radius: float = ...,
308
+ counterclock: bool = ...,
309
+ wedgeprops: dict[str, Any] | None = ...,
310
+ textprops: dict[str, Any] | None = ...,
311
+ center: tuple[float, float] = ...,
312
+ frame: bool = ...,
313
+ rotatelabels: bool = ...,
314
+ normalize: bool = ...,
315
+ hatch: str | Sequence[str] | None = ...,
316
+ data=...,
317
+ ) -> tuple[list[Wedge], list[Text]] | tuple[
318
+ list[Wedge], list[Text], list[Text]
319
+ ]: ...
320
+ def errorbar(
321
+ self,
322
+ x: float | ArrayLike,
323
+ y: float | ArrayLike,
324
+ yerr: float | ArrayLike | None = ...,
325
+ xerr: float | ArrayLike | None = ...,
326
+ fmt: str = ...,
327
+ *,
328
+ ecolor: ColorType | None = ...,
329
+ elinewidth: float | None = ...,
330
+ capsize: float | None = ...,
331
+ barsabove: bool = ...,
332
+ lolims: bool | ArrayLike = ...,
333
+ uplims: bool | ArrayLike = ...,
334
+ xlolims: bool | ArrayLike = ...,
335
+ xuplims: bool | ArrayLike = ...,
336
+ errorevery: int | tuple[int, int] = ...,
337
+ capthick: float | None = ...,
338
+ data=...,
339
+ **kwargs
340
+ ) -> ErrorbarContainer: ...
341
+ def boxplot(
342
+ self,
343
+ x: ArrayLike | Sequence[ArrayLike],
344
+ *,
345
+ notch: bool | None = ...,
346
+ sym: str | None = ...,
347
+ vert: bool | None = ...,
348
+ orientation: Literal["vertical", "horizontal"] = ...,
349
+ whis: float | tuple[float, float] | None = ...,
350
+ positions: ArrayLike | None = ...,
351
+ widths: float | ArrayLike | None = ...,
352
+ patch_artist: bool | None = ...,
353
+ bootstrap: int | None = ...,
354
+ usermedians: ArrayLike | None = ...,
355
+ conf_intervals: ArrayLike | None = ...,
356
+ meanline: bool | None = ...,
357
+ showmeans: bool | None = ...,
358
+ showcaps: bool | None = ...,
359
+ showbox: bool | None = ...,
360
+ showfliers: bool | None = ...,
361
+ boxprops: dict[str, Any] | None = ...,
362
+ tick_labels: Sequence[str] | None = ...,
363
+ flierprops: dict[str, Any] | None = ...,
364
+ medianprops: dict[str, Any] | None = ...,
365
+ meanprops: dict[str, Any] | None = ...,
366
+ capprops: dict[str, Any] | None = ...,
367
+ whiskerprops: dict[str, Any] | None = ...,
368
+ manage_ticks: bool = ...,
369
+ autorange: bool = ...,
370
+ zorder: float | None = ...,
371
+ capwidths: float | ArrayLike | None = ...,
372
+ label: Sequence[str] | None = ...,
373
+ data=...,
374
+ ) -> dict[str, Any]: ...
375
+ def bxp(
376
+ self,
377
+ bxpstats: Sequence[dict[str, Any]],
378
+ positions: ArrayLike | None = ...,
379
+ *,
380
+ widths: float | ArrayLike | None = ...,
381
+ vert: bool | None = ...,
382
+ orientation: Literal["vertical", "horizontal"] = ...,
383
+ patch_artist: bool = ...,
384
+ shownotches: bool = ...,
385
+ showmeans: bool = ...,
386
+ showcaps: bool = ...,
387
+ showbox: bool = ...,
388
+ showfliers: bool = ...,
389
+ boxprops: dict[str, Any] | None = ...,
390
+ whiskerprops: dict[str, Any] | None = ...,
391
+ flierprops: dict[str, Any] | None = ...,
392
+ medianprops: dict[str, Any] | None = ...,
393
+ capprops: dict[str, Any] | None = ...,
394
+ meanprops: dict[str, Any] | None = ...,
395
+ meanline: bool = ...,
396
+ manage_ticks: bool = ...,
397
+ zorder: float | None = ...,
398
+ capwidths: float | ArrayLike | None = ...,
399
+ label: Sequence[str] | None = ...,
400
+ ) -> dict[str, Any]: ...
401
+ def scatter(
402
+ self,
403
+ x: float | ArrayLike,
404
+ y: float | ArrayLike,
405
+ s: float | ArrayLike | None = ...,
406
+ c: ArrayLike | Sequence[ColorType] | ColorType | None = ...,
407
+ *,
408
+ marker: MarkerType | None = ...,
409
+ cmap: str | Colormap | None = ...,
410
+ norm: str | Normalize | None = ...,
411
+ vmin: float | None = ...,
412
+ vmax: float | None = ...,
413
+ alpha: float | None = ...,
414
+ linewidths: float | Sequence[float] | None = ...,
415
+ edgecolors: Literal["face", "none"] | ColorType | Sequence[ColorType] | None = ...,
416
+ colorizer: Colorizer | None = ...,
417
+ plotnonfinite: bool = ...,
418
+ data=...,
419
+ **kwargs
420
+ ) -> PathCollection: ...
421
+ def hexbin(
422
+ self,
423
+ x: ArrayLike,
424
+ y: ArrayLike,
425
+ C: ArrayLike | None = ...,
426
+ *,
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
+ colorizer: Colorizer | None = ...,
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
+ ) -> FillBetweenPolyCollection: ...
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
+ ) -> FillBetweenPolyCollection: ...
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
+ colorizer: Colorizer | None = ...,
491
+ origin: Literal["upper", "lower"] | None = ...,
492
+ extent: tuple[float, float, float, float] | None = ...,
493
+ interpolation_stage: Literal["data", "rgba", "auto"] | None = ...,
494
+ filternorm: bool = ...,
495
+ filterrad: float = ...,
496
+ resample: bool | None = ...,
497
+ url: str | None = ...,
498
+ data=...,
499
+ **kwargs
500
+ ) -> AxesImage: ...
501
+ def pcolor(
502
+ self,
503
+ *args: ArrayLike,
504
+ shading: Literal["flat", "nearest", "auto"] | None = ...,
505
+ alpha: float | None = ...,
506
+ norm: str | Normalize | None = ...,
507
+ cmap: str | Colormap | None = ...,
508
+ vmin: float | None = ...,
509
+ vmax: float | None = ...,
510
+ colorizer: Colorizer | None = ...,
511
+ data=...,
512
+ **kwargs
513
+ ) -> Collection: ...
514
+ def pcolormesh(
515
+ self,
516
+ *args: ArrayLike,
517
+ alpha: float | None = ...,
518
+ norm: str | Normalize | None = ...,
519
+ cmap: str | Colormap | None = ...,
520
+ vmin: float | None = ...,
521
+ vmax: float | None = ...,
522
+ colorizer: Colorizer | None = ...,
523
+ shading: Literal["flat", "nearest", "gouraud", "auto"] | None = ...,
524
+ antialiased: bool = ...,
525
+ data=...,
526
+ **kwargs
527
+ ) -> QuadMesh: ...
528
+ def pcolorfast(
529
+ self,
530
+ *args: ArrayLike | tuple[float, float],
531
+ alpha: float | None = ...,
532
+ norm: str | Normalize | None = ...,
533
+ cmap: str | Colormap | None = ...,
534
+ vmin: float | None = ...,
535
+ vmax: float | None = ...,
536
+ colorizer: Colorizer | None = ...,
537
+ data=...,
538
+ **kwargs
539
+ ) -> AxesImage | PcolorImage | QuadMesh: ...
540
+ def contour(self, *args, data=..., **kwargs) -> QuadContourSet: ...
541
+ def contourf(self, *args, data=..., **kwargs) -> QuadContourSet: ...
542
+ def clabel(
543
+ self, CS: ContourSet, levels: ArrayLike | None = ..., **kwargs
544
+ ) -> list[Text]: ...
545
+ def hist(
546
+ self,
547
+ x: ArrayLike | Sequence[ArrayLike],
548
+ bins: int | Sequence[float] | str | None = ...,
549
+ *,
550
+ range: tuple[float, float] | None = ...,
551
+ density: bool = ...,
552
+ weights: ArrayLike | None = ...,
553
+ cumulative: bool | float = ...,
554
+ bottom: ArrayLike | float | None = ...,
555
+ histtype: Literal["bar", "barstacked", "step", "stepfilled"] = ...,
556
+ align: Literal["left", "mid", "right"] = ...,
557
+ orientation: Literal["vertical", "horizontal"] = ...,
558
+ rwidth: float | None = ...,
559
+ log: bool = ...,
560
+ color: ColorType | Sequence[ColorType] | None = ...,
561
+ label: str | Sequence[str] | None = ...,
562
+ stacked: bool = ...,
563
+ data=...,
564
+ **kwargs
565
+ ) -> tuple[
566
+ np.ndarray | list[np.ndarray],
567
+ np.ndarray,
568
+ BarContainer | Polygon | list[BarContainer | Polygon],
569
+ ]: ...
570
+ def stairs(
571
+ self,
572
+ values: ArrayLike,
573
+ edges: ArrayLike | None = ...,
574
+ *,
575
+ orientation: Literal["vertical", "horizontal"] = ...,
576
+ baseline: float | ArrayLike | None = ...,
577
+ fill: bool = ...,
578
+ data=...,
579
+ **kwargs
580
+ ) -> StepPatch: ...
581
+ def hist2d(
582
+ self,
583
+ x: ArrayLike,
584
+ y: ArrayLike,
585
+ bins: None
586
+ | int
587
+ | tuple[int, int]
588
+ | ArrayLike
589
+ | tuple[ArrayLike, ArrayLike] = ...,
590
+ *,
591
+ range: ArrayLike | None = ...,
592
+ density: bool = ...,
593
+ weights: ArrayLike | None = ...,
594
+ cmin: float | None = ...,
595
+ cmax: float | None = ...,
596
+ data=...,
597
+ **kwargs
598
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, QuadMesh]: ...
599
+ def ecdf(
600
+ self,
601
+ x: ArrayLike,
602
+ weights: ArrayLike | None = ...,
603
+ *,
604
+ complementary: bool=...,
605
+ orientation: Literal["vertical", "horizontal"]=...,
606
+ compress: bool=...,
607
+ data=...,
608
+ **kwargs
609
+ ) -> Line2D: ...
610
+ def psd(
611
+ self,
612
+ x: ArrayLike,
613
+ *,
614
+ NFFT: int | None = ...,
615
+ Fs: float | None = ...,
616
+ Fc: int | None = ...,
617
+ detrend: Literal["none", "mean", "linear"]
618
+ | Callable[[ArrayLike], ArrayLike]
619
+ | None = ...,
620
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
621
+ noverlap: int | None = ...,
622
+ pad_to: int | None = ...,
623
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
624
+ scale_by_freq: bool | None = ...,
625
+ return_line: bool | None = ...,
626
+ data=...,
627
+ **kwargs
628
+ ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
629
+ def csd(
630
+ self,
631
+ x: ArrayLike,
632
+ y: ArrayLike,
633
+ *,
634
+ NFFT: int | None = ...,
635
+ Fs: float | None = ...,
636
+ Fc: int | None = ...,
637
+ detrend: Literal["none", "mean", "linear"]
638
+ | Callable[[ArrayLike], ArrayLike]
639
+ | None = ...,
640
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
641
+ noverlap: int | None = ...,
642
+ pad_to: int | None = ...,
643
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
644
+ scale_by_freq: bool | None = ...,
645
+ return_line: bool | None = ...,
646
+ data=...,
647
+ **kwargs
648
+ ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, Line2D]: ...
649
+ def magnitude_spectrum(
650
+ self,
651
+ x: ArrayLike,
652
+ *,
653
+ Fs: float | None = ...,
654
+ Fc: int | None = ...,
655
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
656
+ pad_to: int | None = ...,
657
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
658
+ scale: Literal["default", "linear", "dB"] | None = ...,
659
+ data=...,
660
+ **kwargs
661
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
662
+ def angle_spectrum(
663
+ self,
664
+ x: ArrayLike,
665
+ *,
666
+ Fs: float | None = ...,
667
+ Fc: int | None = ...,
668
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
669
+ pad_to: int | None = ...,
670
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
671
+ data=...,
672
+ **kwargs
673
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
674
+ def phase_spectrum(
675
+ self,
676
+ x: ArrayLike,
677
+ *,
678
+ Fs: float | None = ...,
679
+ Fc: int | None = ...,
680
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
681
+ pad_to: int | None = ...,
682
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
683
+ data=...,
684
+ **kwargs
685
+ ) -> tuple[np.ndarray, np.ndarray, Line2D]: ...
686
+ def cohere(
687
+ self,
688
+ x: ArrayLike,
689
+ y: ArrayLike,
690
+ *,
691
+ NFFT: int = ...,
692
+ Fs: float = ...,
693
+ Fc: int = ...,
694
+ detrend: Literal["none", "mean", "linear"]
695
+ | Callable[[ArrayLike], ArrayLike] = ...,
696
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike = ...,
697
+ noverlap: int = ...,
698
+ pad_to: int | None = ...,
699
+ sides: Literal["default", "onesided", "twosided"] = ...,
700
+ scale_by_freq: bool | None = ...,
701
+ data=...,
702
+ **kwargs
703
+ ) -> tuple[np.ndarray, np.ndarray]: ...
704
+ def specgram(
705
+ self,
706
+ x: ArrayLike,
707
+ *,
708
+ NFFT: int | None = ...,
709
+ Fs: float | None = ...,
710
+ Fc: int | None = ...,
711
+ detrend: Literal["none", "mean", "linear"]
712
+ | Callable[[ArrayLike], ArrayLike]
713
+ | None = ...,
714
+ window: Callable[[ArrayLike], ArrayLike] | ArrayLike | None = ...,
715
+ noverlap: int | None = ...,
716
+ cmap: str | Colormap | None = ...,
717
+ xextent: tuple[float, float] | None = ...,
718
+ pad_to: int | None = ...,
719
+ sides: Literal["default", "onesided", "twosided"] | None = ...,
720
+ scale_by_freq: bool | None = ...,
721
+ mode: Literal["default", "psd", "magnitude", "angle", "phase"] | None = ...,
722
+ scale: Literal["default", "linear", "dB"] | None = ...,
723
+ vmin: float | None = ...,
724
+ vmax: float | None = ...,
725
+ data=...,
726
+ **kwargs
727
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, AxesImage]: ...
728
+ def spy(
729
+ self,
730
+ Z: ArrayLike,
731
+ *,
732
+ precision: float | Literal["present"] = ...,
733
+ marker: str | None = ...,
734
+ markersize: float | None = ...,
735
+ aspect: Literal["equal", "auto"] | float | None = ...,
736
+ origin: Literal["upper", "lower"] = ...,
737
+ **kwargs
738
+ ) -> AxesImage: ...
739
+ def matshow(self, Z: ArrayLike, **kwargs) -> AxesImage: ...
740
+ def violinplot(
741
+ self,
742
+ dataset: ArrayLike | Sequence[ArrayLike],
743
+ positions: ArrayLike | None = ...,
744
+ *,
745
+ vert: bool | None = ...,
746
+ orientation: Literal["vertical", "horizontal"] = ...,
747
+ widths: float | ArrayLike = ...,
748
+ showmeans: bool = ...,
749
+ showextrema: bool = ...,
750
+ showmedians: bool = ...,
751
+ quantiles: Sequence[float | Sequence[float]] | None = ...,
752
+ points: int = ...,
753
+ bw_method: Literal["scott", "silverman"]
754
+ | float
755
+ | Callable[[GaussianKDE], float]
756
+ | None = ...,
757
+ side: Literal["both", "low", "high"] = ...,
758
+ data=...,
759
+ ) -> dict[str, Collection]: ...
760
+ def violin(
761
+ self,
762
+ vpstats: Sequence[dict[str, Any]],
763
+ positions: ArrayLike | None = ...,
764
+ *,
765
+ vert: bool | None = ...,
766
+ orientation: Literal["vertical", "horizontal"] = ...,
767
+ widths: float | ArrayLike = ...,
768
+ showmeans: bool = ...,
769
+ showextrema: bool = ...,
770
+ showmedians: bool = ...,
771
+ side: Literal["both", "low", "high"] = ...,
772
+ ) -> dict[str, Collection]: ...
773
+
774
+ table = mtable.table
775
+ stackplot = mstack.stackplot
776
+ streamplot = mstream.streamplot
777
+ tricontour = mtri.tricontour
778
+ tricontourf = mtri.tricontourf
779
+ tripcolor = mtri.tripcolor
780
+ triplot = mtri.triplot
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_base.py ADDED
The diff for this file is too large to render. See raw diff
 
workspace/outputs/audit_venv/lib/python3.11/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.colorizer import ColorizingArtist
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, SubFigure
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 | SubFigure) -> 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) -> 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 | None: ...
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: ColorizingArtist) -> 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: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axes/_secondary_axes.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ fig = self._parent.get_figure(root=False)
31
+ if self._orientation == 'x':
32
+ super().__init__(fig, [0, 1., 1, 0.0001], **kwargs)
33
+ self._axis = self.xaxis
34
+ self._locstrings = ['top', 'bottom']
35
+ self._otherstrings = ['left', 'right']
36
+ else: # 'y'
37
+ super().__init__(fig, [0, 1., 0.0001, 1], **kwargs)
38
+ self._axis = self.yaxis
39
+ self._locstrings = ['right', 'left']
40
+ self._otherstrings = ['top', 'bottom']
41
+ self._parentscale = None
42
+ # this gets positioned w/o constrained_layout so exclude:
43
+
44
+ self.set_location(location, transform)
45
+ self.set_functions(functions)
46
+
47
+ # styling:
48
+ otheraxis = self.yaxis if self._orientation == 'x' else self.xaxis
49
+ otheraxis.set_major_locator(mticker.NullLocator())
50
+ otheraxis.set_ticks_position('none')
51
+
52
+ self.spines[self._otherstrings].set_visible(False)
53
+ self.spines[self._locstrings].set_visible(True)
54
+
55
+ if self._pos < 0.5:
56
+ # flip the location strings...
57
+ self._locstrings = self._locstrings[::-1]
58
+ self.set_alignment(self._locstrings[0])
59
+
60
+ def set_alignment(self, align):
61
+ """
62
+ Set if axes spine and labels are drawn at top or bottom (or left/right)
63
+ of the Axes.
64
+
65
+ Parameters
66
+ ----------
67
+ align : {'top', 'bottom', 'left', 'right'}
68
+ Either 'top' or 'bottom' for orientation='x' or
69
+ 'left' or 'right' for orientation='y' axis.
70
+ """
71
+ _api.check_in_list(self._locstrings, align=align)
72
+ if align == self._locstrings[1]: # Need to change the orientation.
73
+ self._locstrings = self._locstrings[::-1]
74
+ self.spines[self._locstrings[0]].set_visible(True)
75
+ self.spines[self._locstrings[1]].set_visible(False)
76
+ self._axis.set_ticks_position(align)
77
+ self._axis.set_label_position(align)
78
+
79
+ def set_location(self, location, transform=None):
80
+ """
81
+ Set the vertical or horizontal location of the axes in
82
+ parent-normalized coordinates.
83
+
84
+ Parameters
85
+ ----------
86
+ location : {'top', 'bottom', 'left', 'right'} or float
87
+ The position to put the secondary axis. Strings can be 'top' or
88
+ 'bottom' for orientation='x' and 'right' or 'left' for
89
+ orientation='y'. A float indicates the relative position on the
90
+ parent Axes to put the new Axes, 0.0 being the bottom (or left)
91
+ and 1.0 being the top (or right).
92
+
93
+ transform : `.Transform`, optional
94
+ Transform for the location to use. Defaults to
95
+ the parent's ``transAxes``, so locations are normally relative to
96
+ the parent axes.
97
+
98
+ .. versionadded:: 3.9
99
+ """
100
+
101
+ _api.check_isinstance((transforms.Transform, None), transform=transform)
102
+
103
+ # This puts the rectangle into figure-relative coordinates.
104
+ if isinstance(location, str):
105
+ _api.check_in_list(self._locstrings, location=location)
106
+ self._pos = 1. if location in ('top', 'right') else 0.
107
+ elif isinstance(location, numbers.Real):
108
+ self._pos = location
109
+ else:
110
+ raise ValueError(
111
+ f"location must be {self._locstrings[0]!r}, "
112
+ f"{self._locstrings[1]!r}, or a float, not {location!r}")
113
+
114
+ self._loc = location
115
+
116
+ if self._orientation == 'x':
117
+ # An x-secondary axes is like an inset axes from x = 0 to x = 1 and
118
+ # from y = pos to y = pos + eps, in the parent's transAxes coords.
119
+ bounds = [0, self._pos, 1., 1e-10]
120
+
121
+ # If a transformation is provided, use its y component rather than
122
+ # the parent's transAxes. This can be used to place axes in the data
123
+ # coords, for instance.
124
+ if transform is not None:
125
+ transform = transforms.blended_transform_factory(
126
+ self._parent.transAxes, transform)
127
+ else: # 'y'
128
+ bounds = [self._pos, 0, 1e-10, 1]
129
+ if transform is not None:
130
+ transform = transforms.blended_transform_factory(
131
+ transform, self._parent.transAxes) # Use provided x axis
132
+
133
+ # If no transform is provided, use the parent's transAxes
134
+ if transform is None:
135
+ transform = self._parent.transAxes
136
+
137
+ # this locator lets the axes move in the parent axes coordinates.
138
+ # so it never needs to know where the parent is explicitly in
139
+ # figure coordinates.
140
+ # it gets called in ax.apply_aspect() (of all places)
141
+ self.set_axes_locator(_TransformedBoundsLocator(bounds, transform))
142
+
143
+ def apply_aspect(self, position=None):
144
+ # docstring inherited.
145
+ self._set_lims()
146
+ super().apply_aspect(position)
147
+
148
+ @_docstring.copy(Axis.set_ticks)
149
+ def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
150
+ ret = self._axis.set_ticks(ticks, labels, minor=minor, **kwargs)
151
+ self.stale = True
152
+ self._ticks_set = True
153
+ return ret
154
+
155
+ def set_functions(self, functions):
156
+ """
157
+ Set how the secondary axis converts limits from the parent Axes.
158
+
159
+ Parameters
160
+ ----------
161
+ functions : 2-tuple of func, or `Transform` with an inverse.
162
+ Transform between the parent axis values and the secondary axis
163
+ values.
164
+
165
+ If supplied as a 2-tuple of functions, the first function is
166
+ the forward transform function and the second is the inverse
167
+ transform.
168
+
169
+ If a transform is supplied, then the transform must have an
170
+ inverse.
171
+ """
172
+
173
+ if (isinstance(functions, tuple) and len(functions) == 2 and
174
+ callable(functions[0]) and callable(functions[1])):
175
+ # make an arbitrary convert from a two-tuple of functions
176
+ # forward and inverse.
177
+ self._functions = functions
178
+ elif isinstance(functions, Transform):
179
+ self._functions = (
180
+ functions.transform,
181
+ lambda x: functions.inverted().transform(x)
182
+ )
183
+ elif functions is None:
184
+ self._functions = (lambda x: x, lambda x: x)
185
+ else:
186
+ raise ValueError('functions argument of secondary Axes '
187
+ 'must be a two-tuple of callable functions '
188
+ 'with the first function being the transform '
189
+ 'and the second being the inverse')
190
+ self._set_scale()
191
+
192
+ def draw(self, renderer):
193
+ """
194
+ Draw the secondary Axes.
195
+
196
+ Consults the parent Axes for its limits and converts them
197
+ using the converter specified by
198
+ `~.axes._secondary_axes.set_functions` (or *functions*
199
+ parameter when Axes initialized.)
200
+ """
201
+ self._set_lims()
202
+ # this sets the scale in case the parent has set its scale.
203
+ self._set_scale()
204
+ super().draw(renderer)
205
+
206
+ def _set_scale(self):
207
+ """
208
+ Check if parent has set its scale
209
+ """
210
+
211
+ if self._orientation == 'x':
212
+ pscale = self._parent.xaxis.get_scale()
213
+ set_scale = self.set_xscale
214
+ else: # 'y'
215
+ pscale = self._parent.yaxis.get_scale()
216
+ set_scale = self.set_yscale
217
+ if pscale == self._parentscale:
218
+ return
219
+
220
+ if self._ticks_set:
221
+ ticks = self._axis.get_ticklocs()
222
+
223
+ # need to invert the roles here for the ticks to line up.
224
+ set_scale('functionlog' if pscale == 'log' else 'function',
225
+ functions=self._functions[::-1])
226
+
227
+ # OK, set_scale sets the locators, but if we've called
228
+ # axsecond.set_ticks, we want to keep those.
229
+ if self._ticks_set:
230
+ self._axis.set_major_locator(mticker.FixedLocator(ticks))
231
+
232
+ # If the parent scale doesn't change, we can skip this next time.
233
+ self._parentscale = pscale
234
+
235
+ def _set_lims(self):
236
+ """
237
+ Set the limits based on parent limits and the convert method
238
+ between the parent and this secondary Axes.
239
+ """
240
+ if self._orientation == 'x':
241
+ lims = self._parent.get_xlim()
242
+ set_lim = self.set_xlim
243
+ else: # 'y'
244
+ lims = self._parent.get_ylim()
245
+ set_lim = self.set_ylim
246
+ order = lims[0] < lims[1]
247
+ lims = self._functions[0](np.array(lims))
248
+ neworder = lims[0] < lims[1]
249
+ if neworder != order:
250
+ # Flip because the transform will take care of the flipping.
251
+ lims = lims[::-1]
252
+ set_lim(lims)
253
+
254
+ def set_aspect(self, *args, **kwargs):
255
+ """
256
+ Secondary Axes cannot set the aspect ratio, so calling this just
257
+ sets a warning.
258
+ """
259
+ _api.warn_external("Secondary Axes can't set the aspect ratio")
260
+
261
+ def set_color(self, color):
262
+ """
263
+ Change the color of the secondary Axes and all decorators.
264
+
265
+ Parameters
266
+ ----------
267
+ color : :mpltype:`color`
268
+ """
269
+ axis = self._axis_map[self._orientation]
270
+ axis.set_tick_params(colors=color)
271
+ for spine in self.spines.values():
272
+ if spine.axis is axis:
273
+ spine.set_color(color)
274
+ axis.label.set_color(color)
275
+
276
+
277
+ _secax_docstring = '''
278
+ Warnings
279
+ --------
280
+ This method is experimental as of 3.1, and the API may change.
281
+
282
+ Parameters
283
+ ----------
284
+ location : {'top', 'bottom', 'left', 'right'} or float
285
+ The position to put the secondary axis. Strings can be 'top' or
286
+ 'bottom' for orientation='x' and 'right' or 'left' for
287
+ orientation='y'. A float indicates the relative position on the
288
+ parent Axes to put the new Axes, 0.0 being the bottom (or left)
289
+ and 1.0 being the top (or right).
290
+
291
+ functions : 2-tuple of func, or Transform with an inverse
292
+
293
+ If a 2-tuple of functions, the user specifies the transform
294
+ function and its inverse. i.e.
295
+ ``functions=(lambda x: 2 / x, lambda x: 2 / x)`` would be an
296
+ reciprocal transform with a factor of 2. Both functions must accept
297
+ numpy arrays as input.
298
+
299
+ The user can also directly supply a subclass of
300
+ `.transforms.Transform` so long as it has an inverse.
301
+
302
+ See :doc:`/gallery/subplots_axes_and_figures/secondary_axis`
303
+ for examples of making these conversions.
304
+
305
+ transform : `.Transform`, optional
306
+ If specified, *location* will be
307
+ placed relative to this transform (in the direction of the axis)
308
+ rather than the parent's axis. i.e. a secondary x-axis will
309
+ use the provided y transform and the x transform of the parent.
310
+
311
+ .. versionadded:: 3.9
312
+
313
+ Returns
314
+ -------
315
+ ax : axes._secondary_axes.SecondaryAxis
316
+
317
+ Other Parameters
318
+ ----------------
319
+ **kwargs : `~matplotlib.axes.Axes` properties.
320
+ Other miscellaneous Axes parameters.
321
+ '''
322
+ _docstring.interpd.register(_secax_docstring=_secax_docstring)
workspace/outputs/audit_venv/lib/python3.11/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: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axis.py ADDED
The diff for this file is too large to render. See raw diff
 
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/axis.pyi ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Iterable, Sequence
2
+ import datetime
3
+ from typing import Any, Literal, overload
4
+ from typing_extensions import Self # < Py 3.11
5
+
6
+ import numpy as np
7
+ from numpy.typing import ArrayLike
8
+
9
+ import matplotlib.artist as martist
10
+ from matplotlib import cbook
11
+ from matplotlib.axes import Axes
12
+ from matplotlib.backend_bases import RendererBase
13
+ from matplotlib.lines import Line2D
14
+ from matplotlib.text import Text
15
+ from matplotlib.ticker import Locator, Formatter
16
+ from matplotlib.transforms import Transform, Bbox
17
+ from matplotlib.typing import ColorType
18
+ from matplotlib.units import ConversionInterface
19
+
20
+
21
+ GRIDLINE_INTERPOLATION_STEPS: int
22
+
23
+ class Tick(martist.Artist):
24
+ axes: Axes
25
+ tick1line: Line2D
26
+ tick2line: Line2D
27
+ gridline: Line2D
28
+ label1: Text
29
+ label2: Text
30
+ def __init__(
31
+ self,
32
+ axes: Axes,
33
+ loc: float,
34
+ *,
35
+ size: float | None = ...,
36
+ width: float | None = ...,
37
+ color: ColorType | None = ...,
38
+ tickdir: Literal["in", "inout", "out"] | None = ...,
39
+ pad: float | None = ...,
40
+ labelsize: float | None = ...,
41
+ labelcolor: ColorType | None = ...,
42
+ labelfontfamily: str | Sequence[str] | None = ...,
43
+ zorder: float | None = ...,
44
+ gridOn: bool | None = ...,
45
+ tick1On: bool = ...,
46
+ tick2On: bool = ...,
47
+ label1On: bool = ...,
48
+ label2On: bool = ...,
49
+ major: bool = ...,
50
+ labelrotation: float = ...,
51
+ grid_color: ColorType | None = ...,
52
+ grid_linestyle: str | None = ...,
53
+ grid_linewidth: float | None = ...,
54
+ grid_alpha: float | None = ...,
55
+ **kwargs
56
+ ) -> None: ...
57
+ def get_tickdir(self) -> Literal["in", "inout", "out"]: ...
58
+ def get_tick_padding(self) -> float: ...
59
+ def get_children(self) -> list[martist.Artist]: ...
60
+ stale: bool
61
+ def set_pad(self, val: float) -> None: ...
62
+ def get_pad(self) -> None: ...
63
+ def get_loc(self) -> float: ...
64
+ def set_url(self, url: str | None) -> None: ...
65
+ def get_view_interval(self) -> ArrayLike: ...
66
+ def update_position(self, loc: float) -> None: ...
67
+
68
+ class XTick(Tick):
69
+ __name__: str
70
+ def __init__(self, *args, **kwargs) -> None: ...
71
+ stale: bool
72
+ def update_position(self, loc: float) -> None: ...
73
+ def get_view_interval(self) -> np.ndarray: ...
74
+
75
+ class YTick(Tick):
76
+ __name__: str
77
+ def __init__(self, *args, **kwargs) -> None: ...
78
+ stale: bool
79
+ def update_position(self, loc: float) -> None: ...
80
+ def get_view_interval(self) -> np.ndarray: ...
81
+
82
+ class Ticker:
83
+ def __init__(self) -> None: ...
84
+ @property
85
+ def locator(self) -> Locator | None: ...
86
+ @locator.setter
87
+ def locator(self, locator: Locator) -> None: ...
88
+ @property
89
+ def formatter(self) -> Formatter | None: ...
90
+ @formatter.setter
91
+ def formatter(self, formatter: Formatter) -> None: ...
92
+
93
+ class _LazyTickList:
94
+ def __init__(self, major: bool) -> None: ...
95
+ @overload
96
+ def __get__(self, instance: None, owner: None) -> Self: ...
97
+ @overload
98
+ def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ...
99
+
100
+ class Axis(martist.Artist):
101
+ OFFSETTEXTPAD: int
102
+ isDefault_label: bool
103
+ axes: Axes
104
+ major: Ticker
105
+ minor: Ticker
106
+ callbacks: cbook.CallbackRegistry
107
+ label: Text
108
+ offsetText: Text
109
+ labelpad: float
110
+ pickradius: float
111
+ def __init__(self, axes, *, pickradius: float = ...,
112
+ clear: bool = ...) -> None: ...
113
+ @property
114
+ def isDefault_majloc(self) -> bool: ...
115
+ @isDefault_majloc.setter
116
+ def isDefault_majloc(self, value: bool) -> None: ...
117
+ @property
118
+ def isDefault_majfmt(self) -> bool: ...
119
+ @isDefault_majfmt.setter
120
+ def isDefault_majfmt(self, value: bool) -> None: ...
121
+ @property
122
+ def isDefault_minloc(self) -> bool: ...
123
+ @isDefault_minloc.setter
124
+ def isDefault_minloc(self, value: bool) -> None: ...
125
+ @property
126
+ def isDefault_minfmt(self) -> bool: ...
127
+ @isDefault_minfmt.setter
128
+ def isDefault_minfmt(self, value: bool) -> None: ...
129
+ majorTicks: _LazyTickList
130
+ minorTicks: _LazyTickList
131
+ def get_remove_overlapping_locs(self) -> bool: ...
132
+ def set_remove_overlapping_locs(self, val: bool) -> None: ...
133
+ @property
134
+ def remove_overlapping_locs(self) -> bool: ...
135
+ @remove_overlapping_locs.setter
136
+ def remove_overlapping_locs(self, val: bool) -> None: ...
137
+ stale: bool
138
+ def set_label_coords(
139
+ self, x: float, y: float, transform: Transform | None = ...
140
+ ) -> None: ...
141
+ def get_transform(self) -> Transform: ...
142
+ def get_scale(self) -> str: ...
143
+ def limit_range_for_scale(
144
+ self, vmin: float, vmax: float
145
+ ) -> tuple[float, float]: ...
146
+ def get_children(self) -> list[martist.Artist]: ...
147
+ # TODO units
148
+ converter: Any
149
+ units: Any
150
+ def clear(self) -> None: ...
151
+ def reset_ticks(self) -> None: ...
152
+ def minorticks_on(self) -> None: ...
153
+ def minorticks_off(self) -> None: ...
154
+ def set_tick_params(
155
+ self,
156
+ which: Literal["major", "minor", "both"] = ...,
157
+ reset: bool = ...,
158
+ **kwargs
159
+ ) -> None: ...
160
+ def get_tick_params(
161
+ self, which: Literal["major", "minor"] = ...
162
+ ) -> dict[str, Any]: ...
163
+ def get_view_interval(self) -> tuple[float, float]: ...
164
+ def set_view_interval(
165
+ self, vmin: float, vmax: float, ignore: bool = ...
166
+ ) -> None: ...
167
+ def get_data_interval(self) -> tuple[float, float]: ...
168
+ def set_data_interval(
169
+ self, vmin: float, vmax: float, ignore: bool = ...
170
+ ) -> None: ...
171
+ def get_inverted(self) -> bool: ...
172
+ def set_inverted(self, inverted: bool) -> None: ...
173
+ def set_default_intervals(self) -> None: ...
174
+ def get_tightbbox(
175
+ self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ...
176
+ ) -> Bbox | None: ...
177
+ def get_tick_padding(self) -> float: ...
178
+ def get_gridlines(self) -> list[Line2D]: ...
179
+ def get_label(self) -> Text: ...
180
+ def get_offset_text(self) -> Text: ...
181
+ def get_pickradius(self) -> float: ...
182
+ def get_majorticklabels(self) -> list[Text]: ...
183
+ def get_minorticklabels(self) -> list[Text]: ...
184
+ def get_ticklabels(
185
+ self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
186
+ ) -> list[Text]: ...
187
+ def get_majorticklines(self) -> list[Line2D]: ...
188
+ def get_minorticklines(self) -> list[Line2D]: ...
189
+ def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ...
190
+ def get_majorticklocs(self) -> np.ndarray: ...
191
+ def get_minorticklocs(self) -> np.ndarray: ...
192
+ def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ...
193
+ def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ...
194
+ def get_label_text(self) -> str: ...
195
+ def get_major_locator(self) -> Locator: ...
196
+ def get_minor_locator(self) -> Locator: ...
197
+ def get_major_formatter(self) -> Formatter: ...
198
+ def get_minor_formatter(self) -> Formatter: ...
199
+ def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
200
+ def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
201
+ def grid(
202
+ self,
203
+ visible: bool | None = ...,
204
+ which: Literal["major", "minor", "both"] = ...,
205
+ **kwargs
206
+ ) -> None: ...
207
+ # TODO units
208
+ def update_units(self, data): ...
209
+ def have_units(self) -> bool: ...
210
+ def convert_units(self, x): ...
211
+ def get_converter(self) -> ConversionInterface | None: ...
212
+ def set_converter(self, converter: ConversionInterface) -> None: ...
213
+ def set_units(self, u) -> None: ...
214
+ def get_units(self): ...
215
+ def set_label_text(
216
+ self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs
217
+ ) -> Text: ...
218
+ def set_major_formatter(
219
+ self, formatter: Formatter | str | Callable[[float, float], str]
220
+ ) -> None: ...
221
+ def set_minor_formatter(
222
+ self, formatter: Formatter | str | Callable[[float, float], str]
223
+ ) -> None: ...
224
+ def set_major_locator(self, locator: Locator) -> None: ...
225
+ def set_minor_locator(self, locator: Locator) -> None: ...
226
+ def set_pickradius(self, pickradius: float) -> None: ...
227
+ def set_ticklabels(
228
+ self,
229
+ labels: Iterable[str | Text],
230
+ *,
231
+ minor: bool = ...,
232
+ fontdict: dict[str, Any] | None = ...,
233
+ **kwargs
234
+ ) -> list[Text]: ...
235
+ def set_ticks(
236
+ self,
237
+ ticks: ArrayLike,
238
+ labels: Iterable[str] | None = ...,
239
+ *,
240
+ minor: bool = ...,
241
+ **kwargs
242
+ ) -> list[Tick]: ...
243
+ def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
244
+ def get_tick_space(self) -> int: ...
245
+ def get_label_position(self) -> Literal["top", "bottom"]: ...
246
+ def set_label_position(
247
+ self, position: Literal["top", "bottom", "left", "right"]
248
+ ) -> None: ...
249
+ def get_minpos(self) -> float: ...
250
+
251
+ class XAxis(Axis):
252
+ __name__: str
253
+ axis_name: str
254
+ def __init__(self, *args, **kwargs) -> None: ...
255
+ label_position: Literal["bottom", "top"]
256
+ stale: bool
257
+ def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override]
258
+ def set_ticks_position(
259
+ self, position: Literal["top", "bottom", "both", "default", "none"]
260
+ ) -> None: ...
261
+ def tick_top(self) -> None: ...
262
+ def tick_bottom(self) -> None: ...
263
+ def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ...
264
+ def get_tick_space(self) -> int: ...
265
+
266
+ class YAxis(Axis):
267
+ __name__: str
268
+ axis_name: str
269
+ def __init__(self, *args, **kwargs) -> None: ...
270
+ label_position: Literal["left", "right"]
271
+ stale: bool
272
+ def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override]
273
+ def set_offset_position(self, position: Literal["left", "right"]) -> None: ...
274
+ def set_ticks_position(
275
+ self, position: Literal["left", "right", "both", "default", "none"]
276
+ ) -> None: ...
277
+ def tick_right(self) -> None: ...
278
+ def tick_left(self) -> None: ...
279
+ def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ...
280
+ def get_tick_space(self) -> int: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_bases.py ADDED
The diff for this file is too large to render. See raw diff
 
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_bases.pyi ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum, IntEnum
2
+ import os
3
+ from matplotlib import (
4
+ cbook,
5
+ transforms,
6
+ widgets,
7
+ _api,
8
+ )
9
+ from matplotlib.artist import Artist
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.backend_managers import ToolManager
12
+ from matplotlib.backend_tools import Cursors, ToolBase
13
+ from matplotlib.colorbar import Colorbar
14
+ from matplotlib.figure import Figure
15
+ from matplotlib.font_manager import FontProperties
16
+ from matplotlib.path import Path
17
+ from matplotlib.texmanager import TexManager
18
+ from matplotlib.text import Text
19
+ from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath
20
+
21
+ from collections.abc import Callable, Iterable, Sequence
22
+ from typing import Any, IO, Literal, NamedTuple, TypeVar
23
+ from numpy.typing import ArrayLike
24
+ from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
25
+
26
+ def register_backend(
27
+ format: str, backend: str | type[FigureCanvasBase], description: str | None = ...
28
+ ) -> None: ...
29
+ def get_registered_canvas_class(format: str) -> type[FigureCanvasBase]: ...
30
+
31
+ class RendererBase:
32
+ def __init__(self) -> None: ...
33
+ def open_group(self, s: str, gid: str | None = ...) -> None: ...
34
+ def close_group(self, s: str) -> None: ...
35
+ def draw_path(
36
+ self,
37
+ gc: GraphicsContextBase,
38
+ path: Path,
39
+ transform: Transform,
40
+ rgbFace: ColorType | None = ...,
41
+ ) -> None: ...
42
+ def draw_markers(
43
+ self,
44
+ gc: GraphicsContextBase,
45
+ marker_path: Path,
46
+ marker_trans: Transform,
47
+ path: Path,
48
+ trans: Transform,
49
+ rgbFace: ColorType | None = ...,
50
+ ) -> None: ...
51
+ def draw_path_collection(
52
+ self,
53
+ gc: GraphicsContextBase,
54
+ master_transform: Transform,
55
+ paths: Sequence[Path],
56
+ all_transforms: Sequence[ArrayLike],
57
+ offsets: ArrayLike | Sequence[ArrayLike],
58
+ offset_trans: Transform,
59
+ facecolors: ColorType | Sequence[ColorType],
60
+ edgecolors: ColorType | Sequence[ColorType],
61
+ linewidths: float | Sequence[float],
62
+ linestyles: LineStyleType | Sequence[LineStyleType],
63
+ antialiaseds: bool | Sequence[bool],
64
+ urls: str | Sequence[str],
65
+ offset_position: Any,
66
+ ) -> None: ...
67
+ def draw_quad_mesh(
68
+ self,
69
+ gc: GraphicsContextBase,
70
+ master_transform: Transform,
71
+ meshWidth,
72
+ meshHeight,
73
+ coordinates: ArrayLike,
74
+ offsets: ArrayLike | Sequence[ArrayLike],
75
+ offsetTrans: Transform,
76
+ facecolors: Sequence[ColorType],
77
+ antialiased: bool,
78
+ edgecolors: Sequence[ColorType] | ColorType | None,
79
+ ) -> None: ...
80
+ def draw_gouraud_triangles(
81
+ self,
82
+ gc: GraphicsContextBase,
83
+ triangles_array: ArrayLike,
84
+ colors_array: ArrayLike,
85
+ transform: Transform,
86
+ ) -> None: ...
87
+ def get_image_magnification(self) -> float: ...
88
+ def draw_image(
89
+ self,
90
+ gc: GraphicsContextBase,
91
+ x: float,
92
+ y: float,
93
+ im: ArrayLike,
94
+ transform: transforms.Affine2DBase | None = ...,
95
+ ) -> None: ...
96
+ def option_image_nocomposite(self) -> bool: ...
97
+ def option_scale_image(self) -> bool: ...
98
+ def draw_tex(
99
+ self,
100
+ gc: GraphicsContextBase,
101
+ x: float,
102
+ y: float,
103
+ s: str,
104
+ prop: FontProperties,
105
+ angle: float,
106
+ *,
107
+ mtext: Text | None = ...
108
+ ) -> None: ...
109
+ def draw_text(
110
+ self,
111
+ gc: GraphicsContextBase,
112
+ x: float,
113
+ y: float,
114
+ s: str,
115
+ prop: FontProperties,
116
+ angle: float,
117
+ ismath: bool | Literal["TeX"] = ...,
118
+ mtext: Text | None = ...,
119
+ ) -> None: ...
120
+ def get_text_width_height_descent(
121
+ self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
122
+ ) -> tuple[float, float, float]: ...
123
+ def flipy(self) -> bool: ...
124
+ def get_canvas_width_height(self) -> tuple[float, float]: ...
125
+ def get_texmanager(self) -> TexManager: ...
126
+ def new_gc(self) -> GraphicsContextBase: ...
127
+ def points_to_pixels(self, points: ArrayLike) -> ArrayLike: ...
128
+ def start_rasterizing(self) -> None: ...
129
+ def stop_rasterizing(self) -> None: ...
130
+ def start_filter(self) -> None: ...
131
+ def stop_filter(self, filter_func) -> None: ...
132
+
133
+ class GraphicsContextBase:
134
+ def __init__(self) -> None: ...
135
+ def copy_properties(self, gc: GraphicsContextBase) -> None: ...
136
+ def restore(self) -> None: ...
137
+ def get_alpha(self) -> float: ...
138
+ def get_antialiased(self) -> int: ...
139
+ def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
140
+ def get_clip_rectangle(self) -> Bbox | None: ...
141
+ def get_clip_path(
142
+ self,
143
+ ) -> tuple[TransformedPath, Transform] | tuple[None, None]: ...
144
+ def get_dashes(self) -> tuple[float, ArrayLike | None]: ...
145
+ def get_forced_alpha(self) -> bool: ...
146
+ def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
147
+ def get_linewidth(self) -> float: ...
148
+ def get_rgb(self) -> tuple[float, float, float, float]: ...
149
+ def get_url(self) -> str | None: ...
150
+ def get_gid(self) -> int | None: ...
151
+ def get_snap(self) -> bool | None: ...
152
+ def set_alpha(self, alpha: float) -> None: ...
153
+ def set_antialiased(self, b: bool) -> None: ...
154
+ def set_capstyle(self, cs: CapStyleType) -> None: ...
155
+ def set_clip_rectangle(self, rectangle: Bbox | None) -> None: ...
156
+ def set_clip_path(self, path: TransformedPath | None) -> None: ...
157
+ def set_dashes(self, dash_offset: float, dash_list: ArrayLike | None) -> None: ...
158
+ def set_foreground(self, fg: ColorType, isRGBA: bool = ...) -> None: ...
159
+ def set_joinstyle(self, js: JoinStyleType) -> None: ...
160
+ def set_linewidth(self, w: float) -> None: ...
161
+ def set_url(self, url: str | None) -> None: ...
162
+ def set_gid(self, id: int | None) -> None: ...
163
+ def set_snap(self, snap: bool | None) -> None: ...
164
+ def set_hatch(self, hatch: str | None) -> None: ...
165
+ def get_hatch(self) -> str | None: ...
166
+ def get_hatch_path(self, density: float = ...) -> Path: ...
167
+ def get_hatch_color(self) -> ColorType: ...
168
+ def set_hatch_color(self, hatch_color: ColorType) -> None: ...
169
+ def get_hatch_linewidth(self) -> float: ...
170
+ def set_hatch_linewidth(self, hatch_linewidth: float) -> None: ...
171
+ def get_sketch_params(self) -> tuple[float, float, float] | None: ...
172
+ def set_sketch_params(
173
+ self,
174
+ scale: float | None = ...,
175
+ length: float | None = ...,
176
+ randomness: float | None = ...,
177
+ ) -> None: ...
178
+
179
+ class TimerBase:
180
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]]
181
+ def __init__(
182
+ self,
183
+ interval: int | None = ...,
184
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
185
+ ) -> None: ...
186
+ def __del__(self) -> None: ...
187
+ def start(self, interval: int | None = ...) -> None: ...
188
+ def stop(self) -> None: ...
189
+ @property
190
+ def interval(self) -> int: ...
191
+ @interval.setter
192
+ def interval(self, interval: int) -> None: ...
193
+ @property
194
+ def single_shot(self) -> bool: ...
195
+ @single_shot.setter
196
+ def single_shot(self, ss: bool) -> None: ...
197
+ def add_callback(self, func: Callable, *args, **kwargs) -> Callable: ...
198
+ def remove_callback(self, func: Callable, *args, **kwargs) -> None: ...
199
+
200
+ class Event:
201
+ name: str
202
+ canvas: FigureCanvasBase
203
+ guiEvent: Any
204
+ def __init__(
205
+ self, name: str, canvas: FigureCanvasBase, guiEvent: Any | None = ...
206
+ ) -> None: ...
207
+
208
+ class DrawEvent(Event):
209
+ renderer: RendererBase
210
+ def __init__(
211
+ self, name: str, canvas: FigureCanvasBase, renderer: RendererBase
212
+ ) -> None: ...
213
+
214
+ class ResizeEvent(Event):
215
+ width: int
216
+ height: int
217
+ def __init__(self, name: str, canvas: FigureCanvasBase) -> None: ...
218
+
219
+ class CloseEvent(Event): ...
220
+
221
+ class LocationEvent(Event):
222
+ x: int
223
+ y: int
224
+ inaxes: Axes | None
225
+ xdata: float | None
226
+ ydata: float | None
227
+ def __init__(
228
+ self,
229
+ name: str,
230
+ canvas: FigureCanvasBase,
231
+ x: int,
232
+ y: int,
233
+ guiEvent: Any | None = ...,
234
+ *,
235
+ modifiers: Iterable[str] | None = ...,
236
+ ) -> None: ...
237
+
238
+ class MouseButton(IntEnum):
239
+ LEFT = 1
240
+ MIDDLE = 2
241
+ RIGHT = 3
242
+ BACK = 8
243
+ FORWARD = 9
244
+
245
+ class MouseEvent(LocationEvent):
246
+ button: MouseButton | Literal["up", "down"] | None
247
+ key: str | None
248
+ step: float
249
+ dblclick: bool
250
+ def __init__(
251
+ self,
252
+ name: str,
253
+ canvas: FigureCanvasBase,
254
+ x: int,
255
+ y: int,
256
+ button: MouseButton | Literal["up", "down"] | None = ...,
257
+ key: str | None = ...,
258
+ step: float = ...,
259
+ dblclick: bool = ...,
260
+ guiEvent: Any | None = ...,
261
+ *,
262
+ buttons: Iterable[MouseButton] | None = ...,
263
+ modifiers: Iterable[str] | None = ...,
264
+ ) -> None: ...
265
+
266
+ class PickEvent(Event):
267
+ mouseevent: MouseEvent
268
+ artist: Artist
269
+ def __init__(
270
+ self,
271
+ name: str,
272
+ canvas: FigureCanvasBase,
273
+ mouseevent: MouseEvent,
274
+ artist: Artist,
275
+ guiEvent: Any | None = ...,
276
+ **kwargs
277
+ ) -> None: ...
278
+
279
+ class KeyEvent(LocationEvent):
280
+ key: str | None
281
+ def __init__(
282
+ self,
283
+ name: str,
284
+ canvas: FigureCanvasBase,
285
+ key: str | None,
286
+ x: int = ...,
287
+ y: int = ...,
288
+ guiEvent: Any | None = ...,
289
+ ) -> None: ...
290
+
291
+ class FigureCanvasBase:
292
+ required_interactive_framework: str | None
293
+
294
+ @_api.classproperty
295
+ def manager_class(cls) -> type[FigureManagerBase]: ...
296
+ events: list[str]
297
+ fixed_dpi: None | float
298
+ filetypes: dict[str, str]
299
+
300
+ @_api.classproperty
301
+ def supports_blit(cls) -> bool: ...
302
+
303
+ figure: Figure
304
+ manager: None | FigureManagerBase
305
+ widgetlock: widgets.LockDraw
306
+ mouse_grabber: None | Axes
307
+ toolbar: None | NavigationToolbar2
308
+ def __init__(self, figure: Figure | None = ...) -> None: ...
309
+ @property
310
+ def callbacks(self) -> cbook.CallbackRegistry: ...
311
+ @property
312
+ def button_pick_id(self) -> int: ...
313
+ @property
314
+ def scroll_pick_id(self) -> int: ...
315
+ @classmethod
316
+ def new_manager(cls, figure: Figure, num: int | str) -> FigureManagerBase: ...
317
+ def is_saving(self) -> bool: ...
318
+ def blit(self, bbox: BboxBase | None = ...) -> None: ...
319
+ def inaxes(self, xy: tuple[float, float]) -> Axes | None: ...
320
+ def grab_mouse(self, ax: Axes) -> None: ...
321
+ def release_mouse(self, ax: Axes) -> None: ...
322
+ def set_cursor(self, cursor: Cursors) -> None: ...
323
+ def draw(self, *args, **kwargs) -> None: ...
324
+ def draw_idle(self, *args, **kwargs) -> None: ...
325
+ @property
326
+ def device_pixel_ratio(self) -> float: ...
327
+ def get_width_height(self, *, physical: bool = ...) -> tuple[int, int]: ...
328
+ @classmethod
329
+ def get_supported_filetypes(cls) -> dict[str, str]: ...
330
+ @classmethod
331
+ def get_supported_filetypes_grouped(cls) -> dict[str, list[str]]: ...
332
+ def print_figure(
333
+ self,
334
+ filename: str | os.PathLike | IO,
335
+ dpi: float | None = ...,
336
+ facecolor: ColorType | Literal["auto"] | None = ...,
337
+ edgecolor: ColorType | Literal["auto"] | None = ...,
338
+ orientation: str = ...,
339
+ format: str | None = ...,
340
+ *,
341
+ bbox_inches: Literal["tight"] | Bbox | None = ...,
342
+ pad_inches: float | None = ...,
343
+ bbox_extra_artists: list[Artist] | None = ...,
344
+ backend: str | None = ...,
345
+ **kwargs
346
+ ) -> Any: ...
347
+ @classmethod
348
+ def get_default_filetype(cls) -> str: ...
349
+ def get_default_filename(self) -> str: ...
350
+ _T = TypeVar("_T", bound=FigureCanvasBase)
351
+ def mpl_connect(self, s: str, func: Callable[[Event], Any]) -> int: ...
352
+ def mpl_disconnect(self, cid: int) -> None: ...
353
+ def new_timer(
354
+ self,
355
+ interval: int | None = ...,
356
+ callbacks: list[tuple[Callable, tuple, dict[str, Any]]] | None = ...,
357
+ ) -> TimerBase: ...
358
+ def flush_events(self) -> None: ...
359
+ def start_event_loop(self, timeout: float = ...) -> None: ...
360
+ def stop_event_loop(self) -> None: ...
361
+
362
+ def key_press_handler(
363
+ event: KeyEvent,
364
+ canvas: FigureCanvasBase | None = ...,
365
+ toolbar: NavigationToolbar2 | None = ...,
366
+ ) -> None: ...
367
+ def button_press_handler(
368
+ event: MouseEvent,
369
+ canvas: FigureCanvasBase | None = ...,
370
+ toolbar: NavigationToolbar2 | None = ...,
371
+ ) -> None: ...
372
+
373
+ class NonGuiException(Exception): ...
374
+
375
+ class FigureManagerBase:
376
+ canvas: FigureCanvasBase
377
+ num: int | str
378
+ key_press_handler_id: int | None
379
+ button_press_handler_id: int | None
380
+ toolmanager: ToolManager | None
381
+ toolbar: NavigationToolbar2 | ToolContainerBase | None
382
+ def __init__(self, canvas: FigureCanvasBase, num: int | str) -> None: ...
383
+ @classmethod
384
+ def create_with_canvas(
385
+ cls, canvas_class: type[FigureCanvasBase], figure: Figure, num: int | str
386
+ ) -> FigureManagerBase: ...
387
+ @classmethod
388
+ def start_main_loop(cls) -> None: ...
389
+ @classmethod
390
+ def pyplot_show(cls, *, block: bool | None = ...) -> None: ...
391
+ def show(self) -> None: ...
392
+ def destroy(self) -> None: ...
393
+ def full_screen_toggle(self) -> None: ...
394
+ def resize(self, w: int, h: int) -> None: ...
395
+ def get_window_title(self) -> str: ...
396
+ def set_window_title(self, title: str) -> None: ...
397
+
398
+ cursors = Cursors
399
+
400
+ class _Mode(str, Enum):
401
+ NONE = ""
402
+ PAN = "pan/zoom"
403
+ ZOOM = "zoom rect"
404
+
405
+ class NavigationToolbar2:
406
+ toolitems: tuple[tuple[str, ...] | tuple[None, ...], ...]
407
+ UNKNOWN_SAVED_STATUS: object
408
+ canvas: FigureCanvasBase
409
+ mode: _Mode
410
+ def __init__(self, canvas: FigureCanvasBase) -> None: ...
411
+ def set_message(self, s: str) -> None: ...
412
+ def draw_rubberband(
413
+ self, event: Event, x0: float, y0: float, x1: float, y1: float
414
+ ) -> None: ...
415
+ def remove_rubberband(self) -> None: ...
416
+ def home(self, *args) -> None: ...
417
+ def back(self, *args) -> None: ...
418
+ def forward(self, *args) -> None: ...
419
+ def mouse_move(self, event: MouseEvent) -> None: ...
420
+ def pan(self, *args) -> None: ...
421
+
422
+ class _PanInfo(NamedTuple):
423
+ button: MouseButton
424
+ axes: list[Axes]
425
+ cid: int
426
+ def press_pan(self, event: Event) -> None: ...
427
+ def drag_pan(self, event: Event) -> None: ...
428
+ def release_pan(self, event: Event) -> None: ...
429
+ def zoom(self, *args) -> None: ...
430
+
431
+ class _ZoomInfo(NamedTuple):
432
+ direction: Literal["in", "out"]
433
+ start_xy: tuple[float, float]
434
+ axes: list[Axes]
435
+ cid: int
436
+ cbar: Colorbar
437
+ def press_zoom(self, event: Event) -> None: ...
438
+ def drag_zoom(self, event: Event) -> None: ...
439
+ def release_zoom(self, event: Event) -> None: ...
440
+ def push_current(self) -> None: ...
441
+ subplot_tool: widgets.SubplotTool
442
+ def configure_subplots(self, *args): ...
443
+ def save_figure(self, *args) -> str | None | object: ...
444
+ def update(self) -> None: ...
445
+ def set_history_buttons(self) -> None: ...
446
+
447
+ class ToolContainerBase:
448
+ toolmanager: ToolManager
449
+ def __init__(self, toolmanager: ToolManager) -> None: ...
450
+ def add_tool(self, tool: ToolBase, group: str, position: int = ...) -> None: ...
451
+ def trigger_tool(self, name: str) -> None: ...
452
+ def add_toolitem(
453
+ self,
454
+ name: str,
455
+ group: str,
456
+ position: int,
457
+ image: str,
458
+ description: str,
459
+ toggle: bool,
460
+ ) -> None: ...
461
+ def toggle_toolitem(self, name: str, toggled: bool) -> None: ...
462
+ def remove_toolitem(self, name: str) -> None: ...
463
+ def set_message(self, s: str) -> None: ...
464
+
465
+ class _Backend:
466
+ backend_version: str
467
+ FigureCanvas: type[FigureCanvasBase] | None
468
+ FigureManager: type[FigureManagerBase]
469
+ mainloop: None | Callable[[], Any]
470
+ @classmethod
471
+ def new_figure_manager(cls, num: int | str, *args, **kwargs) -> FigureManagerBase: ...
472
+ @classmethod
473
+ def new_figure_manager_given_figure(cls, num: int | str, figure: Figure) -> FigureManagerBase: ...
474
+ @classmethod
475
+ def draw_if_interactive(cls) -> None: ...
476
+ @classmethod
477
+ def show(cls, *, block: bool | None = ...) -> None: ...
478
+ @staticmethod
479
+ def export(cls) -> type[_Backend]: ...
480
+
481
+ class ShowBase(_Backend):
482
+ def __call__(self, block: bool | None = ...) -> None: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_managers.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import _api, backend_tools, cbook, widgets
2
+
3
+
4
+ class ToolEvent:
5
+ """Event for tool manipulation (add/remove)."""
6
+ def __init__(self, name, sender, tool, data=None):
7
+ self.name = name
8
+ self.sender = sender
9
+ self.tool = tool
10
+ self.data = data
11
+
12
+
13
+ class ToolTriggerEvent(ToolEvent):
14
+ """Event to inform that a tool has been triggered."""
15
+ def __init__(self, name, sender, tool, canvasevent=None, data=None):
16
+ super().__init__(name, sender, tool, data)
17
+ self.canvasevent = canvasevent
18
+
19
+
20
+ class ToolManagerMessageEvent:
21
+ """
22
+ Event carrying messages from toolmanager.
23
+
24
+ Messages usually get displayed to the user by the toolbar.
25
+ """
26
+ def __init__(self, name, sender, message):
27
+ self.name = name
28
+ self.sender = sender
29
+ self.message = message
30
+
31
+
32
+ class ToolManager:
33
+ """
34
+ Manager for actions triggered by user interactions (key press, toolbar
35
+ clicks, ...) on a Figure.
36
+
37
+ Attributes
38
+ ----------
39
+ figure : `.Figure`
40
+ keypresslock : `~matplotlib.widgets.LockDraw`
41
+ `.LockDraw` object to know if the `canvas` key_press_event is locked.
42
+ messagelock : `~matplotlib.widgets.LockDraw`
43
+ `.LockDraw` object to know if the message is available to write.
44
+ """
45
+
46
+ def __init__(self, figure=None):
47
+
48
+ self._key_press_handler_id = None
49
+
50
+ self._tools = {}
51
+ self._keys = {}
52
+ self._toggled = {}
53
+ self._callbacks = cbook.CallbackRegistry()
54
+
55
+ # to process keypress event
56
+ self.keypresslock = widgets.LockDraw()
57
+ self.messagelock = widgets.LockDraw()
58
+
59
+ self._figure = None
60
+ self.set_figure(figure)
61
+
62
+ @property
63
+ def canvas(self):
64
+ """Canvas managed by FigureManager."""
65
+ if not self._figure:
66
+ return None
67
+ return self._figure.canvas
68
+
69
+ @property
70
+ def figure(self):
71
+ """Figure that holds the canvas."""
72
+ return self._figure
73
+
74
+ @figure.setter
75
+ def figure(self, figure):
76
+ self.set_figure(figure)
77
+
78
+ def set_figure(self, figure, update_tools=True):
79
+ """
80
+ Bind the given figure to the tools.
81
+
82
+ Parameters
83
+ ----------
84
+ figure : `.Figure`
85
+ update_tools : bool, default: True
86
+ Force tools to update figure.
87
+ """
88
+ if self._key_press_handler_id:
89
+ self.canvas.mpl_disconnect(self._key_press_handler_id)
90
+ self._figure = figure
91
+ if figure:
92
+ self._key_press_handler_id = self.canvas.mpl_connect(
93
+ 'key_press_event', self._key_press)
94
+ if update_tools:
95
+ for tool in self._tools.values():
96
+ tool.figure = figure
97
+
98
+ def toolmanager_connect(self, s, func):
99
+ """
100
+ Connect event with string *s* to *func*.
101
+
102
+ Parameters
103
+ ----------
104
+ s : str
105
+ The name of the event. The following events are recognized:
106
+
107
+ - 'tool_message_event'
108
+ - 'tool_removed_event'
109
+ - 'tool_added_event'
110
+
111
+ For every tool added a new event is created
112
+
113
+ - 'tool_trigger_TOOLNAME', where TOOLNAME is the id of the tool.
114
+
115
+ func : callable
116
+ Callback function for the toolmanager event with signature::
117
+
118
+ def func(event: ToolEvent) -> Any
119
+
120
+ Returns
121
+ -------
122
+ cid
123
+ The callback id for the connection. This can be used in
124
+ `.toolmanager_disconnect`.
125
+ """
126
+ return self._callbacks.connect(s, func)
127
+
128
+ def toolmanager_disconnect(self, cid):
129
+ """
130
+ Disconnect callback id *cid*.
131
+
132
+ Example usage::
133
+
134
+ cid = toolmanager.toolmanager_connect('tool_trigger_zoom', onpress)
135
+ #...later
136
+ toolmanager.toolmanager_disconnect(cid)
137
+ """
138
+ return self._callbacks.disconnect(cid)
139
+
140
+ def message_event(self, message, sender=None):
141
+ """Emit a `ToolManagerMessageEvent`."""
142
+ if sender is None:
143
+ sender = self
144
+
145
+ s = 'tool_message_event'
146
+ event = ToolManagerMessageEvent(s, sender, message)
147
+ self._callbacks.process(s, event)
148
+
149
+ @property
150
+ def active_toggle(self):
151
+ """Currently toggled tools."""
152
+ return self._toggled
153
+
154
+ def get_tool_keymap(self, name):
155
+ """
156
+ Return the keymap associated with the specified tool.
157
+
158
+ Parameters
159
+ ----------
160
+ name : str
161
+ Name of the Tool.
162
+
163
+ Returns
164
+ -------
165
+ list of str
166
+ List of keys associated with the tool.
167
+ """
168
+
169
+ keys = [k for k, i in self._keys.items() if i == name]
170
+ return keys
171
+
172
+ def _remove_keys(self, name):
173
+ for k in self.get_tool_keymap(name):
174
+ del self._keys[k]
175
+
176
+ def update_keymap(self, name, key):
177
+ """
178
+ Set the keymap to associate with the specified tool.
179
+
180
+ Parameters
181
+ ----------
182
+ name : str
183
+ Name of the Tool.
184
+ key : str or list of str
185
+ Keys to associate with the tool.
186
+ """
187
+ if name not in self._tools:
188
+ raise KeyError(f'{name!r} not in Tools')
189
+ self._remove_keys(name)
190
+ if isinstance(key, str):
191
+ key = [key]
192
+ for k in key:
193
+ if k in self._keys:
194
+ _api.warn_external(
195
+ f'Key {k} changed from {self._keys[k]} to {name}')
196
+ self._keys[k] = name
197
+
198
+ def remove_tool(self, name):
199
+ """
200
+ Remove tool named *name*.
201
+
202
+ Parameters
203
+ ----------
204
+ name : str
205
+ Name of the tool.
206
+ """
207
+ tool = self.get_tool(name)
208
+ if getattr(tool, 'toggled', False): # If it's a toggled toggle tool, untoggle
209
+ self.trigger_tool(tool, 'toolmanager')
210
+ self._remove_keys(name)
211
+ event = ToolEvent('tool_removed_event', self, tool)
212
+ self._callbacks.process(event.name, event)
213
+ del self._tools[name]
214
+
215
+ def add_tool(self, name, tool, *args, **kwargs):
216
+ """
217
+ Add *tool* to `ToolManager`.
218
+
219
+ If successful, adds a new event ``tool_trigger_{name}`` where
220
+ ``{name}`` is the *name* of the tool; the event is fired every time the
221
+ tool is triggered.
222
+
223
+ Parameters
224
+ ----------
225
+ name : str
226
+ Name of the tool, treated as the ID, has to be unique.
227
+ tool : type
228
+ Class of the tool to be added. A subclass will be used
229
+ instead if one was registered for the current canvas class.
230
+ *args, **kwargs
231
+ Passed to the *tool*'s constructor.
232
+
233
+ See Also
234
+ --------
235
+ matplotlib.backend_tools.ToolBase : The base class for tools.
236
+ """
237
+
238
+ tool_cls = backend_tools._find_tool_class(type(self.canvas), tool)
239
+ if not tool_cls:
240
+ raise ValueError('Impossible to find class for %s' % str(tool))
241
+
242
+ if name in self._tools:
243
+ _api.warn_external('A "Tool class" with the same name already '
244
+ 'exists, not added')
245
+ return self._tools[name]
246
+
247
+ tool_obj = tool_cls(self, name, *args, **kwargs)
248
+ self._tools[name] = tool_obj
249
+
250
+ if tool_obj.default_keymap is not None:
251
+ self.update_keymap(name, tool_obj.default_keymap)
252
+
253
+ # For toggle tools init the radio_group in self._toggled
254
+ if isinstance(tool_obj, backend_tools.ToolToggleBase):
255
+ # None group is not mutually exclusive, a set is used to keep track
256
+ # of all toggled tools in this group
257
+ if tool_obj.radio_group is None:
258
+ self._toggled.setdefault(None, set())
259
+ else:
260
+ self._toggled.setdefault(tool_obj.radio_group, None)
261
+
262
+ # If initially toggled
263
+ if tool_obj.toggled:
264
+ self._handle_toggle(tool_obj, None, None)
265
+ tool_obj.set_figure(self.figure)
266
+
267
+ event = ToolEvent('tool_added_event', self, tool_obj)
268
+ self._callbacks.process(event.name, event)
269
+
270
+ return tool_obj
271
+
272
+ def _handle_toggle(self, tool, canvasevent, data):
273
+ """
274
+ Toggle tools, need to untoggle prior to using other Toggle tool.
275
+ Called from trigger_tool.
276
+
277
+ Parameters
278
+ ----------
279
+ tool : `.ToolBase`
280
+ canvasevent : Event
281
+ Original Canvas event or None.
282
+ data : object
283
+ Extra data to pass to the tool when triggering.
284
+ """
285
+
286
+ radio_group = tool.radio_group
287
+ # radio_group None is not mutually exclusive
288
+ # just keep track of toggled tools in this group
289
+ if radio_group is None:
290
+ if tool.name in self._toggled[None]:
291
+ self._toggled[None].remove(tool.name)
292
+ else:
293
+ self._toggled[None].add(tool.name)
294
+ return
295
+
296
+ # If the tool already has a toggled state, untoggle it
297
+ if self._toggled[radio_group] == tool.name:
298
+ toggled = None
299
+ # If no tool was toggled in the radio_group
300
+ # toggle it
301
+ elif self._toggled[radio_group] is None:
302
+ toggled = tool.name
303
+ # Other tool in the radio_group is toggled
304
+ else:
305
+ # Untoggle previously toggled tool
306
+ self.trigger_tool(self._toggled[radio_group],
307
+ self,
308
+ canvasevent,
309
+ data)
310
+ toggled = tool.name
311
+
312
+ # Keep track of the toggled tool in the radio_group
313
+ self._toggled[radio_group] = toggled
314
+
315
+ def trigger_tool(self, name, sender=None, canvasevent=None, data=None):
316
+ """
317
+ Trigger a tool and emit the ``tool_trigger_{name}`` event.
318
+
319
+ Parameters
320
+ ----------
321
+ name : str
322
+ Name of the tool.
323
+ sender : object
324
+ Object that wishes to trigger the tool.
325
+ canvasevent : Event
326
+ Original Canvas event or None.
327
+ data : object
328
+ Extra data to pass to the tool when triggering.
329
+ """
330
+ tool = self.get_tool(name)
331
+ if tool is None:
332
+ return
333
+
334
+ if sender is None:
335
+ sender = self
336
+
337
+ if isinstance(tool, backend_tools.ToolToggleBase):
338
+ self._handle_toggle(tool, canvasevent, data)
339
+
340
+ tool.trigger(sender, canvasevent, data) # Actually trigger Tool.
341
+
342
+ s = 'tool_trigger_%s' % name
343
+ event = ToolTriggerEvent(s, sender, tool, canvasevent, data)
344
+ self._callbacks.process(s, event)
345
+
346
+ def _key_press(self, event):
347
+ if event.key is None or self.keypresslock.locked():
348
+ return
349
+
350
+ name = self._keys.get(event.key, None)
351
+ if name is None:
352
+ return
353
+ self.trigger_tool(name, canvasevent=event)
354
+
355
+ @property
356
+ def tools(self):
357
+ """A dict mapping tool name -> controlled tool."""
358
+ return self._tools
359
+
360
+ def get_tool(self, name, warn=True):
361
+ """
362
+ Return the tool object with the given name.
363
+
364
+ For convenience, this passes tool objects through.
365
+
366
+ Parameters
367
+ ----------
368
+ name : str or `.ToolBase`
369
+ Name of the tool, or the tool itself.
370
+ warn : bool, default: True
371
+ Whether a warning should be emitted it no tool with the given name
372
+ exists.
373
+
374
+ Returns
375
+ -------
376
+ `.ToolBase` or None
377
+ The tool or None if no tool with the given name exists.
378
+ """
379
+ if (isinstance(name, backend_tools.ToolBase)
380
+ and name.name in self._tools):
381
+ return name
382
+ if name not in self._tools:
383
+ if warn:
384
+ _api.warn_external(
385
+ f"ToolManager does not control tool {name!r}")
386
+ return None
387
+ return self._tools[name]
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_managers.pyi ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import backend_tools, widgets
2
+ from matplotlib.backend_bases import FigureCanvasBase
3
+ from matplotlib.figure import Figure
4
+
5
+ from collections.abc import Callable, Iterable
6
+ from typing import Any, TypeVar
7
+
8
+ class ToolEvent:
9
+ name: str
10
+ sender: Any
11
+ tool: backend_tools.ToolBase
12
+ data: Any
13
+ def __init__(self, name, sender, tool, data: Any | None = ...) -> None: ...
14
+
15
+ class ToolTriggerEvent(ToolEvent):
16
+ canvasevent: ToolEvent
17
+ def __init__(
18
+ self,
19
+ name,
20
+ sender,
21
+ tool,
22
+ canvasevent: ToolEvent | None = ...,
23
+ data: Any | None = ...,
24
+ ) -> None: ...
25
+
26
+ class ToolManagerMessageEvent:
27
+ name: str
28
+ sender: Any
29
+ message: str
30
+ def __init__(self, name: str, sender: Any, message: str) -> None: ...
31
+
32
+ class ToolManager:
33
+ keypresslock: widgets.LockDraw
34
+ messagelock: widgets.LockDraw
35
+ def __init__(self, figure: Figure | None = ...) -> None: ...
36
+ @property
37
+ def canvas(self) -> FigureCanvasBase | None: ...
38
+ @property
39
+ def figure(self) -> Figure | None: ...
40
+ @figure.setter
41
+ def figure(self, figure: Figure) -> None: ...
42
+ def set_figure(self, figure: Figure, update_tools: bool = ...) -> None: ...
43
+ def toolmanager_connect(self, s: str, func: Callable[[ToolEvent], Any]) -> int: ...
44
+ def toolmanager_disconnect(self, cid: int) -> None: ...
45
+ def message_event(self, message: str, sender: Any | None = ...) -> None: ...
46
+ @property
47
+ def active_toggle(self) -> dict[str | None, list[str] | str]: ...
48
+ def get_tool_keymap(self, name: str) -> list[str]: ...
49
+ def update_keymap(self, name: str, key: str | Iterable[str]) -> None: ...
50
+ def remove_tool(self, name: str) -> None: ...
51
+ _T = TypeVar("_T", bound=backend_tools.ToolBase)
52
+ def add_tool(self, name: str, tool: type[_T], *args, **kwargs) -> _T: ...
53
+ def trigger_tool(
54
+ self,
55
+ name: str | backend_tools.ToolBase,
56
+ sender: Any | None = ...,
57
+ canvasevent: ToolEvent | None = ...,
58
+ data: Any | None = ...,
59
+ ) -> None: ...
60
+ @property
61
+ def tools(self) -> dict[str, backend_tools.ToolBase]: ...
62
+ def get_tool(
63
+ self, name: str | backend_tools.ToolBase, warn: bool = ...
64
+ ) -> backend_tools.ToolBase | None: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_tools.py ADDED
@@ -0,0 +1,998 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Abstract base classes define the primitives for Tools.
3
+ These tools are used by `matplotlib.backend_managers.ToolManager`
4
+
5
+ :class:`ToolBase`
6
+ Simple stateless tool
7
+
8
+ :class:`ToolToggleBase`
9
+ Tool that has two states, only one Toggle tool can be
10
+ active at any given time for the same
11
+ `matplotlib.backend_managers.ToolManager`
12
+ """
13
+
14
+ import enum
15
+ import functools
16
+ import re
17
+ import time
18
+ from types import SimpleNamespace
19
+ import uuid
20
+ from weakref import WeakKeyDictionary
21
+
22
+ import numpy as np
23
+
24
+ import matplotlib as mpl
25
+ from matplotlib._pylab_helpers import Gcf
26
+ from matplotlib import _api, cbook
27
+
28
+
29
+ class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
30
+ """Backend-independent cursor types."""
31
+ POINTER = enum.auto()
32
+ HAND = enum.auto()
33
+ SELECT_REGION = enum.auto()
34
+ MOVE = enum.auto()
35
+ WAIT = enum.auto()
36
+ RESIZE_HORIZONTAL = enum.auto()
37
+ RESIZE_VERTICAL = enum.auto()
38
+ cursors = Cursors # Backcompat.
39
+
40
+
41
+ # _tool_registry, _register_tool_class, and _find_tool_class implement a
42
+ # mechanism through which ToolManager.add_tool can determine whether a subclass
43
+ # of the requested tool class has been registered (either for the current
44
+ # canvas class or for a parent class), in which case that tool subclass will be
45
+ # instantiated instead. This is the mechanism used e.g. to allow different
46
+ # GUI backends to implement different specializations for ConfigureSubplots.
47
+
48
+
49
+ _tool_registry = set()
50
+
51
+
52
+ def _register_tool_class(canvas_cls, tool_cls=None):
53
+ """Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
54
+ if tool_cls is None:
55
+ return functools.partial(_register_tool_class, canvas_cls)
56
+ _tool_registry.add((canvas_cls, tool_cls))
57
+ return tool_cls
58
+
59
+
60
+ def _find_tool_class(canvas_cls, tool_cls):
61
+ """Find a subclass of *tool_cls* registered for *canvas_cls*."""
62
+ for canvas_parent in canvas_cls.__mro__:
63
+ for tool_child in _api.recursive_subclasses(tool_cls):
64
+ if (canvas_parent, tool_child) in _tool_registry:
65
+ return tool_child
66
+ return tool_cls
67
+
68
+
69
+ # Views positions tool
70
+ _views_positions = 'viewpos'
71
+
72
+
73
+ class ToolBase:
74
+ """
75
+ Base tool class.
76
+
77
+ A base tool, only implements `trigger` method or no method at all.
78
+ The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
79
+ """
80
+
81
+ default_keymap = None
82
+ """
83
+ Keymap to associate with this tool.
84
+
85
+ ``list[str]``: List of keys that will trigger this tool when a keypress
86
+ event is emitted on ``self.figure.canvas``. Note that this attribute is
87
+ looked up on the instance, and can therefore be a property (this is used
88
+ e.g. by the built-in tools to load the rcParams at instantiation time).
89
+ """
90
+
91
+ description = None
92
+ """
93
+ Description of the Tool.
94
+
95
+ `str`: Tooltip used if the Tool is included in a Toolbar.
96
+ """
97
+
98
+ image = None
99
+ """
100
+ Icon filename.
101
+
102
+ ``str | None``: Filename of the Toolbar icon; either absolute, or relative to the
103
+ directory containing the Python source file where the ``Tool.image`` class attribute
104
+ is defined (in the latter case, this cannot be defined as an instance attribute).
105
+ In either case, the extension is optional; leaving it off lets individual backends
106
+ select the icon format they prefer. If None, the *name* is used as a label in the
107
+ toolbar button.
108
+ """
109
+
110
+ def __init__(self, toolmanager, name):
111
+ self._name = name
112
+ self._toolmanager = toolmanager
113
+ self._figure = None
114
+
115
+ name = property(
116
+ lambda self: self._name,
117
+ doc="The tool id (str, must be unique among tools of a tool manager).")
118
+ toolmanager = property(
119
+ lambda self: self._toolmanager,
120
+ doc="The `.ToolManager` that controls this tool.")
121
+ canvas = property(
122
+ lambda self: self._figure.canvas if self._figure is not None else None,
123
+ doc="The canvas of the figure affected by this tool, or None.")
124
+
125
+ def set_figure(self, figure):
126
+ self._figure = figure
127
+
128
+ figure = property(
129
+ lambda self: self._figure,
130
+ # The setter must explicitly call self.set_figure so that subclasses can
131
+ # meaningfully override it.
132
+ lambda self, figure: self.set_figure(figure),
133
+ doc="The Figure affected by this tool, or None.")
134
+
135
+ def _make_classic_style_pseudo_toolbar(self):
136
+ """
137
+ Return a placeholder object with a single `canvas` attribute.
138
+
139
+ This is useful to reuse the implementations of tools already provided
140
+ by the classic Toolbars.
141
+ """
142
+ return SimpleNamespace(canvas=self.canvas)
143
+
144
+ def trigger(self, sender, event, data=None):
145
+ """
146
+ Called when this tool gets used.
147
+
148
+ This method is called by `.ToolManager.trigger_tool`.
149
+
150
+ Parameters
151
+ ----------
152
+ event : `.Event`
153
+ The canvas event that caused this tool to be called.
154
+ sender : object
155
+ Object that requested the tool to be triggered.
156
+ data : object
157
+ Extra data.
158
+ """
159
+ pass
160
+
161
+
162
+ class ToolToggleBase(ToolBase):
163
+ """
164
+ Toggleable tool.
165
+
166
+ Every time it is triggered, it switches between enable and disable.
167
+
168
+ Parameters
169
+ ----------
170
+ ``*args``
171
+ Variable length argument to be used by the Tool.
172
+ ``**kwargs``
173
+ `toggled` if present and True, sets the initial state of the Tool
174
+ Arbitrary keyword arguments to be consumed by the Tool
175
+ """
176
+
177
+ radio_group = None
178
+ """
179
+ Attribute to group 'radio' like tools (mutually exclusive).
180
+
181
+ `str` that identifies the group or **None** if not belonging to a group.
182
+ """
183
+
184
+ cursor = None
185
+ """Cursor to use when the tool is active."""
186
+
187
+ default_toggled = False
188
+ """Default of toggled state."""
189
+
190
+ def __init__(self, *args, **kwargs):
191
+ self._toggled = kwargs.pop('toggled', self.default_toggled)
192
+ super().__init__(*args, **kwargs)
193
+
194
+ def trigger(self, sender, event, data=None):
195
+ """Calls `enable` or `disable` based on `toggled` value."""
196
+ if self._toggled:
197
+ self.disable(event)
198
+ else:
199
+ self.enable(event)
200
+ self._toggled = not self._toggled
201
+
202
+ def enable(self, event=None):
203
+ """
204
+ Enable the toggle tool.
205
+
206
+ `trigger` calls this method when `toggled` is False.
207
+ """
208
+ pass
209
+
210
+ def disable(self, event=None):
211
+ """
212
+ Disable the toggle tool.
213
+
214
+ `trigger` call this method when `toggled` is True.
215
+
216
+ This can happen in different circumstances.
217
+
218
+ * Click on the toolbar tool button.
219
+ * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
220
+ * Another `ToolToggleBase` derived tool is triggered
221
+ (from the same `.ToolManager`).
222
+ """
223
+ pass
224
+
225
+ @property
226
+ def toggled(self):
227
+ """State of the toggled tool."""
228
+ return self._toggled
229
+
230
+ def set_figure(self, figure):
231
+ toggled = self.toggled
232
+ if toggled:
233
+ if self.figure:
234
+ self.trigger(self, None)
235
+ else:
236
+ # if no figure the internal state is not changed
237
+ # we change it here so next call to trigger will change it back
238
+ self._toggled = False
239
+ super().set_figure(figure)
240
+ if toggled:
241
+ if figure:
242
+ self.trigger(self, None)
243
+ else:
244
+ # if there is no figure, trigger won't change the internal
245
+ # state we change it back
246
+ self._toggled = True
247
+
248
+
249
+ class ToolSetCursor(ToolBase):
250
+ """
251
+ Change to the current cursor while inaxes.
252
+
253
+ This tool, keeps track of all `ToolToggleBase` derived tools, and updates
254
+ the cursor when a tool gets triggered.
255
+ """
256
+ def __init__(self, *args, **kwargs):
257
+ super().__init__(*args, **kwargs)
258
+ self._id_drag = None
259
+ self._current_tool = None
260
+ self._default_cursor = cursors.POINTER
261
+ self._last_cursor = self._default_cursor
262
+ self.toolmanager.toolmanager_connect('tool_added_event',
263
+ self._add_tool_cbk)
264
+ for tool in self.toolmanager.tools.values(): # process current tools
265
+ self._add_tool_cbk(mpl.backend_managers.ToolEvent(
266
+ 'tool_added_event', self.toolmanager, tool))
267
+
268
+ def set_figure(self, figure):
269
+ if self._id_drag:
270
+ self.canvas.mpl_disconnect(self._id_drag)
271
+ super().set_figure(figure)
272
+ if figure:
273
+ self._id_drag = self.canvas.mpl_connect(
274
+ 'motion_notify_event', self._set_cursor_cbk)
275
+
276
+ def _add_tool_cbk(self, event):
277
+ """Process every newly added tool."""
278
+ if getattr(event.tool, 'cursor', None) is not None:
279
+ self.toolmanager.toolmanager_connect(
280
+ f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk)
281
+
282
+ def _tool_trigger_cbk(self, event):
283
+ self._current_tool = event.tool if event.tool.toggled else None
284
+ self._set_cursor_cbk(event.canvasevent)
285
+
286
+ def _set_cursor_cbk(self, event):
287
+ if not event or not self.canvas:
288
+ return
289
+ if (self._current_tool and getattr(event, "inaxes", None)
290
+ and event.inaxes.get_navigate()):
291
+ if self._last_cursor != self._current_tool.cursor:
292
+ self.canvas.set_cursor(self._current_tool.cursor)
293
+ self._last_cursor = self._current_tool.cursor
294
+ elif self._last_cursor != self._default_cursor:
295
+ self.canvas.set_cursor(self._default_cursor)
296
+ self._last_cursor = self._default_cursor
297
+
298
+
299
+ class ToolCursorPosition(ToolBase):
300
+ """
301
+ Send message with the current pointer position.
302
+
303
+ This tool runs in the background reporting the position of the cursor.
304
+ """
305
+ def __init__(self, *args, **kwargs):
306
+ self._id_drag = None
307
+ super().__init__(*args, **kwargs)
308
+
309
+ def set_figure(self, figure):
310
+ if self._id_drag:
311
+ self.canvas.mpl_disconnect(self._id_drag)
312
+ super().set_figure(figure)
313
+ if figure:
314
+ self._id_drag = self.canvas.mpl_connect(
315
+ 'motion_notify_event', self.send_message)
316
+
317
+ def send_message(self, event):
318
+ """Call `matplotlib.backend_managers.ToolManager.message_event`."""
319
+ if self.toolmanager.messagelock.locked():
320
+ return
321
+
322
+ from matplotlib.backend_bases import NavigationToolbar2
323
+ message = NavigationToolbar2._mouse_event_to_message(event)
324
+ self.toolmanager.message_event(message, self)
325
+
326
+
327
+ class RubberbandBase(ToolBase):
328
+ """Draw and remove a rubberband."""
329
+ def trigger(self, sender, event, data=None):
330
+ """Call `draw_rubberband` or `remove_rubberband` based on data."""
331
+ if not self.figure.canvas.widgetlock.available(sender):
332
+ return
333
+ if data is not None:
334
+ self.draw_rubberband(*data)
335
+ else:
336
+ self.remove_rubberband()
337
+
338
+ def draw_rubberband(self, *data):
339
+ """
340
+ Draw rubberband.
341
+
342
+ This method must get implemented per backend.
343
+ """
344
+ raise NotImplementedError
345
+
346
+ def remove_rubberband(self):
347
+ """
348
+ Remove rubberband.
349
+
350
+ This method should get implemented per backend.
351
+ """
352
+ pass
353
+
354
+
355
+ class ToolQuit(ToolBase):
356
+ """Tool to call the figure manager destroy method."""
357
+
358
+ description = 'Quit the figure'
359
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
360
+
361
+ def trigger(self, sender, event, data=None):
362
+ Gcf.destroy_fig(self.figure)
363
+
364
+
365
+ class ToolQuitAll(ToolBase):
366
+ """Tool to call the figure manager destroy method."""
367
+
368
+ description = 'Quit all figures'
369
+ default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
370
+
371
+ def trigger(self, sender, event, data=None):
372
+ Gcf.destroy_all()
373
+
374
+
375
+ class ToolGrid(ToolBase):
376
+ """Tool to toggle the major grids of the figure."""
377
+
378
+ description = 'Toggle major grids'
379
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
380
+
381
+ def trigger(self, sender, event, data=None):
382
+ sentinel = str(uuid.uuid4())
383
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid`
384
+ # to a unique key and sending an appropriate event.
385
+ with (cbook._setattr_cm(event, key=sentinel),
386
+ mpl.rc_context({'keymap.grid': sentinel})):
387
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
388
+
389
+
390
+ class ToolMinorGrid(ToolBase):
391
+ """Tool to toggle the major and minor grids of the figure."""
392
+
393
+ description = 'Toggle major and minor grids'
394
+ default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
395
+
396
+ def trigger(self, sender, event, data=None):
397
+ sentinel = str(uuid.uuid4())
398
+ # Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
399
+ # to a unique key and sending an appropriate event.
400
+ with (cbook._setattr_cm(event, key=sentinel),
401
+ mpl.rc_context({'keymap.grid_minor': sentinel})):
402
+ mpl.backend_bases.key_press_handler(event, self.figure.canvas)
403
+
404
+
405
+ class ToolFullScreen(ToolBase):
406
+ """Tool to toggle full screen."""
407
+
408
+ description = 'Toggle fullscreen mode'
409
+ default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
410
+
411
+ def trigger(self, sender, event, data=None):
412
+ self.figure.canvas.manager.full_screen_toggle()
413
+
414
+
415
+ class AxisScaleBase(ToolToggleBase):
416
+ """Base Tool to toggle between linear and logarithmic."""
417
+
418
+ def trigger(self, sender, event, data=None):
419
+ if event.inaxes is None:
420
+ return
421
+ super().trigger(sender, event, data)
422
+
423
+ def enable(self, event=None):
424
+ self.set_scale(event.inaxes, 'log')
425
+ self.figure.canvas.draw_idle()
426
+
427
+ def disable(self, event=None):
428
+ self.set_scale(event.inaxes, 'linear')
429
+ self.figure.canvas.draw_idle()
430
+
431
+
432
+ class ToolYScale(AxisScaleBase):
433
+ """Tool to toggle between linear and logarithmic scales on the Y axis."""
434
+
435
+ description = 'Toggle scale Y axis'
436
+ default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
437
+
438
+ def set_scale(self, ax, scale):
439
+ ax.set_yscale(scale)
440
+
441
+
442
+ class ToolXScale(AxisScaleBase):
443
+ """Tool to toggle between linear and logarithmic scales on the X axis."""
444
+
445
+ description = 'Toggle scale X axis'
446
+ default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
447
+
448
+ def set_scale(self, ax, scale):
449
+ ax.set_xscale(scale)
450
+
451
+
452
+ class ToolViewsPositions(ToolBase):
453
+ """
454
+ Auxiliary Tool to handle changes in views and positions.
455
+
456
+ Runs in the background and should get used by all the tools that
457
+ need to access the figure's history of views and positions, e.g.
458
+
459
+ * `ToolZoom`
460
+ * `ToolPan`
461
+ * `ToolHome`
462
+ * `ToolBack`
463
+ * `ToolForward`
464
+ """
465
+
466
+ def __init__(self, *args, **kwargs):
467
+ self.views = WeakKeyDictionary()
468
+ self.positions = WeakKeyDictionary()
469
+ self.home_views = WeakKeyDictionary()
470
+ super().__init__(*args, **kwargs)
471
+
472
+ def add_figure(self, figure):
473
+ """Add the current figure to the stack of views and positions."""
474
+
475
+ if figure not in self.views:
476
+ self.views[figure] = cbook._Stack()
477
+ self.positions[figure] = cbook._Stack()
478
+ self.home_views[figure] = WeakKeyDictionary()
479
+ # Define Home
480
+ self.push_current(figure)
481
+ # Make sure we add a home view for new Axes as they're added
482
+ figure.add_axobserver(lambda fig: self.update_home_views(fig))
483
+
484
+ def clear(self, figure):
485
+ """Reset the Axes stack."""
486
+ if figure in self.views:
487
+ self.views[figure].clear()
488
+ self.positions[figure].clear()
489
+ self.home_views[figure].clear()
490
+ self.update_home_views()
491
+
492
+ def update_view(self):
493
+ """
494
+ Update the view limits and position for each Axes from the current
495
+ stack position. If any Axes are present in the figure that aren't in
496
+ the current stack position, use the home view limits for those Axes and
497
+ don't update *any* positions.
498
+ """
499
+
500
+ views = self.views[self.figure]()
501
+ if views is None:
502
+ return
503
+ pos = self.positions[self.figure]()
504
+ if pos is None:
505
+ return
506
+ home_views = self.home_views[self.figure]
507
+ all_axes = self.figure.get_axes()
508
+ for a in all_axes:
509
+ if a in views:
510
+ cur_view = views[a]
511
+ else:
512
+ cur_view = home_views[a]
513
+ a._set_view(cur_view)
514
+
515
+ if set(all_axes).issubset(pos):
516
+ for a in all_axes:
517
+ # Restore both the original and modified positions
518
+ a._set_position(pos[a][0], 'original')
519
+ a._set_position(pos[a][1], 'active')
520
+
521
+ self.figure.canvas.draw_idle()
522
+
523
+ def push_current(self, figure=None):
524
+ """
525
+ Push the current view limits and position onto their respective stacks.
526
+ """
527
+ if not figure:
528
+ figure = self.figure
529
+ views = WeakKeyDictionary()
530
+ pos = WeakKeyDictionary()
531
+ for a in figure.get_axes():
532
+ views[a] = a._get_view()
533
+ pos[a] = self._axes_pos(a)
534
+ self.views[figure].push(views)
535
+ self.positions[figure].push(pos)
536
+
537
+ def _axes_pos(self, ax):
538
+ """
539
+ Return the original and modified positions for the specified Axes.
540
+
541
+ Parameters
542
+ ----------
543
+ ax : matplotlib.axes.Axes
544
+ The `.Axes` to get the positions for.
545
+
546
+ Returns
547
+ -------
548
+ original_position, modified_position
549
+ A tuple of the original and modified positions.
550
+ """
551
+
552
+ return (ax.get_position(True).frozen(),
553
+ ax.get_position().frozen())
554
+
555
+ def update_home_views(self, figure=None):
556
+ """
557
+ Make sure that ``self.home_views`` has an entry for all Axes present
558
+ in the figure.
559
+ """
560
+
561
+ if not figure:
562
+ figure = self.figure
563
+ for a in figure.get_axes():
564
+ if a not in self.home_views[figure]:
565
+ self.home_views[figure][a] = a._get_view()
566
+
567
+ def home(self):
568
+ """Recall the first view and position from the stack."""
569
+ self.views[self.figure].home()
570
+ self.positions[self.figure].home()
571
+
572
+ def back(self):
573
+ """Back one step in the stack of views and positions."""
574
+ self.views[self.figure].back()
575
+ self.positions[self.figure].back()
576
+
577
+ def forward(self):
578
+ """Forward one step in the stack of views and positions."""
579
+ self.views[self.figure].forward()
580
+ self.positions[self.figure].forward()
581
+
582
+
583
+ class ViewsPositionsBase(ToolBase):
584
+ """Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
585
+
586
+ _on_trigger = None
587
+
588
+ def trigger(self, sender, event, data=None):
589
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
590
+ getattr(self.toolmanager.get_tool(_views_positions),
591
+ self._on_trigger)()
592
+ self.toolmanager.get_tool(_views_positions).update_view()
593
+
594
+
595
+ class ToolHome(ViewsPositionsBase):
596
+ """Restore the original view limits."""
597
+
598
+ description = 'Reset original view'
599
+ image = 'mpl-data/images/home'
600
+ default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
601
+ _on_trigger = 'home'
602
+
603
+
604
+ class ToolBack(ViewsPositionsBase):
605
+ """Move back up the view limits stack."""
606
+
607
+ description = 'Back to previous view'
608
+ image = 'mpl-data/images/back'
609
+ default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
610
+ _on_trigger = 'back'
611
+
612
+
613
+ class ToolForward(ViewsPositionsBase):
614
+ """Move forward in the view lim stack."""
615
+
616
+ description = 'Forward to next view'
617
+ image = 'mpl-data/images/forward'
618
+ default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
619
+ _on_trigger = 'forward'
620
+
621
+
622
+ class ConfigureSubplotsBase(ToolBase):
623
+ """Base tool for the configuration of subplots."""
624
+
625
+ description = 'Configure subplots'
626
+ image = 'mpl-data/images/subplots'
627
+
628
+
629
+ class SaveFigureBase(ToolBase):
630
+ """Base tool for figure saving."""
631
+
632
+ description = 'Save the figure'
633
+ image = 'mpl-data/images/filesave'
634
+ default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
635
+
636
+
637
+ class ZoomPanBase(ToolToggleBase):
638
+ """Base class for `ToolZoom` and `ToolPan`."""
639
+ def __init__(self, *args):
640
+ super().__init__(*args)
641
+ self._button_pressed = None
642
+ self._xypress = None
643
+ self._idPress = None
644
+ self._idRelease = None
645
+ self._idScroll = None
646
+ self.base_scale = 2.
647
+ self.scrollthresh = .5 # .5 second scroll threshold
648
+ self.lastscroll = time.time()-self.scrollthresh
649
+
650
+ def enable(self, event=None):
651
+ """Connect press/release events and lock the canvas."""
652
+ self.figure.canvas.widgetlock(self)
653
+ self._idPress = self.figure.canvas.mpl_connect(
654
+ 'button_press_event', self._press)
655
+ self._idRelease = self.figure.canvas.mpl_connect(
656
+ 'button_release_event', self._release)
657
+ self._idScroll = self.figure.canvas.mpl_connect(
658
+ 'scroll_event', self.scroll_zoom)
659
+
660
+ def disable(self, event=None):
661
+ """Release the canvas and disconnect press/release events."""
662
+ self._cancel_action()
663
+ self.figure.canvas.widgetlock.release(self)
664
+ self.figure.canvas.mpl_disconnect(self._idPress)
665
+ self.figure.canvas.mpl_disconnect(self._idRelease)
666
+ self.figure.canvas.mpl_disconnect(self._idScroll)
667
+
668
+ def trigger(self, sender, event, data=None):
669
+ self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
670
+ super().trigger(sender, event, data)
671
+ new_navigate_mode = self.name.upper() if self.toggled else None
672
+ for ax in self.figure.axes:
673
+ ax.set_navigate_mode(new_navigate_mode)
674
+
675
+ def scroll_zoom(self, event):
676
+ # https://gist.github.com/tacaswell/3144287
677
+ if event.inaxes is None:
678
+ return
679
+
680
+ if event.button == 'up':
681
+ # deal with zoom in
682
+ scl = self.base_scale
683
+ elif event.button == 'down':
684
+ # deal with zoom out
685
+ scl = 1/self.base_scale
686
+ else:
687
+ # deal with something that should never happen
688
+ scl = 1
689
+
690
+ ax = event.inaxes
691
+ ax._set_view_from_bbox([event.x, event.y, scl])
692
+
693
+ # If last scroll was done within the timing threshold, delete the
694
+ # previous view
695
+ if (time.time()-self.lastscroll) < self.scrollthresh:
696
+ self.toolmanager.get_tool(_views_positions).back()
697
+
698
+ self.figure.canvas.draw_idle() # force re-draw
699
+
700
+ self.lastscroll = time.time()
701
+ self.toolmanager.get_tool(_views_positions).push_current()
702
+
703
+
704
+ class ToolZoom(ZoomPanBase):
705
+ """A Tool for zooming using a rectangle selector."""
706
+
707
+ description = 'Zoom to rectangle'
708
+ image = 'mpl-data/images/zoom_to_rect'
709
+ default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
710
+ cursor = cursors.SELECT_REGION
711
+ radio_group = 'default'
712
+
713
+ def __init__(self, *args):
714
+ super().__init__(*args)
715
+ self._ids_zoom = []
716
+
717
+ def _cancel_action(self):
718
+ for zoom_id in self._ids_zoom:
719
+ self.figure.canvas.mpl_disconnect(zoom_id)
720
+ self.toolmanager.trigger_tool('rubberband', self)
721
+ self.figure.canvas.draw_idle()
722
+ self._xypress = None
723
+ self._button_pressed = None
724
+ self._ids_zoom = []
725
+ return
726
+
727
+ def _press(self, event):
728
+ """Callback for mouse button presses in zoom-to-rectangle mode."""
729
+
730
+ # If we're already in the middle of a zoom, pressing another
731
+ # button works to "cancel"
732
+ if self._ids_zoom:
733
+ self._cancel_action()
734
+
735
+ if event.button == 1:
736
+ self._button_pressed = 1
737
+ elif event.button == 3:
738
+ self._button_pressed = 3
739
+ else:
740
+ self._cancel_action()
741
+ return
742
+
743
+ x, y = event.x, event.y
744
+
745
+ self._xypress = []
746
+ for i, a in enumerate(self.figure.get_axes()):
747
+ if (x is not None and y is not None and a.in_axes(event) and
748
+ a.get_navigate() and a.can_zoom()):
749
+ self._xypress.append((x, y, a, i, a._get_view()))
750
+
751
+ id1 = self.figure.canvas.mpl_connect(
752
+ 'motion_notify_event', self._mouse_move)
753
+ id2 = self.figure.canvas.mpl_connect(
754
+ 'key_press_event', self._switch_on_zoom_mode)
755
+ id3 = self.figure.canvas.mpl_connect(
756
+ 'key_release_event', self._switch_off_zoom_mode)
757
+
758
+ self._ids_zoom = id1, id2, id3
759
+ self._zoom_mode = event.key
760
+
761
+ def _switch_on_zoom_mode(self, event):
762
+ self._zoom_mode = event.key
763
+ self._mouse_move(event)
764
+
765
+ def _switch_off_zoom_mode(self, event):
766
+ self._zoom_mode = None
767
+ self._mouse_move(event)
768
+
769
+ def _mouse_move(self, event):
770
+ """Callback for mouse moves in zoom-to-rectangle mode."""
771
+
772
+ if self._xypress:
773
+ x, y = event.x, event.y
774
+ lastx, lasty, a, ind, view = self._xypress[0]
775
+ (x1, y1), (x2, y2) = np.clip(
776
+ [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
777
+ if self._zoom_mode == "x":
778
+ y1, y2 = a.bbox.intervaly
779
+ elif self._zoom_mode == "y":
780
+ x1, x2 = a.bbox.intervalx
781
+ self.toolmanager.trigger_tool(
782
+ 'rubberband', self, data=(x1, y1, x2, y2))
783
+
784
+ def _release(self, event):
785
+ """Callback for mouse button releases in zoom-to-rectangle mode."""
786
+
787
+ for zoom_id in self._ids_zoom:
788
+ self.figure.canvas.mpl_disconnect(zoom_id)
789
+ self._ids_zoom = []
790
+
791
+ if not self._xypress:
792
+ self._cancel_action()
793
+ return
794
+
795
+ done_ax = []
796
+
797
+ for cur_xypress in self._xypress:
798
+ x, y = event.x, event.y
799
+ lastx, lasty, a, _ind, view = cur_xypress
800
+ # ignore singular clicks - 5 pixels is a threshold
801
+ if abs(x - lastx) < 5 or abs(y - lasty) < 5:
802
+ self._cancel_action()
803
+ return
804
+
805
+ # detect twinx, twiny Axes and avoid double zooming
806
+ twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
807
+ twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
808
+ done_ax.append(a)
809
+
810
+ if self._button_pressed == 1:
811
+ direction = 'in'
812
+ elif self._button_pressed == 3:
813
+ direction = 'out'
814
+ else:
815
+ continue
816
+
817
+ a._set_view_from_bbox((lastx, lasty, x, y), direction,
818
+ self._zoom_mode, twinx, twiny)
819
+
820
+ self._zoom_mode = None
821
+ self.toolmanager.get_tool(_views_positions).push_current()
822
+ self._cancel_action()
823
+
824
+
825
+ class ToolPan(ZoomPanBase):
826
+ """Pan Axes with left mouse, zoom with right."""
827
+
828
+ default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
829
+ description = 'Pan axes with left mouse, zoom with right'
830
+ image = 'mpl-data/images/move'
831
+ cursor = cursors.MOVE
832
+ radio_group = 'default'
833
+
834
+ def __init__(self, *args):
835
+ super().__init__(*args)
836
+ self._id_drag = None
837
+
838
+ def _cancel_action(self):
839
+ self._button_pressed = None
840
+ self._xypress = []
841
+ self.figure.canvas.mpl_disconnect(self._id_drag)
842
+ self.toolmanager.messagelock.release(self)
843
+ self.figure.canvas.draw_idle()
844
+
845
+ def _press(self, event):
846
+ if event.button == 1:
847
+ self._button_pressed = 1
848
+ elif event.button == 3:
849
+ self._button_pressed = 3
850
+ else:
851
+ self._cancel_action()
852
+ return
853
+
854
+ x, y = event.x, event.y
855
+
856
+ self._xypress = []
857
+ for i, a in enumerate(self.figure.get_axes()):
858
+ if (x is not None and y is not None and a.in_axes(event) and
859
+ a.get_navigate() and a.can_pan()):
860
+ a.start_pan(x, y, event.button)
861
+ self._xypress.append((a, i))
862
+ self.toolmanager.messagelock(self)
863
+ self._id_drag = self.figure.canvas.mpl_connect(
864
+ 'motion_notify_event', self._mouse_move)
865
+
866
+ def _release(self, event):
867
+ if self._button_pressed is None:
868
+ self._cancel_action()
869
+ return
870
+
871
+ self.figure.canvas.mpl_disconnect(self._id_drag)
872
+ self.toolmanager.messagelock.release(self)
873
+
874
+ for a, _ind in self._xypress:
875
+ a.end_pan()
876
+ if not self._xypress:
877
+ self._cancel_action()
878
+ return
879
+
880
+ self.toolmanager.get_tool(_views_positions).push_current()
881
+ self._cancel_action()
882
+
883
+ def _mouse_move(self, event):
884
+ for a, _ind in self._xypress:
885
+ # safer to use the recorded button at the _press than current
886
+ # button: # multiple button can get pressed during motion...
887
+ a.drag_pan(self._button_pressed, event.key, event.x, event.y)
888
+ self.toolmanager.canvas.draw_idle()
889
+
890
+
891
+ class ToolHelpBase(ToolBase):
892
+ description = 'Print tool list, shortcuts and description'
893
+ default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
894
+ image = 'mpl-data/images/help'
895
+
896
+ @staticmethod
897
+ def format_shortcut(key_sequence):
898
+ """
899
+ Convert a shortcut string from the notation used in rc config to the
900
+ standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
901
+ """
902
+ return (key_sequence if len(key_sequence) == 1 else
903
+ re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
904
+
905
+ def _format_tool_keymap(self, name):
906
+ keymaps = self.toolmanager.get_tool_keymap(name)
907
+ return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
908
+
909
+ def _get_help_entries(self):
910
+ return [(name, self._format_tool_keymap(name), tool.description)
911
+ for name, tool in sorted(self.toolmanager.tools.items())
912
+ if tool.description]
913
+
914
+ def _get_help_text(self):
915
+ entries = self._get_help_entries()
916
+ entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
917
+ return "\n".join(entries)
918
+
919
+ def _get_help_html(self):
920
+ fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
921
+ rows = [fmt.format(
922
+ "<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
923
+ rows += [fmt.format(*row) for row in self._get_help_entries()]
924
+ return ("<style>td {padding: 0px 4px}</style>"
925
+ "<table><thead>" + rows[0] + "</thead>"
926
+ "<tbody>".join(rows[1:]) + "</tbody></table>")
927
+
928
+
929
+ class ToolCopyToClipboardBase(ToolBase):
930
+ """Tool to copy the figure to the clipboard."""
931
+
932
+ description = 'Copy the canvas figure to clipboard'
933
+ default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
934
+
935
+ def trigger(self, *args, **kwargs):
936
+ message = "Copy tool is not available"
937
+ self.toolmanager.message_event(message, self)
938
+
939
+
940
+ default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
941
+ 'zoom': ToolZoom, 'pan': ToolPan,
942
+ 'subplots': ConfigureSubplotsBase,
943
+ 'save': SaveFigureBase,
944
+ 'grid': ToolGrid,
945
+ 'grid_minor': ToolMinorGrid,
946
+ 'fullscreen': ToolFullScreen,
947
+ 'quit': ToolQuit,
948
+ 'quit_all': ToolQuitAll,
949
+ 'xscale': ToolXScale,
950
+ 'yscale': ToolYScale,
951
+ 'position': ToolCursorPosition,
952
+ _views_positions: ToolViewsPositions,
953
+ 'cursor': ToolSetCursor,
954
+ 'rubberband': RubberbandBase,
955
+ 'help': ToolHelpBase,
956
+ 'copy': ToolCopyToClipboardBase,
957
+ }
958
+
959
+ default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
960
+ ['zoompan', ['pan', 'zoom', 'subplots']],
961
+ ['io', ['save', 'help']]]
962
+
963
+
964
+ def add_tools_to_manager(toolmanager, tools=default_tools):
965
+ """
966
+ Add multiple tools to a `.ToolManager`.
967
+
968
+ Parameters
969
+ ----------
970
+ toolmanager : `.backend_managers.ToolManager`
971
+ Manager to which the tools are added.
972
+ tools : {str: class_like}, optional
973
+ The tools to add in a {name: tool} dict, see
974
+ `.backend_managers.ToolManager.add_tool` for more info.
975
+ """
976
+
977
+ for name, tool in tools.items():
978
+ toolmanager.add_tool(name, tool)
979
+
980
+
981
+ def add_tools_to_container(container, tools=default_toolbar_tools):
982
+ """
983
+ Add multiple tools to the container.
984
+
985
+ Parameters
986
+ ----------
987
+ container : Container
988
+ `.backend_bases.ToolContainerBase` object that will get the tools
989
+ added.
990
+ tools : list, optional
991
+ List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
992
+ where the tools ``[tool1, tool2, ...]`` will display in group1.
993
+ See `.backend_bases.ToolContainerBase.add_tool` for details.
994
+ """
995
+
996
+ for group, grouptools in tools:
997
+ for position, tool in enumerate(grouptools):
998
+ container.add_tool(tool, group, position)
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backend_tools.pyi ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from matplotlib import cbook
3
+ from matplotlib.axes import Axes
4
+ from matplotlib.backend_bases import ToolContainerBase, FigureCanvasBase
5
+ from matplotlib.backend_managers import ToolManager, ToolEvent
6
+ from matplotlib.figure import Figure
7
+ from matplotlib.scale import ScaleBase
8
+
9
+ from typing import Any, cast
10
+
11
+ class Cursors(enum.IntEnum):
12
+ POINTER = cast(int, ...)
13
+ HAND = cast(int, ...)
14
+ SELECT_REGION = cast(int, ...)
15
+ MOVE = cast(int, ...)
16
+ WAIT = cast(int, ...)
17
+ RESIZE_HORIZONTAL = cast(int, ...)
18
+ RESIZE_VERTICAL = cast(int, ...)
19
+
20
+ cursors = Cursors
21
+
22
+ class ToolBase:
23
+ @property
24
+ def default_keymap(self) -> list[str] | None: ...
25
+ description: str | None
26
+ image: str | None
27
+ def __init__(self, toolmanager: ToolManager, name: str) -> None: ...
28
+ @property
29
+ def name(self) -> str: ...
30
+ @property
31
+ def toolmanager(self) -> ToolManager: ...
32
+ @property
33
+ def canvas(self) -> FigureCanvasBase | None: ...
34
+ @property
35
+ def figure(self) -> Figure | None: ...
36
+ @figure.setter
37
+ def figure(self, figure: Figure | None) -> None: ...
38
+ def set_figure(self, figure: Figure | None) -> None: ...
39
+ def trigger(self, sender: Any, event: ToolEvent, data: Any = ...) -> None: ...
40
+
41
+ class ToolToggleBase(ToolBase):
42
+ radio_group: str | None
43
+ cursor: Cursors | None
44
+ default_toggled: bool
45
+ def __init__(self, *args, **kwargs) -> None: ...
46
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
47
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
48
+ @property
49
+ def toggled(self) -> bool: ...
50
+ def set_figure(self, figure: Figure | None) -> None: ...
51
+
52
+ class ToolSetCursor(ToolBase): ...
53
+
54
+ class ToolCursorPosition(ToolBase):
55
+ def send_message(self, event: ToolEvent) -> None: ...
56
+
57
+ class RubberbandBase(ToolBase):
58
+ def draw_rubberband(self, *data) -> None: ...
59
+ def remove_rubberband(self) -> None: ...
60
+
61
+ class ToolQuit(ToolBase): ...
62
+ class ToolQuitAll(ToolBase): ...
63
+ class ToolGrid(ToolBase): ...
64
+ class ToolMinorGrid(ToolBase): ...
65
+ class ToolFullScreen(ToolBase): ...
66
+
67
+ class AxisScaleBase(ToolToggleBase):
68
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
69
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
70
+
71
+ class ToolYScale(AxisScaleBase):
72
+ def set_scale(self, ax: Axes, scale: str | ScaleBase) -> None: ...
73
+
74
+ class ToolXScale(AxisScaleBase):
75
+ def set_scale(self, ax, scale: str | ScaleBase) -> None: ...
76
+
77
+ class ToolViewsPositions(ToolBase):
78
+ views: dict[Figure | Axes, cbook._Stack]
79
+ positions: dict[Figure | Axes, cbook._Stack]
80
+ home_views: dict[Figure, dict[Axes, tuple[float, float, float, float]]]
81
+ def add_figure(self, figure: Figure) -> None: ...
82
+ def clear(self, figure: Figure) -> None: ...
83
+ def update_view(self) -> None: ...
84
+ def push_current(self, figure: Figure | None = ...) -> None: ...
85
+ def update_home_views(self, figure: Figure | None = ...) -> None: ...
86
+ def home(self) -> None: ...
87
+ def back(self) -> None: ...
88
+ def forward(self) -> None: ...
89
+
90
+ class ViewsPositionsBase(ToolBase): ...
91
+ class ToolHome(ViewsPositionsBase): ...
92
+ class ToolBack(ViewsPositionsBase): ...
93
+ class ToolForward(ViewsPositionsBase): ...
94
+ class ConfigureSubplotsBase(ToolBase): ...
95
+ class SaveFigureBase(ToolBase): ...
96
+
97
+ class ZoomPanBase(ToolToggleBase):
98
+ base_scale: float
99
+ scrollthresh: float
100
+ lastscroll: float
101
+ def __init__(self, *args) -> None: ...
102
+ def enable(self, event: ToolEvent | None = ...) -> None: ...
103
+ def disable(self, event: ToolEvent | None = ...) -> None: ...
104
+ def scroll_zoom(self, event: ToolEvent) -> None: ...
105
+
106
+ class ToolZoom(ZoomPanBase): ...
107
+ class ToolPan(ZoomPanBase): ...
108
+
109
+ class ToolHelpBase(ToolBase):
110
+ @staticmethod
111
+ def format_shortcut(key_sequence: str) -> str: ...
112
+
113
+ class ToolCopyToClipboardBase(ToolBase): ...
114
+
115
+ default_tools: dict[str, ToolBase]
116
+ default_toolbar_tools: list[list[str | list[str]]]
117
+
118
+ def add_tools_to_manager(
119
+ toolmanager: ToolManager, tools: dict[str, type[ToolBase]] = ...
120
+ ) -> None: ...
121
+ def add_tools_to_container(container: ToolContainerBase, tools: list[Any] = ...) -> None: ...
workspace/outputs/audit_venv/lib/python3.11/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
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f23270158ad82041a491e010c17440961919edf741a327501d6b0b289a1f762
3
+ size 601792
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_agg.pyi ADDED
File without changes
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_gtk.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common code for GTK3 and GTK4 backends.
3
+ """
4
+
5
+ import logging
6
+ import sys
7
+
8
+ import matplotlib as mpl
9
+ from matplotlib import _api, backend_tools, cbook
10
+ from matplotlib._pylab_helpers import Gcf
11
+ from matplotlib.backend_bases import (
12
+ _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
13
+ TimerBase)
14
+ from matplotlib.backend_tools import Cursors
15
+
16
+ import gi
17
+ # The GTK3/GTK4 backends will have already called `gi.require_version` to set
18
+ # the desired GTK.
19
+ from gi.repository import Gdk, Gio, GLib, Gtk
20
+
21
+
22
+ try:
23
+ gi.require_foreign("cairo")
24
+ except ImportError as e:
25
+ raise ImportError("Gtk-based backends require cairo") from e
26
+
27
+ _log = logging.getLogger(__name__)
28
+ _application = None # Placeholder
29
+
30
+
31
+ def _shutdown_application(app):
32
+ # The application might prematurely shut down if Ctrl-C'd out of IPython,
33
+ # so close all windows.
34
+ for win in app.get_windows():
35
+ win.close()
36
+ # The PyGObject wrapper incorrectly thinks that None is not allowed, or we
37
+ # would call this:
38
+ # Gio.Application.set_default(None)
39
+ # Instead, we set this property and ignore default applications with it:
40
+ app._created_by_matplotlib = True
41
+ global _application
42
+ _application = None
43
+
44
+
45
+ def _create_application():
46
+ global _application
47
+
48
+ if _application is None:
49
+ app = Gio.Application.get_default()
50
+ if app is None or getattr(app, '_created_by_matplotlib', False):
51
+ # display_is_valid returns False only if on Linux and neither X11
52
+ # nor Wayland display can be opened.
53
+ if not mpl._c_internal_utils.display_is_valid():
54
+ raise RuntimeError('Invalid DISPLAY variable')
55
+ _application = Gtk.Application.new('org.matplotlib.Matplotlib3',
56
+ Gio.ApplicationFlags.NON_UNIQUE)
57
+ # The activate signal must be connected, but we don't care for
58
+ # handling it, since we don't do any remote processing.
59
+ _application.connect('activate', lambda *args, **kwargs: None)
60
+ _application.connect('shutdown', _shutdown_application)
61
+ _application.register()
62
+ cbook._setup_new_guiapp()
63
+ else:
64
+ _application = app
65
+
66
+ return _application
67
+
68
+
69
+ def mpl_to_gtk_cursor_name(mpl_cursor):
70
+ return _api.check_getitem({
71
+ Cursors.MOVE: "move",
72
+ Cursors.HAND: "pointer",
73
+ Cursors.POINTER: "default",
74
+ Cursors.SELECT_REGION: "crosshair",
75
+ Cursors.WAIT: "wait",
76
+ Cursors.RESIZE_HORIZONTAL: "ew-resize",
77
+ Cursors.RESIZE_VERTICAL: "ns-resize",
78
+ }, cursor=mpl_cursor)
79
+
80
+
81
+ class TimerGTK(TimerBase):
82
+ """Subclass of `.TimerBase` using GTK timer events."""
83
+
84
+ def __init__(self, *args, **kwargs):
85
+ self._timer = None
86
+ super().__init__(*args, **kwargs)
87
+
88
+ def _timer_start(self):
89
+ # Need to stop it, otherwise we potentially leak a timer id that will
90
+ # never be stopped.
91
+ self._timer_stop()
92
+ self._timer = GLib.timeout_add(self._interval, self._on_timer)
93
+
94
+ def _timer_stop(self):
95
+ if self._timer is not None:
96
+ GLib.source_remove(self._timer)
97
+ self._timer = None
98
+
99
+ def _timer_set_interval(self):
100
+ # Only stop and restart it if the timer has already been started.
101
+ if self._timer is not None:
102
+ self._timer_stop()
103
+ self._timer_start()
104
+
105
+ def _on_timer(self):
106
+ super()._on_timer()
107
+
108
+ # Gtk timeout_add() requires that the callback returns True if it
109
+ # is to be called again.
110
+ if self.callbacks and not self._single:
111
+ return True
112
+ else:
113
+ self._timer = None
114
+ return False
115
+
116
+
117
+ class _FigureCanvasGTK(FigureCanvasBase):
118
+ _timer_cls = TimerGTK
119
+
120
+
121
+ class _FigureManagerGTK(FigureManagerBase):
122
+ """
123
+ Attributes
124
+ ----------
125
+ canvas : `FigureCanvas`
126
+ The FigureCanvas instance
127
+ num : int or str
128
+ The Figure number
129
+ toolbar : Gtk.Toolbar or Gtk.Box
130
+ The toolbar
131
+ vbox : Gtk.VBox
132
+ The Gtk.VBox containing the canvas and toolbar
133
+ window : Gtk.Window
134
+ The Gtk.Window
135
+ """
136
+
137
+ def __init__(self, canvas, num):
138
+ self._gtk_ver = gtk_ver = Gtk.get_major_version()
139
+
140
+ app = _create_application()
141
+ self.window = Gtk.Window()
142
+ app.add_window(self.window)
143
+ super().__init__(canvas, num)
144
+
145
+ if gtk_ver == 3:
146
+ icon_ext = "png" if sys.platform == "win32" else "svg"
147
+ self.window.set_icon_from_file(
148
+ str(cbook._get_data_path(f"images/matplotlib.{icon_ext}")))
149
+
150
+ self.vbox = Gtk.Box()
151
+ self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
152
+
153
+ if gtk_ver == 3:
154
+ self.window.add(self.vbox)
155
+ self.vbox.show()
156
+ self.canvas.show()
157
+ self.vbox.pack_start(self.canvas, True, True, 0)
158
+ elif gtk_ver == 4:
159
+ self.window.set_child(self.vbox)
160
+ self.vbox.prepend(self.canvas)
161
+
162
+ # calculate size for window
163
+ w, h = self.canvas.get_width_height()
164
+
165
+ if self.toolbar is not None:
166
+ if gtk_ver == 3:
167
+ self.toolbar.show()
168
+ self.vbox.pack_end(self.toolbar, False, False, 0)
169
+ elif gtk_ver == 4:
170
+ sw = Gtk.ScrolledWindow(vscrollbar_policy=Gtk.PolicyType.NEVER)
171
+ sw.set_child(self.toolbar)
172
+ self.vbox.append(sw)
173
+ min_size, nat_size = self.toolbar.get_preferred_size()
174
+ h += nat_size.height
175
+
176
+ self.window.set_default_size(w, h)
177
+
178
+ self._destroying = False
179
+ self.window.connect("destroy", lambda *args: Gcf.destroy(self))
180
+ self.window.connect({3: "delete_event", 4: "close-request"}[gtk_ver],
181
+ lambda *args: Gcf.destroy(self))
182
+ if mpl.is_interactive():
183
+ self.window.show()
184
+ self.canvas.draw_idle()
185
+
186
+ self.canvas.grab_focus()
187
+
188
+ def destroy(self, *args):
189
+ if self._destroying:
190
+ # Otherwise, this can be called twice when the user presses 'q',
191
+ # which calls Gcf.destroy(self), then this destroy(), then triggers
192
+ # Gcf.destroy(self) once again via
193
+ # `connect("destroy", lambda *args: Gcf.destroy(self))`.
194
+ return
195
+ self._destroying = True
196
+ self.window.destroy()
197
+ self.canvas.destroy()
198
+
199
+ @classmethod
200
+ def start_main_loop(cls):
201
+ global _application
202
+ if _application is None:
203
+ return
204
+
205
+ try:
206
+ _application.run() # Quits when all added windows close.
207
+ except KeyboardInterrupt:
208
+ # Ensure all windows can process their close event from
209
+ # _shutdown_application.
210
+ context = GLib.MainContext.default()
211
+ while context.pending():
212
+ context.iteration(True)
213
+ raise
214
+ finally:
215
+ # Running after quit is undefined, so create a new one next time.
216
+ _application = None
217
+
218
+ def show(self):
219
+ # show the figure window
220
+ self.window.show()
221
+ self.canvas.draw()
222
+ if mpl.rcParams["figure.raise_window"]:
223
+ meth_name = {3: "get_window", 4: "get_surface"}[self._gtk_ver]
224
+ if getattr(self.window, meth_name)():
225
+ self.window.present()
226
+ else:
227
+ # If this is called by a callback early during init,
228
+ # self.window (a GtkWindow) may not have an associated
229
+ # low-level GdkWindow (on GTK3) or GdkSurface (on GTK4) yet,
230
+ # and present() would crash.
231
+ _api.warn_external("Cannot raise window yet to be setup")
232
+
233
+ def full_screen_toggle(self):
234
+ is_fullscreen = {
235
+ 3: lambda w: (w.get_window().get_state()
236
+ & Gdk.WindowState.FULLSCREEN),
237
+ 4: lambda w: w.is_fullscreen(),
238
+ }[self._gtk_ver]
239
+ if is_fullscreen(self.window):
240
+ self.window.unfullscreen()
241
+ else:
242
+ self.window.fullscreen()
243
+
244
+ def get_window_title(self):
245
+ return self.window.get_title()
246
+
247
+ def set_window_title(self, title):
248
+ self.window.set_title(title)
249
+
250
+ def resize(self, width, height):
251
+ width = int(width / self.canvas.device_pixel_ratio)
252
+ height = int(height / self.canvas.device_pixel_ratio)
253
+ if self.toolbar:
254
+ min_size, nat_size = self.toolbar.get_preferred_size()
255
+ height += nat_size.height
256
+ canvas_size = self.canvas.get_allocation()
257
+ if self._gtk_ver >= 4 or canvas_size.width == canvas_size.height == 1:
258
+ # A canvas size of (1, 1) cannot exist in most cases, because
259
+ # window decorations would prevent such a small window. This call
260
+ # must be before the window has been mapped and widgets have been
261
+ # sized, so just change the window's starting size.
262
+ self.window.set_default_size(width, height)
263
+ else:
264
+ self.window.resize(width, height)
265
+
266
+
267
+ class _NavigationToolbar2GTK(NavigationToolbar2):
268
+ # Must be implemented in GTK3/GTK4 backends:
269
+ # * __init__
270
+ # * save_figure
271
+
272
+ def set_message(self, s):
273
+ escaped = GLib.markup_escape_text(s)
274
+ self.message.set_markup(f'<small>{escaped}</small>')
275
+
276
+ def draw_rubberband(self, event, x0, y0, x1, y1):
277
+ height = self.canvas.figure.bbox.height
278
+ y1 = height - y1
279
+ y0 = height - y0
280
+ rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
281
+ self.canvas._draw_rubberband(rect)
282
+
283
+ def remove_rubberband(self):
284
+ self.canvas._draw_rubberband(None)
285
+
286
+ def _update_buttons_checked(self):
287
+ for name, active in [("Pan", "PAN"), ("Zoom", "ZOOM")]:
288
+ button = self._gtk_ids.get(name)
289
+ if button:
290
+ with button.handler_block(button._signal_handler):
291
+ button.set_active(self.mode.name == active)
292
+
293
+ def pan(self, *args):
294
+ super().pan(*args)
295
+ self._update_buttons_checked()
296
+
297
+ def zoom(self, *args):
298
+ super().zoom(*args)
299
+ self._update_buttons_checked()
300
+
301
+ def set_history_buttons(self):
302
+ can_backward = self._nav_stack._pos > 0
303
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
304
+ if 'Back' in self._gtk_ids:
305
+ self._gtk_ids['Back'].set_sensitive(can_backward)
306
+ if 'Forward' in self._gtk_ids:
307
+ self._gtk_ids['Forward'].set_sensitive(can_forward)
308
+
309
+
310
+ class RubberbandGTK(backend_tools.RubberbandBase):
311
+ def draw_rubberband(self, x0, y0, x1, y1):
312
+ _NavigationToolbar2GTK.draw_rubberband(
313
+ self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
314
+
315
+ def remove_rubberband(self):
316
+ _NavigationToolbar2GTK.remove_rubberband(
317
+ self._make_classic_style_pseudo_toolbar())
318
+
319
+
320
+ class ConfigureSubplotsGTK(backend_tools.ConfigureSubplotsBase):
321
+ def trigger(self, *args):
322
+ _NavigationToolbar2GTK.configure_subplots(self, None)
323
+
324
+
325
+ class _BackendGTK(_Backend):
326
+ backend_version = "{}.{}.{}".format(
327
+ Gtk.get_major_version(),
328
+ Gtk.get_minor_version(),
329
+ Gtk.get_micro_version(),
330
+ )
331
+ mainloop = _FigureManagerGTK.start_main_loop
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_pdf_ps.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common functionality between the PDF and PS backends.
3
+ """
4
+
5
+ from io import BytesIO
6
+ import functools
7
+ import logging
8
+
9
+ from fontTools import subset
10
+
11
+ import matplotlib as mpl
12
+ from .. import font_manager, ft2font
13
+ from .._afm import AFM
14
+ from ..backend_bases import RendererBase
15
+
16
+
17
+ @functools.lru_cache(50)
18
+ def _cached_get_afm_from_fname(fname):
19
+ with open(fname, "rb") as fh:
20
+ return AFM(fh)
21
+
22
+
23
+ def get_glyphs_subset(fontfile, characters):
24
+ """
25
+ Subset a TTF font
26
+
27
+ Reads the named fontfile and restricts the font to the characters.
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
+ Returns
37
+ -------
38
+ fontTools.ttLib.ttFont.TTFont
39
+ An open font object representing the subset, which needs to
40
+ be closed by the caller.
41
+ """
42
+
43
+ options = subset.Options(glyph_names=True, recommended_glyphs=True)
44
+
45
+ # Prevent subsetting extra tables.
46
+ options.drop_tables += [
47
+ 'FFTM', # FontForge Timestamp.
48
+ 'PfEd', # FontForge personal table.
49
+ 'BDF', # X11 BDF header.
50
+ 'meta', # Metadata stores design/supported languages (meaningless for subsets).
51
+ 'MERG', # Merge Table.
52
+ 'TSIV', # Microsoft Visual TrueType extension.
53
+ 'Zapf', # Information about the individual glyphs in the font.
54
+ 'bdat', # The bitmap data table.
55
+ 'bloc', # The bitmap location table.
56
+ 'cidg', # CID to Glyph ID table (Apple Advanced Typography).
57
+ 'fdsc', # The font descriptors table.
58
+ 'feat', # Feature name table (Apple Advanced Typography).
59
+ 'fmtx', # The Font Metrics Table.
60
+ 'fond', # Data-fork font information (Apple Advanced Typography).
61
+ 'just', # The justification table (Apple Advanced Typography).
62
+ 'kerx', # An extended kerning table (Apple Advanced Typography).
63
+ 'ltag', # Language Tag.
64
+ 'morx', # Extended Glyph Metamorphosis Table.
65
+ 'trak', # Tracking table.
66
+ 'xref', # The cross-reference table (some Apple font tooling information).
67
+ ]
68
+ # if fontfile is a ttc, specify font number
69
+ if fontfile.endswith(".ttc"):
70
+ options.font_number = 0
71
+
72
+ font = subset.load_font(fontfile, options)
73
+ subsetter = subset.Subsetter(options=options)
74
+ subsetter.populate(text=characters)
75
+ subsetter.subset(font)
76
+ return font
77
+
78
+
79
+ def font_as_file(font):
80
+ """
81
+ Convert a TTFont object into a file-like object.
82
+
83
+ Parameters
84
+ ----------
85
+ font : fontTools.ttLib.ttFont.TTFont
86
+ A font object
87
+
88
+ Returns
89
+ -------
90
+ BytesIO
91
+ A file object with the font saved into it
92
+ """
93
+ fh = BytesIO()
94
+ font.save(fh, reorderTables=False)
95
+ return fh
96
+
97
+
98
+ class CharacterTracker:
99
+ """
100
+ Helper for font subsetting by the pdf and ps backends.
101
+
102
+ Maintains a mapping of font paths to the set of character codepoints that
103
+ are being used from that font.
104
+ """
105
+
106
+ def __init__(self):
107
+ self.used = {}
108
+
109
+ def track(self, font, s):
110
+ """Record that string *s* is being typeset using font *font*."""
111
+ char_to_font = font._get_fontmap(s)
112
+ for _c, _f in char_to_font.items():
113
+ self.used.setdefault(_f.fname, set()).add(ord(_c))
114
+
115
+ def track_glyph(self, font, glyph):
116
+ """Record that codepoint *glyph* is being typeset using font *font*."""
117
+ self.used.setdefault(font.fname, set()).add(glyph)
118
+
119
+
120
+ class RendererPDFPSBase(RendererBase):
121
+ # The following attributes must be defined by the subclasses:
122
+ # - _afm_font_dir
123
+ # - _use_afm_rc_name
124
+
125
+ def __init__(self, width, height):
126
+ super().__init__()
127
+ self.width = width
128
+ self.height = height
129
+
130
+ def flipy(self):
131
+ # docstring inherited
132
+ return False # y increases from bottom to top.
133
+
134
+ def option_scale_image(self):
135
+ # docstring inherited
136
+ return True # PDF and PS support arbitrary image scaling.
137
+
138
+ def option_image_nocomposite(self):
139
+ # docstring inherited
140
+ # Decide whether to composite image based on rcParam value.
141
+ return not mpl.rcParams["image.composite_image"]
142
+
143
+ def get_canvas_width_height(self):
144
+ # docstring inherited
145
+ return self.width * 72.0, self.height * 72.0
146
+
147
+ def get_text_width_height_descent(self, s, prop, ismath):
148
+ # docstring inherited
149
+ if ismath == "TeX":
150
+ return super().get_text_width_height_descent(s, prop, ismath)
151
+ elif ismath:
152
+ parse = self._text2path.mathtext_parser.parse(s, 72, prop)
153
+ return parse.width, parse.height, parse.depth
154
+ elif mpl.rcParams[self._use_afm_rc_name]:
155
+ font = self._get_font_afm(prop)
156
+ l, b, w, h, d = font.get_str_bbox_and_descent(s)
157
+ scale = prop.get_size_in_points() / 1000
158
+ w *= scale
159
+ h *= scale
160
+ d *= scale
161
+ return w, h, d
162
+ else:
163
+ font = self._get_font_ttf(prop)
164
+ font.set_text(s, 0.0, flags=ft2font.LoadFlags.NO_HINTING)
165
+ w, h = font.get_width_height()
166
+ d = font.get_descent()
167
+ scale = 1 / 64
168
+ w *= scale
169
+ h *= scale
170
+ d *= scale
171
+ return w, h, d
172
+
173
+ def _get_font_afm(self, prop):
174
+ fname = font_manager.findfont(
175
+ prop, fontext="afm", directory=self._afm_font_dir)
176
+ return _cached_get_afm_from_fname(fname)
177
+
178
+ def _get_font_ttf(self, prop):
179
+ fnames = font_manager.fontManager._find_fonts_by_props(prop)
180
+ try:
181
+ font = font_manager.get_font(fnames)
182
+ font.clear()
183
+ font.set_size(prop.get_size_in_points(), 72)
184
+ return font
185
+ except RuntimeError:
186
+ logging.getLogger(__name__).warning(
187
+ "The PostScript/PDF backend does not currently "
188
+ "support the selected font (%s).", fnames)
189
+ raise
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_backend_tk.py ADDED
@@ -0,0 +1,1105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ import weakref
3
+ from contextlib import contextmanager
4
+ import logging
5
+ import math
6
+ import os.path
7
+ import pathlib
8
+ import sys
9
+ import tkinter as tk
10
+ import tkinter.filedialog
11
+ import tkinter.font
12
+ import tkinter.messagebox
13
+ from tkinter.simpledialog import SimpleDialog
14
+
15
+ import numpy as np
16
+ from PIL import Image, ImageTk
17
+
18
+ import matplotlib as mpl
19
+ from matplotlib import _api, backend_tools, cbook, _c_internal_utils
20
+ from matplotlib.backend_bases import (
21
+ _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
22
+ TimerBase, ToolContainerBase, cursors, _Mode, MouseButton,
23
+ CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
24
+ from matplotlib._pylab_helpers import Gcf
25
+
26
+ try:
27
+ from . import _tkagg
28
+ from ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET
29
+ except ImportError as e:
30
+ # catch incompatibility of python-build-standalone with Tk
31
+ cause1 = getattr(e, '__cause__', None)
32
+ cause2 = getattr(cause1, '__cause__', None)
33
+ if (isinstance(cause1, ImportError) and
34
+ isinstance(cause2, AttributeError) and
35
+ "'_tkinter' has no attribute '__file__'" in str(cause2)):
36
+
37
+ is_uv_python = "/uv/python" in (os.path.realpath(sys.executable))
38
+ if is_uv_python:
39
+ raise ImportError(
40
+ "Failed to import tkagg backend. You appear to be using an outdated "
41
+ "version of uv's managed Python distribution which is not compatible "
42
+ "with Tk. Please upgrade to the latest uv version, then update "
43
+ "Python with: `uv python upgrade --reinstall`"
44
+ ) from e
45
+ else:
46
+ raise ImportError(
47
+ "Failed to import tkagg backend. This is likely caused by using a "
48
+ "Python executable based on python-build-standalone, which is not "
49
+ "compatible with Tk. Recent versions of python-build-standalone "
50
+ "should be compatible with Tk. Please update your python version "
51
+ "or select another backend."
52
+ ) from e
53
+ else:
54
+ raise
55
+
56
+
57
+ _log = logging.getLogger(__name__)
58
+ cursord = {
59
+ cursors.MOVE: "fleur",
60
+ cursors.HAND: "hand2",
61
+ cursors.POINTER: "arrow",
62
+ cursors.SELECT_REGION: "crosshair",
63
+ cursors.WAIT: "watch",
64
+ cursors.RESIZE_HORIZONTAL: "sb_h_double_arrow",
65
+ cursors.RESIZE_VERTICAL: "sb_v_double_arrow",
66
+ }
67
+
68
+
69
+ @contextmanager
70
+ def _restore_foreground_window_at_end():
71
+ foreground = _c_internal_utils.Win32_GetForegroundWindow()
72
+ try:
73
+ yield
74
+ finally:
75
+ if foreground and mpl.rcParams['tk.window_focus']:
76
+ _c_internal_utils.Win32_SetForegroundWindow(foreground)
77
+
78
+
79
+ _blit_args = {}
80
+ # Initialize to a non-empty string that is not a Tcl command
81
+ _blit_tcl_name = "mpl_blit_" + uuid.uuid4().hex
82
+
83
+
84
+ def _blit(argsid):
85
+ """
86
+ Thin wrapper to blit called via tkapp.call.
87
+
88
+ *argsid* is a unique string identifier to fetch the correct arguments from
89
+ the ``_blit_args`` dict, since arguments cannot be passed directly.
90
+ """
91
+ photoimage, data, offsets, bbox, comp_rule = _blit_args.pop(argsid)
92
+ if not photoimage.tk.call("info", "commands", photoimage):
93
+ return
94
+ _tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets,
95
+ bbox)
96
+
97
+
98
+ def blit(photoimage, aggimage, offsets, bbox=None):
99
+ """
100
+ Blit *aggimage* to *photoimage*.
101
+
102
+ *offsets* is a tuple describing how to fill the ``offset`` field of the
103
+ ``Tk_PhotoImageBlock`` struct: it should be (0, 1, 2, 3) for RGBA8888 data,
104
+ (2, 1, 0, 3) for little-endian ARBG32 (i.e. GBRA8888) data and (1, 2, 3, 0)
105
+ for big-endian ARGB32 (i.e. ARGB8888) data.
106
+
107
+ If *bbox* is passed, it defines the region that gets blitted. That region
108
+ will be composed with the previous data according to the alpha channel.
109
+ Blitting will be clipped to pixels inside the canvas, including silently
110
+ doing nothing if the *bbox* region is entirely outside the canvas.
111
+
112
+ Tcl events must be dispatched to trigger a blit from a non-Tcl thread.
113
+ """
114
+ data = np.asarray(aggimage)
115
+ height, width = data.shape[:2]
116
+ if bbox is not None:
117
+ (x1, y1), (x2, y2) = bbox.__array__()
118
+ x1 = max(math.floor(x1), 0)
119
+ x2 = min(math.ceil(x2), width)
120
+ y1 = max(math.floor(y1), 0)
121
+ y2 = min(math.ceil(y2), height)
122
+ if (x1 > x2) or (y1 > y2):
123
+ return
124
+ bboxptr = (x1, x2, y1, y2)
125
+ comp_rule = TK_PHOTO_COMPOSITE_OVERLAY
126
+ else:
127
+ bboxptr = (0, width, 0, height)
128
+ comp_rule = TK_PHOTO_COMPOSITE_SET
129
+
130
+ # NOTE: _tkagg.blit is thread unsafe and will crash the process if called
131
+ # from a thread (GH#13293). Instead of blanking and blitting here,
132
+ # use tkapp.call to post a cross-thread event if this function is called
133
+ # from a non-Tcl thread.
134
+
135
+ # tkapp.call coerces all arguments to strings, so to avoid string parsing
136
+ # within _blit, pack up the arguments into a global data structure.
137
+ args = photoimage, data, offsets, bboxptr, comp_rule
138
+ # Need a unique key to avoid thread races.
139
+ # Again, make the key a string to avoid string parsing in _blit.
140
+ argsid = str(id(args))
141
+ _blit_args[argsid] = args
142
+
143
+ try:
144
+ photoimage.tk.call(_blit_tcl_name, argsid)
145
+ except tk.TclError as e:
146
+ if "invalid command name" not in str(e):
147
+ raise
148
+ photoimage.tk.createcommand(_blit_tcl_name, _blit)
149
+ photoimage.tk.call(_blit_tcl_name, argsid)
150
+
151
+
152
+ class TimerTk(TimerBase):
153
+ """Subclass of `backend_bases.TimerBase` using Tk timer events."""
154
+
155
+ def __init__(self, parent, *args, **kwargs):
156
+ self._timer = None
157
+ super().__init__(*args, **kwargs)
158
+ self.parent = parent
159
+
160
+ def _timer_start(self):
161
+ self._timer_stop()
162
+ self._timer = self.parent.after(self._interval, self._on_timer)
163
+
164
+ def _timer_stop(self):
165
+ if self._timer is not None:
166
+ self.parent.after_cancel(self._timer)
167
+ self._timer = None
168
+
169
+ def _on_timer(self):
170
+ super()._on_timer()
171
+ # Tk after() is only a single shot, so we need to add code here to
172
+ # reset the timer if we're not operating in single shot mode. However,
173
+ # if _timer is None, this means that _timer_stop has been called; so
174
+ # don't recreate the timer in that case.
175
+ if not self._single and self._timer:
176
+ if self._interval > 0:
177
+ self._timer = self.parent.after(self._interval, self._on_timer)
178
+ else:
179
+ # Edge case: Tcl after 0 *prepends* events to the queue
180
+ # so a 0 interval does not allow any other events to run.
181
+ # This incantation is cancellable and runs as fast as possible
182
+ # while also allowing events and drawing every frame. GH#18236
183
+ self._timer = self.parent.after_idle(
184
+ lambda: self.parent.after(self._interval, self._on_timer)
185
+ )
186
+ else:
187
+ self._timer = None
188
+
189
+
190
+ class FigureCanvasTk(FigureCanvasBase):
191
+ required_interactive_framework = "tk"
192
+ manager_class = _api.classproperty(lambda cls: FigureManagerTk)
193
+
194
+ def __init__(self, figure=None, master=None):
195
+ super().__init__(figure)
196
+ self._idle_draw_id = None
197
+ self._event_loop_id = None
198
+ w, h = self.get_width_height(physical=True)
199
+ self._tkcanvas = tk.Canvas(
200
+ master=master, background="white",
201
+ width=w, height=h, borderwidth=0, highlightthickness=0)
202
+ self._tkphoto = tk.PhotoImage(
203
+ master=self._tkcanvas, width=w, height=h)
204
+ self._tkcanvas_image_region = self._tkcanvas.create_image(
205
+ w//2, h//2, image=self._tkphoto)
206
+ self._tkcanvas.bind("<Configure>", self.resize)
207
+ self._tkcanvas.bind("<Map>", self._update_device_pixel_ratio)
208
+ self._tkcanvas.bind("<Key>", self.key_press)
209
+ self._tkcanvas.bind("<Motion>", self.motion_notify_event)
210
+ self._tkcanvas.bind("<Enter>", self.enter_notify_event)
211
+ self._tkcanvas.bind("<Leave>", self.leave_notify_event)
212
+ self._tkcanvas.bind("<KeyRelease>", self.key_release)
213
+ for name in ["<Button-1>", "<Button-2>", "<Button-3>"]:
214
+ self._tkcanvas.bind(name, self.button_press_event)
215
+ for name in [
216
+ "<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>"]:
217
+ self._tkcanvas.bind(name, self.button_dblclick_event)
218
+ for name in [
219
+ "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>"]:
220
+ self._tkcanvas.bind(name, self.button_release_event)
221
+
222
+ # Mouse wheel on Linux generates button 4/5 events
223
+ for name in "<Button-4>", "<Button-5>":
224
+ self._tkcanvas.bind(name, self.scroll_event)
225
+ # Mouse wheel for windows goes to the window with the focus.
226
+ # Since the canvas won't usually have the focus, bind the
227
+ # event to the window containing the canvas instead.
228
+ # See https://wiki.tcl-lang.org/3893 (mousewheel) for details
229
+ root = self._tkcanvas.winfo_toplevel()
230
+
231
+ # Prevent long-lived references via tkinter callback structure GH-24820
232
+ weakself = weakref.ref(self)
233
+ weakroot = weakref.ref(root)
234
+
235
+ def scroll_event_windows(event):
236
+ self = weakself()
237
+ if self is None:
238
+ root = weakroot()
239
+ if root is not None:
240
+ root.unbind("<MouseWheel>", scroll_event_windows_id)
241
+ return
242
+ return self.scroll_event_windows(event)
243
+ scroll_event_windows_id = root.bind("<MouseWheel>", scroll_event_windows, "+")
244
+
245
+ # Can't get destroy events by binding to _tkcanvas. Therefore, bind
246
+ # to the window and filter.
247
+ def filter_destroy(event):
248
+ self = weakself()
249
+ if self is None:
250
+ root = weakroot()
251
+ if root is not None:
252
+ root.unbind("<Destroy>", filter_destroy_id)
253
+ return
254
+ if event.widget is self._tkcanvas:
255
+ CloseEvent("close_event", self)._process()
256
+ filter_destroy_id = root.bind("<Destroy>", filter_destroy, "+")
257
+
258
+ self._tkcanvas.focus_set()
259
+
260
+ self._rubberband_rect_black = None
261
+ self._rubberband_rect_white = None
262
+
263
+ def _update_device_pixel_ratio(self, event=None):
264
+ ratio = None
265
+ if sys.platform == 'win32':
266
+ # Tk gives scaling with respect to 72 DPI, but Windows screens are
267
+ # scaled vs 96 dpi, and pixel ratio settings are given in whole
268
+ # percentages, so round to 2 digits.
269
+ ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2)
270
+ elif sys.platform == "linux":
271
+ ratio = self._tkcanvas.winfo_fpixels('1i') / 96
272
+ if ratio is not None and self._set_device_pixel_ratio(ratio):
273
+ # The easiest way to resize the canvas is to resize the canvas
274
+ # widget itself, since we implement all the logic for resizing the
275
+ # canvas backing store on that event.
276
+ w, h = self.get_width_height(physical=True)
277
+ self._tkcanvas.configure(width=w, height=h)
278
+
279
+ def resize(self, event):
280
+ width, height = event.width, event.height
281
+
282
+ # compute desired figure size in inches
283
+ dpival = self.figure.dpi
284
+ winch = width / dpival
285
+ hinch = height / dpival
286
+ self.figure.set_size_inches(winch, hinch, forward=False)
287
+
288
+ self._tkcanvas.delete(self._tkcanvas_image_region)
289
+ self._tkphoto.configure(width=int(width), height=int(height))
290
+ self._tkcanvas_image_region = self._tkcanvas.create_image(
291
+ int(width / 2), int(height / 2), image=self._tkphoto)
292
+ ResizeEvent("resize_event", self)._process()
293
+ self.draw_idle()
294
+
295
+ def draw_idle(self):
296
+ # docstring inherited
297
+ if self._idle_draw_id:
298
+ return
299
+
300
+ def idle_draw(*args):
301
+ try:
302
+ self.draw()
303
+ finally:
304
+ self._idle_draw_id = None
305
+
306
+ self._idle_draw_id = self._tkcanvas.after_idle(idle_draw)
307
+
308
+ def get_tk_widget(self):
309
+ """
310
+ Return the Tk widget used to implement FigureCanvasTkAgg.
311
+
312
+ Although the initial implementation uses a Tk canvas, this routine
313
+ is intended to hide that fact.
314
+ """
315
+ return self._tkcanvas
316
+
317
+ def _event_mpl_coords(self, event):
318
+ # calling canvasx/canvasy allows taking scrollbars into account (i.e.
319
+ # the top of the widget may have been scrolled out of view).
320
+ return (self._tkcanvas.canvasx(event.x),
321
+ # flipy so y=0 is bottom of canvas
322
+ self.figure.bbox.height - self._tkcanvas.canvasy(event.y))
323
+
324
+ def motion_notify_event(self, event):
325
+ MouseEvent("motion_notify_event", self,
326
+ *self._event_mpl_coords(event),
327
+ buttons=self._mpl_buttons(event),
328
+ modifiers=self._mpl_modifiers(event),
329
+ guiEvent=event)._process()
330
+
331
+ def enter_notify_event(self, event):
332
+ LocationEvent("figure_enter_event", self,
333
+ *self._event_mpl_coords(event),
334
+ modifiers=self._mpl_modifiers(event),
335
+ guiEvent=event)._process()
336
+
337
+ def leave_notify_event(self, event):
338
+ LocationEvent("figure_leave_event", self,
339
+ *self._event_mpl_coords(event),
340
+ modifiers=self._mpl_modifiers(event),
341
+ guiEvent=event)._process()
342
+
343
+ def button_press_event(self, event, dblclick=False):
344
+ # set focus to the canvas so that it can receive keyboard events
345
+ self._tkcanvas.focus_set()
346
+
347
+ num = getattr(event, 'num', None)
348
+ if sys.platform == 'darwin': # 2 and 3 are reversed.
349
+ num = {2: 3, 3: 2}.get(num, num)
350
+ MouseEvent("button_press_event", self,
351
+ *self._event_mpl_coords(event), num, dblclick=dblclick,
352
+ modifiers=self._mpl_modifiers(event),
353
+ guiEvent=event)._process()
354
+
355
+ def button_dblclick_event(self, event):
356
+ self.button_press_event(event, dblclick=True)
357
+
358
+ def button_release_event(self, event):
359
+ num = getattr(event, 'num', None)
360
+ if sys.platform == 'darwin': # 2 and 3 are reversed.
361
+ num = {2: 3, 3: 2}.get(num, num)
362
+ MouseEvent("button_release_event", self,
363
+ *self._event_mpl_coords(event), num,
364
+ modifiers=self._mpl_modifiers(event),
365
+ guiEvent=event)._process()
366
+
367
+ def scroll_event(self, event):
368
+ num = getattr(event, 'num', None)
369
+ step = 1 if num == 4 else -1 if num == 5 else 0
370
+ MouseEvent("scroll_event", self,
371
+ *self._event_mpl_coords(event), step=step,
372
+ modifiers=self._mpl_modifiers(event),
373
+ guiEvent=event)._process()
374
+
375
+ def scroll_event_windows(self, event):
376
+ """MouseWheel event processor"""
377
+ # need to find the window that contains the mouse
378
+ w = event.widget.winfo_containing(event.x_root, event.y_root)
379
+ if w != self._tkcanvas:
380
+ return
381
+ x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx())
382
+ y = (self.figure.bbox.height
383
+ - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty()))
384
+ step = event.delta / 120
385
+ MouseEvent("scroll_event", self,
386
+ x, y, step=step, modifiers=self._mpl_modifiers(event),
387
+ guiEvent=event)._process()
388
+
389
+ @staticmethod
390
+ def _mpl_buttons(event): # See _mpl_modifiers.
391
+ # NOTE: This fails to report multiclicks on macOS; only one button is
392
+ # reported (multiclicks work correctly on Linux & Windows).
393
+ modifiers = [
394
+ # macOS appears to swap right and middle (look for "Swap buttons
395
+ # 2/3" in tk/macosx/tkMacOSXMouseEvent.c).
396
+ (MouseButton.LEFT, 1 << 8),
397
+ (MouseButton.RIGHT, 1 << 9),
398
+ (MouseButton.MIDDLE, 1 << 10),
399
+ (MouseButton.BACK, 1 << 11),
400
+ (MouseButton.FORWARD, 1 << 12),
401
+ ] if sys.platform == "darwin" else [
402
+ (MouseButton.LEFT, 1 << 8),
403
+ (MouseButton.MIDDLE, 1 << 9),
404
+ (MouseButton.RIGHT, 1 << 10),
405
+ (MouseButton.BACK, 1 << 11),
406
+ (MouseButton.FORWARD, 1 << 12),
407
+ ]
408
+ # State *before* press/release.
409
+ return [name for name, mask in modifiers if event.state & mask]
410
+
411
+ @staticmethod
412
+ def _mpl_modifiers(event, *, exclude=None):
413
+ # Add modifier keys to the key string. Bit values are inferred from
414
+ # the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... =
415
+ # Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5)
416
+ # In general, the modifier key is excluded from the modifier flag,
417
+ # however this is not the case on "darwin", so double check that
418
+ # we aren't adding repeat modifier flags to a modifier key.
419
+ modifiers = [
420
+ ("ctrl", 1 << 2, "control"),
421
+ ("alt", 1 << 17, "alt"),
422
+ ("shift", 1 << 0, "shift"),
423
+ ] if sys.platform == "win32" else [
424
+ ("ctrl", 1 << 2, "control"),
425
+ ("alt", 1 << 4, "alt"),
426
+ ("shift", 1 << 0, "shift"),
427
+ ("cmd", 1 << 3, "cmd"),
428
+ ] if sys.platform == "darwin" else [
429
+ ("ctrl", 1 << 2, "control"),
430
+ ("alt", 1 << 3, "alt"),
431
+ ("shift", 1 << 0, "shift"),
432
+ ("super", 1 << 6, "super"),
433
+ ]
434
+ return [name for name, mask, key in modifiers
435
+ if event.state & mask and exclude != key]
436
+
437
+ def _get_key(self, event):
438
+ unikey = event.char
439
+ key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym)
440
+ if key is not None:
441
+ mods = self._mpl_modifiers(event, exclude=key)
442
+ # shift is not added to the keys as this is already accounted for.
443
+ if "shift" in mods and unikey:
444
+ mods.remove("shift")
445
+ return "+".join([*mods, key])
446
+
447
+ def key_press(self, event):
448
+ KeyEvent("key_press_event", self,
449
+ self._get_key(event), *self._event_mpl_coords(event),
450
+ guiEvent=event)._process()
451
+
452
+ def key_release(self, event):
453
+ KeyEvent("key_release_event", self,
454
+ self._get_key(event), *self._event_mpl_coords(event),
455
+ guiEvent=event)._process()
456
+
457
+ def new_timer(self, *args, **kwargs):
458
+ # docstring inherited
459
+ return TimerTk(self._tkcanvas, *args, **kwargs)
460
+
461
+ def flush_events(self):
462
+ # docstring inherited
463
+ self._tkcanvas.update()
464
+
465
+ def start_event_loop(self, timeout=0):
466
+ # docstring inherited
467
+ if timeout > 0:
468
+ milliseconds = int(1000 * timeout)
469
+ if milliseconds > 0:
470
+ self._event_loop_id = self._tkcanvas.after(
471
+ milliseconds, self.stop_event_loop)
472
+ else:
473
+ self._event_loop_id = self._tkcanvas.after_idle(
474
+ self.stop_event_loop)
475
+ self._tkcanvas.mainloop()
476
+
477
+ def stop_event_loop(self):
478
+ # docstring inherited
479
+ if self._event_loop_id:
480
+ self._tkcanvas.after_cancel(self._event_loop_id)
481
+ self._event_loop_id = None
482
+ self._tkcanvas.quit()
483
+
484
+ def set_cursor(self, cursor):
485
+ try:
486
+ self._tkcanvas.configure(cursor=cursord[cursor])
487
+ except tkinter.TclError:
488
+ pass
489
+
490
+
491
+ class FigureManagerTk(FigureManagerBase):
492
+ """
493
+ Attributes
494
+ ----------
495
+ canvas : `FigureCanvas`
496
+ The FigureCanvas instance
497
+ num : int or str
498
+ The Figure number
499
+ toolbar : tk.Toolbar
500
+ The tk.Toolbar
501
+ window : tk.Window
502
+ The tk.Window
503
+ """
504
+
505
+ _owns_mainloop = False
506
+
507
+ def __init__(self, canvas, num, window):
508
+ self.window = window
509
+ super().__init__(canvas, num)
510
+ self.window.withdraw()
511
+ # packing toolbar first, because if space is getting low, last packed
512
+ # widget is getting shrunk first (-> the canvas)
513
+ self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
514
+
515
+ # If the window has per-monitor DPI awareness, then setup a Tk variable
516
+ # to store the DPI, which will be updated by the C code, and the trace
517
+ # will handle it on the Python side.
518
+ window_frame = int(window.wm_frame(), 16)
519
+ self._window_dpi = tk.IntVar(master=window, value=96,
520
+ name=f'window_dpi{window_frame}')
521
+ self._window_dpi_cbname = ''
522
+ if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()):
523
+ self._window_dpi_cbname = self._window_dpi.trace_add(
524
+ 'write', self._update_window_dpi)
525
+
526
+ self._shown = False
527
+
528
+ @classmethod
529
+ def create_with_canvas(cls, canvas_class, figure, num):
530
+ # docstring inherited
531
+ with _restore_foreground_window_at_end():
532
+ if cbook._get_running_interactive_framework() is None:
533
+ cbook._setup_new_guiapp()
534
+ _c_internal_utils.Win32_SetProcessDpiAwareness_max()
535
+ window = tk.Tk(className="matplotlib")
536
+ window.withdraw()
537
+
538
+ # Put a Matplotlib icon on the window rather than the default tk
539
+ # icon. See https://www.tcl.tk/man/tcl/TkCmd/wm.html#M50
540
+ #
541
+ # `ImageTk` can be replaced with `tk` whenever the minimum
542
+ # supported Tk version is increased to 8.6, as Tk 8.6+ natively
543
+ # supports PNG images.
544
+ icon_fname = str(cbook._get_data_path(
545
+ 'images/matplotlib.png'))
546
+ icon_img = ImageTk.PhotoImage(file=icon_fname, master=window)
547
+
548
+ icon_fname_large = str(cbook._get_data_path(
549
+ 'images/matplotlib_large.png'))
550
+ icon_img_large = ImageTk.PhotoImage(
551
+ file=icon_fname_large, master=window)
552
+
553
+ window.iconphoto(False, icon_img_large, icon_img)
554
+
555
+ canvas = canvas_class(figure, master=window)
556
+ manager = cls(canvas, num, window)
557
+ if mpl.is_interactive():
558
+ manager.show()
559
+ canvas.draw_idle()
560
+ return manager
561
+
562
+ @classmethod
563
+ def start_main_loop(cls):
564
+ managers = Gcf.get_all_fig_managers()
565
+ if managers:
566
+ first_manager = managers[0]
567
+ manager_class = type(first_manager)
568
+ if manager_class._owns_mainloop:
569
+ return
570
+ manager_class._owns_mainloop = True
571
+ try:
572
+ first_manager.window.mainloop()
573
+ finally:
574
+ manager_class._owns_mainloop = False
575
+
576
+ def _update_window_dpi(self, *args):
577
+ newdpi = self._window_dpi.get()
578
+ self.window.call('tk', 'scaling', newdpi / 72)
579
+ if self.toolbar and hasattr(self.toolbar, '_rescale'):
580
+ self.toolbar._rescale()
581
+ self.canvas._update_device_pixel_ratio()
582
+
583
+ def resize(self, width, height):
584
+ max_size = 1_400_000 # the measured max on xorg 1.20.8 was 1_409_023
585
+
586
+ if (width > max_size or height > max_size) and sys.platform == 'linux':
587
+ raise ValueError(
588
+ 'You have requested to resize the '
589
+ f'Tk window to ({width}, {height}), one of which '
590
+ f'is bigger than {max_size}. At larger sizes xorg will '
591
+ 'either exit with an error on newer versions (~1.20) or '
592
+ 'cause corruption on older version (~1.19). We '
593
+ 'do not expect a window over a million pixel wide or tall '
594
+ 'to be intended behavior.')
595
+ self.canvas._tkcanvas.configure(width=width, height=height)
596
+
597
+ def show(self):
598
+ with _restore_foreground_window_at_end():
599
+ if not self._shown:
600
+ def destroy(*args):
601
+ Gcf.destroy(self)
602
+ self.window.protocol("WM_DELETE_WINDOW", destroy)
603
+ self.window.deiconify()
604
+ self.canvas._tkcanvas.focus_set()
605
+ else:
606
+ self.canvas.draw_idle()
607
+ if mpl.rcParams['figure.raise_window']:
608
+ self.canvas.manager.window.attributes('-topmost', 1)
609
+ self.canvas.manager.window.attributes('-topmost', 0)
610
+ self._shown = True
611
+
612
+ def destroy(self, *args):
613
+ if self.canvas._idle_draw_id:
614
+ self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)
615
+ if self.canvas._event_loop_id:
616
+ self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id)
617
+ if self._window_dpi_cbname:
618
+ self._window_dpi.trace_remove('write', self._window_dpi_cbname)
619
+
620
+ # NOTE: events need to be flushed before issuing destroy (GH #9956),
621
+ # however, self.window.update() can break user code. An async callback
622
+ # is the safest way to achieve a complete draining of the event queue,
623
+ # but it leaks if no tk event loop is running. Therefore we explicitly
624
+ # check for an event loop and choose our best guess.
625
+ def delayed_destroy():
626
+ self.window.destroy()
627
+
628
+ if self._owns_mainloop and not Gcf.get_num_fig_managers():
629
+ self.window.quit()
630
+
631
+ if cbook._get_running_interactive_framework() == "tk":
632
+ # "after idle after 0" avoids Tcl error/race (GH #19940)
633
+ self.window.after_idle(self.window.after, 0, delayed_destroy)
634
+ else:
635
+ self.window.update()
636
+ delayed_destroy()
637
+
638
+ def get_window_title(self):
639
+ return self.window.wm_title()
640
+
641
+ def set_window_title(self, title):
642
+ self.window.wm_title(title)
643
+
644
+ def full_screen_toggle(self):
645
+ is_fullscreen = bool(self.window.attributes('-fullscreen'))
646
+ self.window.attributes('-fullscreen', not is_fullscreen)
647
+
648
+
649
+ class NavigationToolbar2Tk(NavigationToolbar2, tk.Frame):
650
+ def __init__(self, canvas, window=None, *, pack_toolbar=True):
651
+ """
652
+ Parameters
653
+ ----------
654
+ canvas : `FigureCanvas`
655
+ The figure canvas on which to operate.
656
+ window : tk.Window
657
+ The tk.Window which owns this toolbar.
658
+ pack_toolbar : bool, default: True
659
+ If True, add the toolbar to the parent's pack manager's packing
660
+ list during initialization with ``side="bottom"`` and ``fill="x"``.
661
+ If you want to use the toolbar with a different layout manager, use
662
+ ``pack_toolbar=False``.
663
+ """
664
+
665
+ if window is None:
666
+ window = canvas.get_tk_widget().master
667
+ tk.Frame.__init__(self, master=window, borderwidth=2,
668
+ width=int(canvas.figure.bbox.width), height=50)
669
+
670
+ self._buttons = {}
671
+ for text, tooltip_text, image_file, callback in self.toolitems:
672
+ if text is None:
673
+ # Add a spacer; return value is unused.
674
+ self._Spacer()
675
+ else:
676
+ self._buttons[text] = button = self._Button(
677
+ text,
678
+ str(cbook._get_data_path(f"images/{image_file}.png")),
679
+ toggle=callback in ["zoom", "pan"],
680
+ command=getattr(self, callback),
681
+ )
682
+ if tooltip_text is not None:
683
+ add_tooltip(button, tooltip_text)
684
+
685
+ self._label_font = tkinter.font.Font(root=window, size=10)
686
+
687
+ # This filler item ensures the toolbar is always at least two text
688
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
689
+ # over images because those use two-line messages which resize the
690
+ # toolbar.
691
+ label = tk.Label(master=self, font=self._label_font,
692
+ text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
693
+ label.pack(side=tk.RIGHT)
694
+
695
+ self.message = tk.StringVar(master=self)
696
+ self._message_label = tk.Label(master=self, font=self._label_font,
697
+ textvariable=self.message,
698
+ justify=tk.RIGHT)
699
+ self._message_label.pack(side=tk.RIGHT)
700
+
701
+ NavigationToolbar2.__init__(self, canvas)
702
+ if pack_toolbar:
703
+ self.pack(side=tk.BOTTOM, fill=tk.X)
704
+
705
+ def _rescale(self):
706
+ """
707
+ Scale all children of the toolbar to current DPI setting.
708
+
709
+ Before this is called, the Tk scaling setting will have been updated to
710
+ match the new DPI. Tk widgets do not update for changes to scaling, but
711
+ all measurements made after the change will match the new scaling. Thus
712
+ this function re-applies all the same sizes in points, which Tk will
713
+ scale correctly to pixels.
714
+ """
715
+ for widget in self.winfo_children():
716
+ if isinstance(widget, (tk.Button, tk.Checkbutton)):
717
+ if hasattr(widget, '_image_file'):
718
+ # Explicit class because ToolbarTk calls _rescale.
719
+ NavigationToolbar2Tk._set_image_for_button(self, widget)
720
+ else:
721
+ # Text-only button is handled by the font setting instead.
722
+ pass
723
+ elif isinstance(widget, tk.Frame):
724
+ widget.configure(height='18p')
725
+ widget.pack_configure(padx='3p')
726
+ elif isinstance(widget, tk.Label):
727
+ pass # Text is handled by the font setting instead.
728
+ else:
729
+ _log.warning('Unknown child class %s', widget.winfo_class)
730
+ self._label_font.configure(size=10)
731
+
732
+ def _update_buttons_checked(self):
733
+ # sync button checkstates to match active mode
734
+ for text, mode in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]:
735
+ if text in self._buttons:
736
+ if self.mode == mode:
737
+ self._buttons[text].select() # NOT .invoke()
738
+ else:
739
+ self._buttons[text].deselect()
740
+
741
+ def pan(self, *args):
742
+ super().pan(*args)
743
+ self._update_buttons_checked()
744
+
745
+ def zoom(self, *args):
746
+ super().zoom(*args)
747
+ self._update_buttons_checked()
748
+
749
+ def set_message(self, s):
750
+ self.message.set(s)
751
+
752
+ def draw_rubberband(self, event, x0, y0, x1, y1):
753
+ # Block copied from remove_rubberband for backend_tools convenience.
754
+ if self.canvas._rubberband_rect_white:
755
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
756
+ if self.canvas._rubberband_rect_black:
757
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
758
+ height = self.canvas.figure.bbox.height
759
+ y0 = height - y0
760
+ y1 = height - y1
761
+ self.canvas._rubberband_rect_black = (
762
+ self.canvas._tkcanvas.create_rectangle(
763
+ x0, y0, x1, y1))
764
+ self.canvas._rubberband_rect_white = (
765
+ self.canvas._tkcanvas.create_rectangle(
766
+ x0, y0, x1, y1, outline='white', dash=(3, 3)))
767
+
768
+ def remove_rubberband(self):
769
+ if self.canvas._rubberband_rect_white:
770
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
771
+ self.canvas._rubberband_rect_white = None
772
+ if self.canvas._rubberband_rect_black:
773
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
774
+ self.canvas._rubberband_rect_black = None
775
+
776
+ def _set_image_for_button(self, button):
777
+ """
778
+ Set the image for a button based on its pixel size.
779
+
780
+ The pixel size is determined by the DPI scaling of the window.
781
+ """
782
+ if button._image_file is None:
783
+ return
784
+
785
+ # Allow _image_file to be relative to Matplotlib's "images" data
786
+ # directory.
787
+ path_regular = cbook._get_data_path('images', button._image_file)
788
+ path_large = path_regular.with_name(
789
+ path_regular.name.replace('.png', '_large.png'))
790
+ size = button.winfo_pixels('18p')
791
+
792
+ # Nested functions because ToolbarTk calls _Button.
793
+ def _get_color(color_name):
794
+ # `winfo_rgb` returns an (r, g, b) tuple in the range 0-65535
795
+ return button.winfo_rgb(button.cget(color_name))
796
+
797
+ def _is_dark(color):
798
+ if isinstance(color, str):
799
+ color = _get_color(color)
800
+ return max(color) < 65535 / 2
801
+
802
+ def _recolor_icon(image, color):
803
+ image_data = np.asarray(image).copy()
804
+ black_mask = (image_data[..., :3] == 0).all(axis=-1)
805
+ image_data[black_mask, :3] = color
806
+ return Image.fromarray(image_data)
807
+
808
+ # Use the high-resolution (48x48 px) icon if it exists and is needed
809
+ with Image.open(path_large if (size > 24 and path_large.exists())
810
+ else path_regular) as im:
811
+ # assure a RGBA image as foreground color is RGB
812
+ im = im.convert("RGBA")
813
+ image = ImageTk.PhotoImage(im.resize((size, size)), master=self)
814
+ button._ntimage = image
815
+
816
+ # create a version of the icon with the button's text color
817
+ foreground = (255 / 65535) * np.array(
818
+ button.winfo_rgb(button.cget("foreground")))
819
+ im_alt = _recolor_icon(im, foreground)
820
+ image_alt = ImageTk.PhotoImage(
821
+ im_alt.resize((size, size)), master=self)
822
+ button._ntimage_alt = image_alt
823
+
824
+ if _is_dark("background"):
825
+ # For Checkbuttons, we need to set `image` and `selectimage` at
826
+ # the same time. Otherwise, when updating the `image` option
827
+ # (such as when changing DPI), if the old `selectimage` has
828
+ # just been overwritten, Tk will throw an error.
829
+ image_kwargs = {"image": image_alt}
830
+ else:
831
+ image_kwargs = {"image": image}
832
+ # Checkbuttons may switch the background to `selectcolor` in the
833
+ # checked state, so check separately which image it needs to use in
834
+ # that state to still ensure enough contrast with the background.
835
+ if (
836
+ isinstance(button, tk.Checkbutton)
837
+ and button.cget("selectcolor") != ""
838
+ ):
839
+ if self._windowingsystem != "x11":
840
+ selectcolor = "selectcolor"
841
+ else:
842
+ # On X11, selectcolor isn't used directly for indicator-less
843
+ # buttons. See `::tk::CheckEnter` in the Tk button.tcl source
844
+ # code for details.
845
+ r1, g1, b1 = _get_color("selectcolor")
846
+ r2, g2, b2 = _get_color("activebackground")
847
+ selectcolor = ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2)
848
+ if _is_dark(selectcolor):
849
+ image_kwargs["selectimage"] = image_alt
850
+ else:
851
+ image_kwargs["selectimage"] = image
852
+
853
+ button.configure(**image_kwargs, height='18p', width='18p')
854
+
855
+ def _Button(self, text, image_file, toggle, command):
856
+ if not toggle:
857
+ b = tk.Button(
858
+ master=self, text=text, command=command,
859
+ relief="flat", overrelief="groove", borderwidth=1,
860
+ )
861
+ else:
862
+ # There is a bug in tkinter included in some python 3.6 versions
863
+ # that without this variable, produces a "visual" toggling of
864
+ # other near checkbuttons
865
+ # https://bugs.python.org/issue29402
866
+ # https://bugs.python.org/issue25684
867
+ var = tk.IntVar(master=self)
868
+ b = tk.Checkbutton(
869
+ master=self, text=text, command=command, indicatoron=False,
870
+ variable=var, offrelief="flat", overrelief="groove",
871
+ borderwidth=1
872
+ )
873
+ b.var = var
874
+ b._image_file = image_file
875
+ if image_file is not None:
876
+ # Explicit class because ToolbarTk calls _Button.
877
+ NavigationToolbar2Tk._set_image_for_button(self, b)
878
+ else:
879
+ b.configure(font=self._label_font)
880
+ b.pack(side=tk.LEFT)
881
+ return b
882
+
883
+ def _Spacer(self):
884
+ # Buttons are also 18pt high.
885
+ s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray')
886
+ s.pack(side=tk.LEFT, padx='3p')
887
+ return s
888
+
889
+ def save_figure(self, *args):
890
+ filetypes = self.canvas.get_supported_filetypes_grouped()
891
+ tk_filetypes = [
892
+ (name, " ".join(f"*.{ext}" for ext in exts))
893
+ for name, exts in sorted(filetypes.items())
894
+ ]
895
+
896
+ default_extension = self.canvas.get_default_filetype()
897
+ default_filetype = self.canvas.get_supported_filetypes()[default_extension]
898
+ filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype)
899
+
900
+ # adding a default extension seems to break the
901
+ # asksaveasfilename dialog when you choose various save types
902
+ # from the dropdown. Passing in the empty string seems to
903
+ # work - JDH!
904
+ # defaultextension = self.canvas.get_default_filetype()
905
+ defaultextension = ''
906
+ initialdir = os.path.expanduser(mpl.rcParams['savefig.directory'])
907
+ # get_default_filename() contains the default extension. On some platforms,
908
+ # choosing a different extension from the dropdown does not overwrite it,
909
+ # so we need to remove it to make the dropdown functional.
910
+ initialfile = pathlib.Path(self.canvas.get_default_filename()).stem
911
+ fname = tkinter.filedialog.asksaveasfilename(
912
+ master=self.canvas.get_tk_widget().master,
913
+ title='Save the figure',
914
+ filetypes=tk_filetypes,
915
+ defaultextension=defaultextension,
916
+ initialdir=initialdir,
917
+ initialfile=initialfile,
918
+ typevariable=filetype_variable
919
+ )
920
+
921
+ if fname in ["", ()]:
922
+ return None
923
+ # Save dir for next time, unless empty str (i.e., use cwd).
924
+ if initialdir != "":
925
+ mpl.rcParams['savefig.directory'] = (
926
+ os.path.dirname(str(fname)))
927
+
928
+ # If the filename contains an extension, let savefig() infer the file
929
+ # format from that. If it does not, use the selected dropdown option.
930
+ if pathlib.Path(fname).suffix[1:] != "":
931
+ extension = None
932
+ else:
933
+ extension = filetypes[filetype_variable.get()][0]
934
+
935
+ try:
936
+ self.canvas.figure.savefig(fname, format=extension)
937
+ return fname
938
+ except Exception as e:
939
+ tkinter.messagebox.showerror("Error saving file", str(e))
940
+
941
+ def set_history_buttons(self):
942
+ state_map = {True: tk.NORMAL, False: tk.DISABLED}
943
+ can_back = self._nav_stack._pos > 0
944
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
945
+ if "Back" in self._buttons:
946
+ self._buttons['Back']['state'] = state_map[can_back]
947
+ if "Forward" in self._buttons:
948
+ self._buttons['Forward']['state'] = state_map[can_forward]
949
+
950
+
951
+ def add_tooltip(widget, text):
952
+ tipwindow = None
953
+
954
+ def showtip(event):
955
+ """Display text in tooltip window."""
956
+ nonlocal tipwindow
957
+ if tipwindow or not text:
958
+ return
959
+ x, y, _, _ = widget.bbox("insert")
960
+ x = x + widget.winfo_rootx() + widget.winfo_width()
961
+ y = y + widget.winfo_rooty()
962
+ tipwindow = tk.Toplevel(widget)
963
+ tipwindow.overrideredirect(1)
964
+ tipwindow.geometry(f"+{x}+{y}")
965
+ try: # For Mac OS
966
+ tipwindow.tk.call("::tk::unsupported::MacWindowStyle",
967
+ "style", tipwindow._w,
968
+ "help", "noActivates")
969
+ except tk.TclError:
970
+ pass
971
+ label = tk.Label(tipwindow, text=text, justify=tk.LEFT,
972
+ relief=tk.SOLID, borderwidth=1)
973
+ label.pack(ipadx=1)
974
+
975
+ def hidetip(event):
976
+ nonlocal tipwindow
977
+ if tipwindow:
978
+ tipwindow.destroy()
979
+ tipwindow = None
980
+
981
+ widget.bind("<Enter>", showtip)
982
+ widget.bind("<Leave>", hidetip)
983
+
984
+
985
+ @backend_tools._register_tool_class(FigureCanvasTk)
986
+ class RubberbandTk(backend_tools.RubberbandBase):
987
+ def draw_rubberband(self, x0, y0, x1, y1):
988
+ NavigationToolbar2Tk.draw_rubberband(
989
+ self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
990
+
991
+ def remove_rubberband(self):
992
+ NavigationToolbar2Tk.remove_rubberband(
993
+ self._make_classic_style_pseudo_toolbar())
994
+
995
+
996
+ class ToolbarTk(ToolContainerBase, tk.Frame):
997
+ def __init__(self, toolmanager, window=None):
998
+ ToolContainerBase.__init__(self, toolmanager)
999
+ if window is None:
1000
+ window = self.toolmanager.canvas.get_tk_widget().master
1001
+ xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx
1002
+ height, width = 50, xmax - xmin
1003
+ tk.Frame.__init__(self, master=window,
1004
+ width=int(width), height=int(height),
1005
+ borderwidth=2)
1006
+ self._label_font = tkinter.font.Font(size=10)
1007
+ # This filler item ensures the toolbar is always at least two text
1008
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
1009
+ # over images because those use two-line messages which resize the
1010
+ # toolbar.
1011
+ label = tk.Label(master=self, font=self._label_font,
1012
+ text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
1013
+ label.pack(side=tk.RIGHT)
1014
+ self._message = tk.StringVar(master=self)
1015
+ self._message_label = tk.Label(master=self, font=self._label_font,
1016
+ textvariable=self._message)
1017
+ self._message_label.pack(side=tk.RIGHT)
1018
+ self._toolitems = {}
1019
+ self.pack(side=tk.TOP, fill=tk.X)
1020
+ self._groups = {}
1021
+
1022
+ def _rescale(self):
1023
+ return NavigationToolbar2Tk._rescale(self)
1024
+
1025
+ def add_toolitem(
1026
+ self, name, group, position, image_file, description, toggle):
1027
+ frame = self._get_groupframe(group)
1028
+ buttons = frame.pack_slaves()
1029
+ if position >= len(buttons) or position < 0:
1030
+ before = None
1031
+ else:
1032
+ before = buttons[position]
1033
+ button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle,
1034
+ lambda: self._button_click(name))
1035
+ button.pack_configure(before=before)
1036
+ if description is not None:
1037
+ add_tooltip(button, description)
1038
+ self._toolitems.setdefault(name, [])
1039
+ self._toolitems[name].append(button)
1040
+
1041
+ def _get_groupframe(self, group):
1042
+ if group not in self._groups:
1043
+ if self._groups:
1044
+ self._add_separator()
1045
+ frame = tk.Frame(master=self, borderwidth=0)
1046
+ frame.pack(side=tk.LEFT, fill=tk.Y)
1047
+ frame._label_font = self._label_font
1048
+ self._groups[group] = frame
1049
+ return self._groups[group]
1050
+
1051
+ def _add_separator(self):
1052
+ return NavigationToolbar2Tk._Spacer(self)
1053
+
1054
+ def _button_click(self, name):
1055
+ self.trigger_tool(name)
1056
+
1057
+ def toggle_toolitem(self, name, toggled):
1058
+ if name not in self._toolitems:
1059
+ return
1060
+ for toolitem in self._toolitems[name]:
1061
+ if toggled:
1062
+ toolitem.select()
1063
+ else:
1064
+ toolitem.deselect()
1065
+
1066
+ def remove_toolitem(self, name):
1067
+ for toolitem in self._toolitems.pop(name, []):
1068
+ toolitem.pack_forget()
1069
+
1070
+ def set_message(self, s):
1071
+ self._message.set(s)
1072
+
1073
+
1074
+ @backend_tools._register_tool_class(FigureCanvasTk)
1075
+ class SaveFigureTk(backend_tools.SaveFigureBase):
1076
+ def trigger(self, *args):
1077
+ NavigationToolbar2Tk.save_figure(
1078
+ self._make_classic_style_pseudo_toolbar())
1079
+
1080
+
1081
+ @backend_tools._register_tool_class(FigureCanvasTk)
1082
+ class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase):
1083
+ def trigger(self, *args):
1084
+ NavigationToolbar2Tk.configure_subplots(self)
1085
+
1086
+
1087
+ @backend_tools._register_tool_class(FigureCanvasTk)
1088
+ class HelpTk(backend_tools.ToolHelpBase):
1089
+ def trigger(self, *args):
1090
+ dialog = SimpleDialog(
1091
+ self.figure.canvas._tkcanvas, self._get_help_text(), ["OK"])
1092
+ dialog.done = lambda num: dialog.frame.master.withdraw()
1093
+
1094
+
1095
+ Toolbar = ToolbarTk
1096
+ FigureManagerTk._toolbar2_class = NavigationToolbar2Tk
1097
+ FigureManagerTk._toolmanager_toolbar_class = ToolbarTk
1098
+
1099
+
1100
+ @_Backend.export
1101
+ class _BackendTk(_Backend):
1102
+ backend_version = tk.TkVersion
1103
+ FigureCanvas = FigureCanvasTk
1104
+ FigureManager = FigureManagerTk
1105
+ mainloop = FigureManagerTk.start_main_loop
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_macosx.pyi ADDED
File without changes
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_tkagg.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c5b4865b5b83ef564aa6bdedd76e8c66e280f4c3ebe32ec33ea6c9546e5bb8b
3
+ size 169344
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/_tkagg.pyi ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.typing import NDArray
3
+
4
+ TK_PHOTO_COMPOSITE_OVERLAY: int
5
+ TK_PHOTO_COMPOSITE_SET: int
6
+
7
+ def blit(
8
+ interp: int,
9
+ photo_name: str,
10
+ data: NDArray[np.uint8],
11
+ comp_rule: int,
12
+ offset: tuple[int, int, int, int],
13
+ bbox: tuple[int, int, int, int],
14
+ ) -> None: ...
15
+ def enable_dpi_awareness(frame_handle: int, interp: int) -> bool | None: ...
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_agg.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ An `Anti-Grain Geometry`_ (AGG) backend.
3
+
4
+ Features that are implemented:
5
+
6
+ * capstyles and join styles
7
+ * dashes
8
+ * linewidth
9
+ * lines, rectangles, ellipses
10
+ * clipping to a rectangle
11
+ * output to RGBA and Pillow-supported image formats
12
+ * alpha blending
13
+ * DPI scaling properly - everything scales properly (dashes, linewidths, etc)
14
+ * draw polygon
15
+ * freetype2 w/ ft2font
16
+
17
+ Still TODO:
18
+
19
+ * integrate screen dpi w/ ppi and text
20
+
21
+ .. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com
22
+ """
23
+
24
+ from contextlib import nullcontext
25
+ from math import radians, cos, sin
26
+
27
+ import numpy as np
28
+
29
+ import matplotlib as mpl
30
+ from matplotlib import _api, cbook
31
+ from matplotlib.backend_bases import (
32
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
33
+ from matplotlib.font_manager import fontManager as _fontManager, get_font
34
+ from matplotlib.ft2font import LoadFlags
35
+ from matplotlib.mathtext import MathTextParser
36
+ from matplotlib.path import Path
37
+ from matplotlib.transforms import Bbox, BboxBase
38
+ from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
39
+
40
+
41
+ def get_hinting_flag():
42
+ mapping = {
43
+ 'default': LoadFlags.DEFAULT,
44
+ 'no_autohint': LoadFlags.NO_AUTOHINT,
45
+ 'force_autohint': LoadFlags.FORCE_AUTOHINT,
46
+ 'no_hinting': LoadFlags.NO_HINTING,
47
+ True: LoadFlags.FORCE_AUTOHINT,
48
+ False: LoadFlags.NO_HINTING,
49
+ 'either': LoadFlags.DEFAULT,
50
+ 'native': LoadFlags.NO_AUTOHINT,
51
+ 'auto': LoadFlags.FORCE_AUTOHINT,
52
+ 'none': LoadFlags.NO_HINTING,
53
+ }
54
+ return mapping[mpl.rcParams['text.hinting']]
55
+
56
+
57
+ class RendererAgg(RendererBase):
58
+ """
59
+ The renderer handles all the drawing primitives using a graphics
60
+ context instance that controls the colors/styles
61
+ """
62
+
63
+ def __init__(self, width, height, dpi):
64
+ super().__init__()
65
+
66
+ self.dpi = dpi
67
+ self.width = width
68
+ self.height = height
69
+ self._renderer = _RendererAgg(int(width), int(height), dpi)
70
+ self._filter_renderers = []
71
+
72
+ self._update_methods()
73
+ self.mathtext_parser = MathTextParser('agg')
74
+
75
+ self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
76
+
77
+ def __getstate__(self):
78
+ # We only want to preserve the init keywords of the Renderer.
79
+ # Anything else can be re-created.
80
+ return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
81
+
82
+ def __setstate__(self, state):
83
+ self.__init__(state['width'], state['height'], state['dpi'])
84
+
85
+ def _update_methods(self):
86
+ self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
87
+ self.draw_image = self._renderer.draw_image
88
+ self.draw_markers = self._renderer.draw_markers
89
+ self.draw_path_collection = self._renderer.draw_path_collection
90
+ self.draw_quad_mesh = self._renderer.draw_quad_mesh
91
+ self.copy_from_bbox = self._renderer.copy_from_bbox
92
+
93
+ def draw_path(self, gc, path, transform, rgbFace=None):
94
+ # docstring inherited
95
+ nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing
96
+ npts = path.vertices.shape[0]
97
+
98
+ if (npts > nmax > 100 and path.should_simplify and
99
+ rgbFace is None and gc.get_hatch() is None):
100
+ nch = np.ceil(npts / nmax)
101
+ chsize = int(np.ceil(npts / nch))
102
+ i0 = np.arange(0, npts, chsize)
103
+ i1 = np.zeros_like(i0)
104
+ i1[:-1] = i0[1:] - 1
105
+ i1[-1] = npts
106
+ for ii0, ii1 in zip(i0, i1):
107
+ v = path.vertices[ii0:ii1, :]
108
+ c = path.codes
109
+ if c is not None:
110
+ c = c[ii0:ii1]
111
+ c[0] = Path.MOVETO # move to end of last chunk
112
+ p = Path(v, c)
113
+ p.simplify_threshold = path.simplify_threshold
114
+ try:
115
+ self._renderer.draw_path(gc, p, transform, rgbFace)
116
+ except OverflowError:
117
+ msg = (
118
+ "Exceeded cell block limit in Agg.\n\n"
119
+ "Please reduce the value of "
120
+ f"rcParams['agg.path.chunksize'] (currently {nmax}) "
121
+ "or increase the path simplification threshold"
122
+ "(rcParams['path.simplify_threshold'] = "
123
+ f"{mpl.rcParams['path.simplify_threshold']:.2f} by "
124
+ "default and path.simplify_threshold = "
125
+ f"{path.simplify_threshold:.2f} on the input)."
126
+ )
127
+ raise OverflowError(msg) from None
128
+ else:
129
+ try:
130
+ self._renderer.draw_path(gc, path, transform, rgbFace)
131
+ except OverflowError:
132
+ cant_chunk = ''
133
+ if rgbFace is not None:
134
+ cant_chunk += "- cannot split filled path\n"
135
+ if gc.get_hatch() is not None:
136
+ cant_chunk += "- cannot split hatched path\n"
137
+ if not path.should_simplify:
138
+ cant_chunk += "- path.should_simplify is False\n"
139
+ if len(cant_chunk):
140
+ msg = (
141
+ "Exceeded cell block limit in Agg, however for the "
142
+ "following reasons:\n\n"
143
+ f"{cant_chunk}\n"
144
+ "we cannot automatically split up this path to draw."
145
+ "\n\nPlease manually simplify your path."
146
+ )
147
+
148
+ else:
149
+ inc_threshold = (
150
+ "or increase the path simplification threshold"
151
+ "(rcParams['path.simplify_threshold'] = "
152
+ f"{mpl.rcParams['path.simplify_threshold']} "
153
+ "by default and path.simplify_threshold "
154
+ f"= {path.simplify_threshold} "
155
+ "on the input)."
156
+ )
157
+ if nmax > 100:
158
+ msg = (
159
+ "Exceeded cell block limit in Agg. Please reduce "
160
+ "the value of rcParams['agg.path.chunksize'] "
161
+ f"(currently {nmax}) {inc_threshold}"
162
+ )
163
+ else:
164
+ msg = (
165
+ "Exceeded cell block limit in Agg. Please set "
166
+ "the value of rcParams['agg.path.chunksize'], "
167
+ f"(currently {nmax}) to be greater than 100 "
168
+ + inc_threshold
169
+ )
170
+
171
+ raise OverflowError(msg) from None
172
+
173
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
174
+ """Draw mathtext using :mod:`matplotlib.mathtext`."""
175
+ ox, oy, width, height, descent, font_image = \
176
+ self.mathtext_parser.parse(s, self.dpi, prop,
177
+ antialiased=gc.get_antialiased())
178
+
179
+ xd = descent * sin(radians(angle))
180
+ yd = descent * cos(radians(angle))
181
+ x = round(x + ox + xd)
182
+ y = round(y - oy + yd)
183
+ self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
184
+
185
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
186
+ # docstring inherited
187
+ if ismath:
188
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
189
+ font = self._prepare_font(prop)
190
+ # We pass '0' for angle here, since it will be rotated (in raster
191
+ # space) in the following call to draw_text_image).
192
+ font.set_text(s, 0, flags=get_hinting_flag())
193
+ font.draw_glyphs_to_bitmap(
194
+ antialiased=gc.get_antialiased())
195
+ d = font.get_descent() / 64.0
196
+ # The descent needs to be adjusted for the angle.
197
+ xo, yo = font.get_bitmap_offset()
198
+ xo /= 64.0
199
+ yo /= 64.0
200
+ xd = d * sin(radians(angle))
201
+ yd = d * cos(radians(angle))
202
+ x = round(x + xo + xd)
203
+ y = round(y + yo + yd)
204
+ self._renderer.draw_text_image(font, x, y + 1, angle, gc)
205
+
206
+ def get_text_width_height_descent(self, s, prop, ismath):
207
+ # docstring inherited
208
+
209
+ _api.check_in_list(["TeX", True, False], ismath=ismath)
210
+ if ismath == "TeX":
211
+ return super().get_text_width_height_descent(s, prop, ismath)
212
+
213
+ if ismath:
214
+ ox, oy, width, height, descent, font_image = \
215
+ self.mathtext_parser.parse(s, self.dpi, prop)
216
+ return width, height, descent
217
+
218
+ font = self._prepare_font(prop)
219
+ font.set_text(s, 0.0, flags=get_hinting_flag())
220
+ w, h = font.get_width_height() # width and height of unrotated string
221
+ d = font.get_descent()
222
+ w /= 64.0 # convert from subpixels
223
+ h /= 64.0
224
+ d /= 64.0
225
+ return w, h, d
226
+
227
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
228
+ # docstring inherited
229
+ # todo, handle props, angle, origins
230
+ size = prop.get_size_in_points()
231
+
232
+ texmanager = self.get_texmanager()
233
+
234
+ Z = texmanager.get_grey(s, size, self.dpi)
235
+ Z = np.array(Z * 255.0, np.uint8)
236
+
237
+ w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX")
238
+ xd = d * sin(radians(angle))
239
+ yd = d * cos(radians(angle))
240
+ x = round(x + xd)
241
+ y = round(y + yd)
242
+ self._renderer.draw_text_image(Z, x, y, angle, gc)
243
+
244
+ def get_canvas_width_height(self):
245
+ # docstring inherited
246
+ return self.width, self.height
247
+
248
+ def _prepare_font(self, font_prop):
249
+ """
250
+ Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size.
251
+ """
252
+ font = get_font(_fontManager._find_fonts_by_props(font_prop))
253
+ font.clear()
254
+ size = font_prop.get_size_in_points()
255
+ font.set_size(size, self.dpi)
256
+ return font
257
+
258
+ def points_to_pixels(self, points):
259
+ # docstring inherited
260
+ return points * self.dpi / 72
261
+
262
+ def buffer_rgba(self):
263
+ return memoryview(self._renderer)
264
+
265
+ def tostring_argb(self):
266
+ return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
267
+
268
+ def clear(self):
269
+ self._renderer.clear()
270
+
271
+ def option_image_nocomposite(self):
272
+ # docstring inherited
273
+
274
+ # It is generally faster to composite each image directly to
275
+ # the Figure, and there's no file size benefit to compositing
276
+ # with the Agg backend
277
+ return True
278
+
279
+ def option_scale_image(self):
280
+ # docstring inherited
281
+ return False
282
+
283
+ def restore_region(self, region, bbox=None, xy=None):
284
+ """
285
+ Restore the saved region. If bbox (instance of BboxBase, or
286
+ its extents) is given, only the region specified by the bbox
287
+ will be restored. *xy* (a pair of floats) optionally
288
+ specifies the new position (the LLC of the original region,
289
+ not the LLC of the bbox) where the region will be restored.
290
+
291
+ >>> region = renderer.copy_from_bbox()
292
+ >>> x1, y1, x2, y2 = region.get_extents()
293
+ >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
294
+ ... xy=(x1-dx, y1))
295
+
296
+ """
297
+ if bbox is not None or xy is not None:
298
+ if bbox is None:
299
+ x1, y1, x2, y2 = region.get_extents()
300
+ elif isinstance(bbox, BboxBase):
301
+ x1, y1, x2, y2 = bbox.extents
302
+ else:
303
+ x1, y1, x2, y2 = bbox
304
+
305
+ if xy is None:
306
+ ox, oy = x1, y1
307
+ else:
308
+ ox, oy = xy
309
+
310
+ # The incoming data is float, but the _renderer type-checking wants
311
+ # to see integers.
312
+ self._renderer.restore_region(region, int(x1), int(y1),
313
+ int(x2), int(y2), int(ox), int(oy))
314
+
315
+ else:
316
+ self._renderer.restore_region(region)
317
+
318
+ def start_filter(self):
319
+ """
320
+ Start filtering. It simply creates a new canvas (the old one is saved).
321
+ """
322
+ self._filter_renderers.append(self._renderer)
323
+ self._renderer = _RendererAgg(int(self.width), int(self.height),
324
+ self.dpi)
325
+ self._update_methods()
326
+
327
+ def stop_filter(self, post_processing):
328
+ """
329
+ Save the current canvas as an image and apply post processing.
330
+
331
+ The *post_processing* function::
332
+
333
+ def post_processing(image, dpi):
334
+ # ny, nx, depth = image.shape
335
+ # image (numpy array) has RGBA channels and has a depth of 4.
336
+ ...
337
+ # create a new_image (numpy array of 4 channels, size can be
338
+ # different). The resulting image may have offsets from
339
+ # lower-left corner of the original image
340
+ return new_image, offset_x, offset_y
341
+
342
+ The saved renderer is restored and the returned image from
343
+ post_processing is plotted (using draw_image) on it.
344
+ """
345
+ orig_img = np.asarray(self.buffer_rgba())
346
+ slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3])
347
+ cropped_img = orig_img[slice_y, slice_x]
348
+
349
+ self._renderer = self._filter_renderers.pop()
350
+ self._update_methods()
351
+
352
+ if cropped_img.size:
353
+ img, ox, oy = post_processing(cropped_img / 255, self.dpi)
354
+ gc = self.new_gc()
355
+ if img.dtype.kind == 'f':
356
+ img = np.asarray(img * 255., np.uint8)
357
+ self._renderer.draw_image(
358
+ gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy,
359
+ img[::-1])
360
+
361
+
362
+ class FigureCanvasAgg(FigureCanvasBase):
363
+ # docstring inherited
364
+
365
+ _lastKey = None # Overwritten per-instance on the first draw.
366
+
367
+ def copy_from_bbox(self, bbox):
368
+ renderer = self.get_renderer()
369
+ return renderer.copy_from_bbox(bbox)
370
+
371
+ def restore_region(self, region, bbox=None, xy=None):
372
+ renderer = self.get_renderer()
373
+ return renderer.restore_region(region, bbox, xy)
374
+
375
+ def draw(self):
376
+ # docstring inherited
377
+ self.renderer = self.get_renderer()
378
+ self.renderer.clear()
379
+ # Acquire a lock on the shared font cache.
380
+ with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
381
+ else nullcontext()):
382
+ self.figure.draw(self.renderer)
383
+ # A GUI class may be need to update a window using this draw, so
384
+ # don't forget to call the superclass.
385
+ super().draw()
386
+
387
+ def get_renderer(self):
388
+ w, h = self.figure.bbox.size
389
+ key = w, h, self.figure.dpi
390
+ reuse_renderer = (self._lastKey == key)
391
+ if not reuse_renderer:
392
+ self.renderer = RendererAgg(w, h, self.figure.dpi)
393
+ self._lastKey = key
394
+ return self.renderer
395
+
396
+ def tostring_argb(self):
397
+ """
398
+ Get the image as ARGB `bytes`.
399
+
400
+ `draw` must be called at least once before this function will work and
401
+ to update the renderer for any subsequent changes to the Figure.
402
+ """
403
+ return self.renderer.tostring_argb()
404
+
405
+ def buffer_rgba(self):
406
+ """
407
+ Get the image as a `memoryview` to the renderer's buffer.
408
+
409
+ `draw` must be called at least once before this function will work and
410
+ to update the renderer for any subsequent changes to the Figure.
411
+ """
412
+ return self.renderer.buffer_rgba()
413
+
414
+ def print_raw(self, filename_or_obj, *, metadata=None):
415
+ if metadata is not None:
416
+ raise ValueError("metadata not supported for raw/rgba")
417
+ FigureCanvasAgg.draw(self)
418
+ renderer = self.get_renderer()
419
+ with cbook.open_file_cm(filename_or_obj, "wb") as fh:
420
+ fh.write(renderer.buffer_rgba())
421
+
422
+ print_rgba = print_raw
423
+
424
+ def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
425
+ """
426
+ Draw the canvas, then save it using `.image.imsave` (to which
427
+ *pil_kwargs* and *metadata* are forwarded).
428
+ """
429
+ FigureCanvasAgg.draw(self)
430
+ mpl.image.imsave(
431
+ filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
432
+ dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)
433
+
434
+ def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
435
+ """
436
+ Write the figure to a PNG file.
437
+
438
+ Parameters
439
+ ----------
440
+ filename_or_obj : str or path-like or file-like
441
+ The file to write to.
442
+
443
+ metadata : dict, optional
444
+ Metadata in the PNG file as key-value pairs of bytes or latin-1
445
+ encodable strings.
446
+ According to the PNG specification, keys must be shorter than 79
447
+ chars.
448
+
449
+ The `PNG specification`_ defines some common keywords that may be
450
+ used as appropriate:
451
+
452
+ - Title: Short (one line) title or caption for image.
453
+ - Author: Name of image's creator.
454
+ - Description: Description of image (possibly long).
455
+ - Copyright: Copyright notice.
456
+ - Creation Time: Time of original image creation
457
+ (usually RFC 1123 format).
458
+ - Software: Software used to create the image.
459
+ - Disclaimer: Legal disclaimer.
460
+ - Warning: Warning of nature of content.
461
+ - Source: Device used to create the image.
462
+ - Comment: Miscellaneous comment;
463
+ conversion from other image format.
464
+
465
+ Other keywords may be invented for other purposes.
466
+
467
+ If 'Software' is not given, an autogenerated value for Matplotlib
468
+ will be used. This can be removed by setting it to *None*.
469
+
470
+ For more details see the `PNG specification`_.
471
+
472
+ .. _PNG specification: \
473
+ https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
474
+
475
+ pil_kwargs : dict, optional
476
+ Keyword arguments passed to `PIL.Image.Image.save`.
477
+
478
+ If the 'pnginfo' key is present, it completely overrides
479
+ *metadata*, including the default 'Software' key.
480
+ """
481
+ self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)
482
+
483
+ def print_to_buffer(self):
484
+ FigureCanvasAgg.draw(self)
485
+ renderer = self.get_renderer()
486
+ return (bytes(renderer.buffer_rgba()),
487
+ (int(renderer.width), int(renderer.height)))
488
+
489
+ # Note that these methods should typically be called via savefig() and
490
+ # print_figure(), and the latter ensures that `self.figure.dpi` already
491
+ # matches the dpi kwarg (if any).
492
+
493
+ def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
494
+ # savefig() has already applied savefig.facecolor; we now set it to
495
+ # white to make imsave() blend semi-transparent figures against an
496
+ # assumed white background.
497
+ with mpl.rc_context({"savefig.facecolor": "white"}):
498
+ self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)
499
+
500
+ print_jpeg = print_jpg
501
+
502
+ def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
503
+ self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)
504
+
505
+ print_tiff = print_tif
506
+
507
+ def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
508
+ self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)
509
+
510
+ print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(
511
+ """
512
+ Write the figure to a {} file.
513
+
514
+ Parameters
515
+ ----------
516
+ filename_or_obj : str or path-like or file-like
517
+ The file to write to.
518
+ pil_kwargs : dict, optional
519
+ Additional keyword arguments that are passed to
520
+ `PIL.Image.Image.save` when saving the figure.
521
+ """.format, ["JPEG", "TIFF", "WebP"])
522
+
523
+
524
+ @_Backend.export
525
+ class _BackendAgg(_Backend):
526
+ backend_version = 'v2.2'
527
+ FigureCanvas = FigureCanvasAgg
528
+ FigureManager = FigureManagerBase
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_cairo.py ADDED
@@ -0,0 +1,529 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Cairo backend for Matplotlib
3
+ ==============================
4
+ :Author: Steve Chaplin and others
5
+
6
+ This backend depends on cairocffi or pycairo.
7
+ """
8
+
9
+ import functools
10
+ import gzip
11
+ import math
12
+
13
+ import numpy as np
14
+
15
+ try:
16
+ import cairo
17
+ if cairo.version_info < (1, 14, 0): # Introduced set_device_scale.
18
+ raise ImportError(f"Cairo backend requires cairo>=1.14.0, "
19
+ f"but only {cairo.version_info} is available")
20
+ except ImportError:
21
+ try:
22
+ import cairocffi as cairo
23
+ except ImportError as err:
24
+ raise ImportError(
25
+ "cairo backend requires that pycairo>=1.14.0 or cairocffi "
26
+ "is installed") from err
27
+
28
+ from .. import _api, cbook, font_manager
29
+ from matplotlib.backend_bases import (
30
+ _Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
31
+ RendererBase)
32
+ from matplotlib.font_manager import ttfFontProperty
33
+ from matplotlib.path import Path
34
+ from matplotlib.transforms import Affine2D
35
+
36
+
37
+ def _set_rgba(ctx, color, alpha, forced_alpha):
38
+ if len(color) == 3 or forced_alpha:
39
+ ctx.set_source_rgba(*color[:3], alpha)
40
+ else:
41
+ ctx.set_source_rgba(*color)
42
+
43
+
44
+ def _append_path(ctx, path, transform, clip=None):
45
+ for points, code in path.iter_segments(
46
+ transform, remove_nans=True, clip=clip):
47
+ if code == Path.MOVETO:
48
+ ctx.move_to(*points)
49
+ elif code == Path.CLOSEPOLY:
50
+ ctx.close_path()
51
+ elif code == Path.LINETO:
52
+ ctx.line_to(*points)
53
+ elif code == Path.CURVE3:
54
+ cur = np.asarray(ctx.get_current_point())
55
+ a = points[:2]
56
+ b = points[-2:]
57
+ ctx.curve_to(*(cur / 3 + a * 2 / 3), *(a * 2 / 3 + b / 3), *b)
58
+ elif code == Path.CURVE4:
59
+ ctx.curve_to(*points)
60
+
61
+
62
+ def _cairo_font_args_from_font_prop(prop):
63
+ """
64
+ Convert a `.FontProperties` or a `.FontEntry` to arguments that can be
65
+ passed to `.Context.select_font_face`.
66
+ """
67
+ def attr(field):
68
+ try:
69
+ return getattr(prop, f"get_{field}")()
70
+ except AttributeError:
71
+ return getattr(prop, field)
72
+
73
+ name = attr("name")
74
+ slant = getattr(cairo, f"FONT_SLANT_{attr('style').upper()}")
75
+ weight = attr("weight")
76
+ weight = (cairo.FONT_WEIGHT_NORMAL
77
+ if font_manager.weight_dict.get(weight, weight) < 550
78
+ else cairo.FONT_WEIGHT_BOLD)
79
+ return name, slant, weight
80
+
81
+
82
+ class RendererCairo(RendererBase):
83
+ def __init__(self, dpi):
84
+ self.dpi = dpi
85
+ self.gc = GraphicsContextCairo(renderer=self)
86
+ self.width = None
87
+ self.height = None
88
+ self.text_ctx = cairo.Context(
89
+ cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
90
+ super().__init__()
91
+
92
+ def set_context(self, ctx):
93
+ surface = ctx.get_target()
94
+ if hasattr(surface, "get_width") and hasattr(surface, "get_height"):
95
+ size = surface.get_width(), surface.get_height()
96
+ elif hasattr(surface, "get_extents"): # GTK4 RecordingSurface.
97
+ ext = surface.get_extents()
98
+ size = ext.width, ext.height
99
+ else: # vector surfaces.
100
+ ctx.save()
101
+ ctx.reset_clip()
102
+ rect, *rest = ctx.copy_clip_rectangle_list()
103
+ if rest:
104
+ raise TypeError("Cannot infer surface size")
105
+ _, _, *size = rect
106
+ ctx.restore()
107
+ self.gc.ctx = ctx
108
+ self.width, self.height = size
109
+
110
+ @staticmethod
111
+ def _fill_and_stroke(ctx, fill_c, alpha, alpha_overrides):
112
+ if fill_c is not None:
113
+ ctx.save()
114
+ _set_rgba(ctx, fill_c, alpha, alpha_overrides)
115
+ ctx.fill_preserve()
116
+ ctx.restore()
117
+ ctx.stroke()
118
+
119
+ def draw_path(self, gc, path, transform, rgbFace=None):
120
+ # docstring inherited
121
+ ctx = gc.ctx
122
+ # Clip the path to the actual rendering extents if it isn't filled.
123
+ clip = (ctx.clip_extents()
124
+ if rgbFace is None and gc.get_hatch() is None
125
+ else None)
126
+ transform = (transform
127
+ + Affine2D().scale(1, -1).translate(0, self.height))
128
+ ctx.new_path()
129
+ _append_path(ctx, path, transform, clip)
130
+ if rgbFace is not None:
131
+ ctx.save()
132
+ _set_rgba(ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
133
+ ctx.fill_preserve()
134
+ ctx.restore()
135
+ hatch_path = gc.get_hatch_path()
136
+ if hatch_path:
137
+ dpi = int(self.dpi)
138
+ hatch_surface = ctx.get_target().create_similar(
139
+ cairo.Content.COLOR_ALPHA, dpi, dpi)
140
+ hatch_ctx = cairo.Context(hatch_surface)
141
+ _append_path(hatch_ctx, hatch_path,
142
+ Affine2D().scale(dpi, -dpi).translate(0, dpi),
143
+ None)
144
+ hatch_ctx.set_line_width(self.points_to_pixels(gc.get_hatch_linewidth()))
145
+ hatch_ctx.set_source_rgba(*gc.get_hatch_color())
146
+ hatch_ctx.fill_preserve()
147
+ hatch_ctx.stroke()
148
+ hatch_pattern = cairo.SurfacePattern(hatch_surface)
149
+ hatch_pattern.set_extend(cairo.Extend.REPEAT)
150
+ ctx.save()
151
+ ctx.set_source(hatch_pattern)
152
+ ctx.fill_preserve()
153
+ ctx.restore()
154
+ ctx.stroke()
155
+
156
+ def draw_markers(self, gc, marker_path, marker_trans, path, transform,
157
+ rgbFace=None):
158
+ # docstring inherited
159
+
160
+ ctx = gc.ctx
161
+ ctx.new_path()
162
+ # Create the path for the marker; it needs to be flipped here already!
163
+ _append_path(ctx, marker_path, marker_trans + Affine2D().scale(1, -1))
164
+ marker_path = ctx.copy_path_flat()
165
+
166
+ # Figure out whether the path has a fill
167
+ x1, y1, x2, y2 = ctx.fill_extents()
168
+ if x1 == 0 and y1 == 0 and x2 == 0 and y2 == 0:
169
+ filled = False
170
+ # No fill, just unset this (so we don't try to fill it later on)
171
+ rgbFace = None
172
+ else:
173
+ filled = True
174
+
175
+ transform = (transform
176
+ + Affine2D().scale(1, -1).translate(0, self.height))
177
+
178
+ ctx.new_path()
179
+ for i, (vertices, codes) in enumerate(
180
+ path.iter_segments(transform, simplify=False)):
181
+ if len(vertices):
182
+ x, y = vertices[-2:]
183
+ ctx.save()
184
+
185
+ # Translate and apply path
186
+ ctx.translate(x, y)
187
+ ctx.append_path(marker_path)
188
+
189
+ ctx.restore()
190
+
191
+ # Slower code path if there is a fill; we need to draw
192
+ # the fill and stroke for each marker at the same time.
193
+ # Also flush out the drawing every once in a while to
194
+ # prevent the paths from getting way too long.
195
+ if filled or i % 1000 == 0:
196
+ self._fill_and_stroke(
197
+ ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
198
+
199
+ # Fast path, if there is no fill, draw everything in one step
200
+ if not filled:
201
+ self._fill_and_stroke(
202
+ ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha())
203
+
204
+ def draw_image(self, gc, x, y, im):
205
+ im = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(im[::-1])
206
+ surface = cairo.ImageSurface.create_for_data(
207
+ im.ravel().data, cairo.FORMAT_ARGB32,
208
+ im.shape[1], im.shape[0], im.shape[1] * 4)
209
+ ctx = gc.ctx
210
+ y = self.height - y - im.shape[0]
211
+
212
+ ctx.save()
213
+ ctx.set_source_surface(surface, float(x), float(y))
214
+ ctx.paint()
215
+ ctx.restore()
216
+
217
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
218
+ # docstring inherited
219
+
220
+ # Note: (x, y) are device/display coords, not user-coords, unlike other
221
+ # draw_* methods
222
+ if ismath:
223
+ self._draw_mathtext(gc, x, y, s, prop, angle)
224
+
225
+ else:
226
+ ctx = gc.ctx
227
+ ctx.new_path()
228
+ ctx.move_to(x, y)
229
+
230
+ ctx.save()
231
+ ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
232
+ ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
233
+ opts = cairo.FontOptions()
234
+ opts.set_antialias(gc.get_antialiased())
235
+ ctx.set_font_options(opts)
236
+ if angle:
237
+ ctx.rotate(np.deg2rad(-angle))
238
+ ctx.show_text(s)
239
+ ctx.restore()
240
+
241
+ def _draw_mathtext(self, gc, x, y, s, prop, angle):
242
+ ctx = gc.ctx
243
+ width, height, descent, glyphs, rects = \
244
+ self._text2path.mathtext_parser.parse(s, self.dpi, prop)
245
+
246
+ ctx.save()
247
+ ctx.translate(x, y)
248
+ if angle:
249
+ ctx.rotate(np.deg2rad(-angle))
250
+
251
+ for font, fontsize, idx, ox, oy in glyphs:
252
+ ctx.new_path()
253
+ ctx.move_to(ox, -oy)
254
+ ctx.select_font_face(
255
+ *_cairo_font_args_from_font_prop(ttfFontProperty(font)))
256
+ ctx.set_font_size(self.points_to_pixels(fontsize))
257
+ ctx.show_text(chr(idx))
258
+
259
+ for ox, oy, w, h in rects:
260
+ ctx.new_path()
261
+ ctx.rectangle(ox, -oy, w, -h)
262
+ ctx.set_source_rgb(0, 0, 0)
263
+ ctx.fill_preserve()
264
+
265
+ ctx.restore()
266
+
267
+ def get_canvas_width_height(self):
268
+ # docstring inherited
269
+ return self.width, self.height
270
+
271
+ def get_text_width_height_descent(self, s, prop, ismath):
272
+ # docstring inherited
273
+
274
+ if ismath == 'TeX':
275
+ return super().get_text_width_height_descent(s, prop, ismath)
276
+
277
+ if ismath:
278
+ width, height, descent, *_ = \
279
+ self._text2path.mathtext_parser.parse(s, self.dpi, prop)
280
+ return width, height, descent
281
+
282
+ ctx = self.text_ctx
283
+ # problem - scale remembers last setting and font can become
284
+ # enormous causing program to crash
285
+ # save/restore prevents the problem
286
+ ctx.save()
287
+ ctx.select_font_face(*_cairo_font_args_from_font_prop(prop))
288
+ ctx.set_font_size(self.points_to_pixels(prop.get_size_in_points()))
289
+
290
+ y_bearing, w, h = ctx.text_extents(s)[1:4]
291
+ ctx.restore()
292
+
293
+ return w, h, h + y_bearing
294
+
295
+ def new_gc(self):
296
+ # docstring inherited
297
+ self.gc.ctx.save()
298
+ # FIXME: The following doesn't properly implement a stack-like behavior
299
+ # and relies instead on the (non-guaranteed) fact that artists never
300
+ # rely on nesting gc states, so directly resetting the attributes (IOW
301
+ # a single-level stack) is enough.
302
+ self.gc._alpha = 1
303
+ self.gc._forced_alpha = False # if True, _alpha overrides A from RGBA
304
+ self.gc._hatch = None
305
+ return self.gc
306
+
307
+ def points_to_pixels(self, points):
308
+ # docstring inherited
309
+ return points / 72 * self.dpi
310
+
311
+
312
+ class GraphicsContextCairo(GraphicsContextBase):
313
+ _joind = {
314
+ 'bevel': cairo.LINE_JOIN_BEVEL,
315
+ 'miter': cairo.LINE_JOIN_MITER,
316
+ 'round': cairo.LINE_JOIN_ROUND,
317
+ }
318
+
319
+ _capd = {
320
+ 'butt': cairo.LINE_CAP_BUTT,
321
+ 'projecting': cairo.LINE_CAP_SQUARE,
322
+ 'round': cairo.LINE_CAP_ROUND,
323
+ }
324
+
325
+ def __init__(self, renderer):
326
+ super().__init__()
327
+ self.renderer = renderer
328
+
329
+ def restore(self):
330
+ self.ctx.restore()
331
+
332
+ def set_alpha(self, alpha):
333
+ super().set_alpha(alpha)
334
+ _set_rgba(
335
+ self.ctx, self._rgb, self.get_alpha(), self.get_forced_alpha())
336
+
337
+ def set_antialiased(self, b):
338
+ self.ctx.set_antialias(
339
+ cairo.ANTIALIAS_DEFAULT if b else cairo.ANTIALIAS_NONE)
340
+
341
+ def get_antialiased(self):
342
+ return self.ctx.get_antialias()
343
+
344
+ def set_capstyle(self, cs):
345
+ self.ctx.set_line_cap(_api.check_getitem(self._capd, capstyle=cs))
346
+ self._capstyle = cs
347
+
348
+ def set_clip_rectangle(self, rectangle):
349
+ if not rectangle:
350
+ return
351
+ x, y, w, h = np.round(rectangle.bounds)
352
+ ctx = self.ctx
353
+ ctx.new_path()
354
+ ctx.rectangle(x, self.renderer.height - h - y, w, h)
355
+ ctx.clip()
356
+
357
+ def set_clip_path(self, path):
358
+ if not path:
359
+ return
360
+ tpath, affine = path.get_transformed_path_and_affine()
361
+ ctx = self.ctx
362
+ ctx.new_path()
363
+ affine = (affine
364
+ + Affine2D().scale(1, -1).translate(0, self.renderer.height))
365
+ _append_path(ctx, tpath, affine)
366
+ ctx.clip()
367
+
368
+ def set_dashes(self, offset, dashes):
369
+ self._dashes = offset, dashes
370
+ if dashes is None:
371
+ self.ctx.set_dash([], 0) # switch dashes off
372
+ else:
373
+ self.ctx.set_dash(
374
+ list(self.renderer.points_to_pixels(np.asarray(dashes))),
375
+ offset)
376
+
377
+ def set_foreground(self, fg, isRGBA=None):
378
+ super().set_foreground(fg, isRGBA)
379
+ if len(self._rgb) == 3:
380
+ self.ctx.set_source_rgb(*self._rgb)
381
+ else:
382
+ self.ctx.set_source_rgba(*self._rgb)
383
+
384
+ def get_rgb(self):
385
+ return self.ctx.get_source().get_rgba()[:3]
386
+
387
+ def set_joinstyle(self, js):
388
+ self.ctx.set_line_join(_api.check_getitem(self._joind, joinstyle=js))
389
+ self._joinstyle = js
390
+
391
+ def set_linewidth(self, w):
392
+ self._linewidth = float(w)
393
+ self.ctx.set_line_width(self.renderer.points_to_pixels(w))
394
+
395
+
396
+ class _CairoRegion:
397
+ def __init__(self, slices, data):
398
+ self._slices = slices
399
+ self._data = data
400
+
401
+
402
+ class FigureCanvasCairo(FigureCanvasBase):
403
+ @property
404
+ def _renderer(self):
405
+ # In theory, _renderer should be set in __init__, but GUI canvas
406
+ # subclasses (FigureCanvasFooCairo) don't always interact well with
407
+ # multiple inheritance (FigureCanvasFoo inits but doesn't super-init
408
+ # FigureCanvasCairo), so initialize it in the getter instead.
409
+ if not hasattr(self, "_cached_renderer"):
410
+ self._cached_renderer = RendererCairo(self.figure.dpi)
411
+ return self._cached_renderer
412
+
413
+ def get_renderer(self):
414
+ return self._renderer
415
+
416
+ def copy_from_bbox(self, bbox):
417
+ surface = self._renderer.gc.ctx.get_target()
418
+ if not isinstance(surface, cairo.ImageSurface):
419
+ raise RuntimeError(
420
+ "copy_from_bbox only works when rendering to an ImageSurface")
421
+ sw = surface.get_width()
422
+ sh = surface.get_height()
423
+ x0 = math.ceil(bbox.x0)
424
+ x1 = math.floor(bbox.x1)
425
+ y0 = math.ceil(sh - bbox.y1)
426
+ y1 = math.floor(sh - bbox.y0)
427
+ if not (0 <= x0 and x1 <= sw and bbox.x0 <= bbox.x1
428
+ and 0 <= y0 and y1 <= sh and bbox.y0 <= bbox.y1):
429
+ raise ValueError("Invalid bbox")
430
+ sls = slice(y0, y0 + max(y1 - y0, 0)), slice(x0, x0 + max(x1 - x0, 0))
431
+ data = (np.frombuffer(surface.get_data(), np.uint32)
432
+ .reshape((sh, sw))[sls].copy())
433
+ return _CairoRegion(sls, data)
434
+
435
+ def restore_region(self, region):
436
+ surface = self._renderer.gc.ctx.get_target()
437
+ if not isinstance(surface, cairo.ImageSurface):
438
+ raise RuntimeError(
439
+ "restore_region only works when rendering to an ImageSurface")
440
+ surface.flush()
441
+ sw = surface.get_width()
442
+ sh = surface.get_height()
443
+ sly, slx = region._slices
444
+ (np.frombuffer(surface.get_data(), np.uint32)
445
+ .reshape((sh, sw))[sly, slx]) = region._data
446
+ surface.mark_dirty_rectangle(
447
+ slx.start, sly.start, slx.stop - slx.start, sly.stop - sly.start)
448
+
449
+ def print_png(self, fobj):
450
+ self._get_printed_image_surface().write_to_png(fobj)
451
+
452
+ def print_rgba(self, fobj):
453
+ width, height = self.get_width_height()
454
+ buf = self._get_printed_image_surface().get_data()
455
+ fobj.write(cbook._premultiplied_argb32_to_unmultiplied_rgba8888(
456
+ np.asarray(buf).reshape((width, height, 4))))
457
+
458
+ print_raw = print_rgba
459
+
460
+ def _get_printed_image_surface(self):
461
+ self._renderer.dpi = self.figure.dpi
462
+ width, height = self.get_width_height()
463
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
464
+ self._renderer.set_context(cairo.Context(surface))
465
+ self.figure.draw(self._renderer)
466
+ return surface
467
+
468
+ def _save(self, fmt, fobj, *, orientation='portrait'):
469
+ # save PDF/PS/SVG
470
+
471
+ dpi = 72
472
+ self.figure.dpi = dpi
473
+ w_in, h_in = self.figure.get_size_inches()
474
+ width_in_points, height_in_points = w_in * dpi, h_in * dpi
475
+
476
+ if orientation == 'landscape':
477
+ width_in_points, height_in_points = (
478
+ height_in_points, width_in_points)
479
+
480
+ if fmt == 'ps':
481
+ if not hasattr(cairo, 'PSSurface'):
482
+ raise RuntimeError('cairo has not been compiled with PS '
483
+ 'support enabled')
484
+ surface = cairo.PSSurface(fobj, width_in_points, height_in_points)
485
+ elif fmt == 'pdf':
486
+ if not hasattr(cairo, 'PDFSurface'):
487
+ raise RuntimeError('cairo has not been compiled with PDF '
488
+ 'support enabled')
489
+ surface = cairo.PDFSurface(fobj, width_in_points, height_in_points)
490
+ elif fmt in ('svg', 'svgz'):
491
+ if not hasattr(cairo, 'SVGSurface'):
492
+ raise RuntimeError('cairo has not been compiled with SVG '
493
+ 'support enabled')
494
+ if fmt == 'svgz':
495
+ if isinstance(fobj, str):
496
+ fobj = gzip.GzipFile(fobj, 'wb')
497
+ else:
498
+ fobj = gzip.GzipFile(None, 'wb', fileobj=fobj)
499
+ surface = cairo.SVGSurface(fobj, width_in_points, height_in_points)
500
+ else:
501
+ raise ValueError(f"Unknown format: {fmt!r}")
502
+
503
+ self._renderer.dpi = self.figure.dpi
504
+ self._renderer.set_context(cairo.Context(surface))
505
+ ctx = self._renderer.gc.ctx
506
+
507
+ if orientation == 'landscape':
508
+ ctx.rotate(np.pi / 2)
509
+ ctx.translate(0, -height_in_points)
510
+ # Perhaps add an '%%Orientation: Landscape' comment?
511
+
512
+ self.figure.draw(self._renderer)
513
+
514
+ ctx.show_page()
515
+ surface.finish()
516
+ if fmt == 'svgz':
517
+ fobj.close()
518
+
519
+ print_pdf = functools.partialmethod(_save, "pdf")
520
+ print_ps = functools.partialmethod(_save, "ps")
521
+ print_svg = functools.partialmethod(_save, "svg")
522
+ print_svgz = functools.partialmethod(_save, "svgz")
523
+
524
+
525
+ @_Backend.export
526
+ class _BackendCairo(_Backend):
527
+ backend_version = cairo.version
528
+ FigureCanvas = FigureCanvasCairo
529
+ FigureManager = FigureManagerBase
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk3.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, MouseButton,
10
+ CloseEvent, KeyEvent, LocationEvent, MouseEvent, ResizeEvent)
11
+
12
+ try:
13
+ from gi import require_version as gi_require_version
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
+ buttons=self._mpl_buttons(event.state),
160
+ modifiers=self._mpl_modifiers(event.state),
161
+ guiEvent=event)._process()
162
+ return False # finish event propagation?
163
+
164
+ def enter_notify_event(self, widget, event):
165
+ gtk_mods = Gdk.Keymap.get_for_display(
166
+ self.get_display()).get_modifier_state()
167
+ LocationEvent("figure_enter_event", self, *self._mpl_coords(event),
168
+ modifiers=self._mpl_modifiers(gtk_mods),
169
+ guiEvent=event)._process()
170
+
171
+ def leave_notify_event(self, widget, event):
172
+ gtk_mods = Gdk.Keymap.get_for_display(
173
+ self.get_display()).get_modifier_state()
174
+ LocationEvent("figure_leave_event", self, *self._mpl_coords(event),
175
+ modifiers=self._mpl_modifiers(gtk_mods),
176
+ guiEvent=event)._process()
177
+
178
+ def size_allocate(self, widget, allocation):
179
+ dpival = self.figure.dpi
180
+ winch = allocation.width * self.device_pixel_ratio / dpival
181
+ hinch = allocation.height * self.device_pixel_ratio / dpival
182
+ self.figure.set_size_inches(winch, hinch, forward=False)
183
+ ResizeEvent("resize_event", self)._process()
184
+ self.draw_idle()
185
+
186
+ @staticmethod
187
+ def _mpl_buttons(event_state):
188
+ modifiers = [
189
+ (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),
190
+ (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),
191
+ (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),
192
+ (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),
193
+ (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),
194
+ ]
195
+ # State *before* press/release.
196
+ return [name for name, mask in modifiers if event_state & mask]
197
+
198
+ @staticmethod
199
+ def _mpl_modifiers(event_state, *, exclude=None):
200
+ modifiers = [
201
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
202
+ ("alt", Gdk.ModifierType.MOD1_MASK, "alt"),
203
+ ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
204
+ ("super", Gdk.ModifierType.MOD4_MASK, "super"),
205
+ ]
206
+ return [name for name, mask, key in modifiers
207
+ if exclude != key and event_state & mask]
208
+
209
+ def _get_key(self, event):
210
+ unikey = chr(Gdk.keyval_to_unicode(event.keyval))
211
+ key = cbook._unikey_or_keysym_to_mplkey(
212
+ unikey, Gdk.keyval_name(event.keyval))
213
+ mods = self._mpl_modifiers(event.state, exclude=key)
214
+ if "shift" in mods and unikey.isprintable():
215
+ mods.remove("shift")
216
+ return "+".join([*mods, key])
217
+
218
+ def _update_device_pixel_ratio(self, *args, **kwargs):
219
+ # We need to be careful in cases with mixed resolution displays if
220
+ # device_pixel_ratio changes.
221
+ if self._set_device_pixel_ratio(self.get_scale_factor()):
222
+ # The easiest way to resize the canvas is to emit a resize event
223
+ # since we implement all the logic for resizing the canvas for that
224
+ # event.
225
+ self.queue_resize()
226
+ self.queue_draw()
227
+
228
+ def configure_event(self, widget, event):
229
+ if widget.get_property("window") is None:
230
+ return
231
+ w = event.width * self.device_pixel_ratio
232
+ h = event.height * self.device_pixel_ratio
233
+ if w < 3 or h < 3:
234
+ return # empty fig
235
+ # resize the figure (in inches)
236
+ dpi = self.figure.dpi
237
+ self.figure.set_size_inches(w / dpi, h / dpi, forward=False)
238
+ return False # finish event propagation?
239
+
240
+ def _draw_rubberband(self, rect):
241
+ self._rubberband_rect = rect
242
+ # TODO: Only update the rubberband area.
243
+ self.queue_draw()
244
+
245
+ def _post_draw(self, widget, ctx):
246
+ if self._rubberband_rect is None:
247
+ return
248
+
249
+ x0, y0, w, h = (dim / self.device_pixel_ratio
250
+ for dim in self._rubberband_rect)
251
+ x1 = x0 + w
252
+ y1 = y0 + h
253
+
254
+ # Draw the lines from x0, y0 towards x1, y1 so that the
255
+ # dashes don't "jump" when moving the zoom box.
256
+ ctx.move_to(x0, y0)
257
+ ctx.line_to(x0, y1)
258
+ ctx.move_to(x0, y0)
259
+ ctx.line_to(x1, y0)
260
+ ctx.move_to(x0, y1)
261
+ ctx.line_to(x1, y1)
262
+ ctx.move_to(x1, y0)
263
+ ctx.line_to(x1, y1)
264
+
265
+ ctx.set_antialias(1)
266
+ ctx.set_line_width(1)
267
+ ctx.set_dash((3, 3), 0)
268
+ ctx.set_source_rgb(0, 0, 0)
269
+ ctx.stroke_preserve()
270
+
271
+ ctx.set_dash((3, 3), 3)
272
+ ctx.set_source_rgb(1, 1, 1)
273
+ ctx.stroke()
274
+
275
+ def on_draw_event(self, widget, ctx):
276
+ # to be overwritten by GTK3Agg or GTK3Cairo
277
+ pass
278
+
279
+ def draw(self):
280
+ # docstring inherited
281
+ if self.is_drawable():
282
+ self.queue_draw()
283
+
284
+ def draw_idle(self):
285
+ # docstring inherited
286
+ if self._idle_draw_id != 0:
287
+ return
288
+ def idle_draw(*args):
289
+ try:
290
+ self.draw()
291
+ finally:
292
+ self._idle_draw_id = 0
293
+ return False
294
+ self._idle_draw_id = GLib.idle_add(idle_draw)
295
+
296
+ def flush_events(self):
297
+ # docstring inherited
298
+ context = GLib.MainContext.default()
299
+ while context.pending():
300
+ context.iteration(True)
301
+
302
+
303
+ class NavigationToolbar2GTK3(_NavigationToolbar2GTK, Gtk.Toolbar):
304
+ def __init__(self, canvas):
305
+ GObject.GObject.__init__(self)
306
+
307
+ self.set_style(Gtk.ToolbarStyle.ICONS)
308
+
309
+ self._gtk_ids = {}
310
+ for text, tooltip_text, image_file, callback in self.toolitems:
311
+ if text is None:
312
+ self.insert(Gtk.SeparatorToolItem(), -1)
313
+ continue
314
+ image = Gtk.Image.new_from_gicon(
315
+ Gio.Icon.new_for_string(
316
+ str(cbook._get_data_path('images',
317
+ f'{image_file}-symbolic.svg'))),
318
+ Gtk.IconSize.LARGE_TOOLBAR)
319
+ self._gtk_ids[text] = button = (
320
+ Gtk.ToggleToolButton() if callback in ['zoom', 'pan'] else
321
+ Gtk.ToolButton())
322
+ button.set_label(text)
323
+ button.set_icon_widget(image)
324
+ # Save the handler id, so that we can block it as needed.
325
+ button._signal_handler = button.connect(
326
+ 'clicked', getattr(self, callback))
327
+ button.set_tooltip_text(tooltip_text)
328
+ self.insert(button, -1)
329
+
330
+ # This filler item ensures the toolbar is always at least two text
331
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
332
+ # over images because those use two-line messages which resize the
333
+ # toolbar.
334
+ toolitem = Gtk.ToolItem()
335
+ self.insert(toolitem, -1)
336
+ label = Gtk.Label()
337
+ label.set_markup(
338
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
339
+ toolitem.set_expand(True) # Push real message to the right.
340
+ toolitem.add(label)
341
+
342
+ toolitem = Gtk.ToolItem()
343
+ self.insert(toolitem, -1)
344
+ self.message = Gtk.Label()
345
+ self.message.set_justify(Gtk.Justification.RIGHT)
346
+ toolitem.add(self.message)
347
+
348
+ self.show_all()
349
+
350
+ _NavigationToolbar2GTK.__init__(self, canvas)
351
+
352
+ def save_figure(self, *args):
353
+ dialog = Gtk.FileChooserDialog(
354
+ title="Save the figure",
355
+ transient_for=self.canvas.get_toplevel(),
356
+ action=Gtk.FileChooserAction.SAVE,
357
+ buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
358
+ Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
359
+ )
360
+ for name, fmts \
361
+ in self.canvas.get_supported_filetypes_grouped().items():
362
+ ff = Gtk.FileFilter()
363
+ ff.set_name(name)
364
+ for fmt in fmts:
365
+ ff.add_pattern(f'*.{fmt}')
366
+ dialog.add_filter(ff)
367
+ if self.canvas.get_default_filetype() in fmts:
368
+ dialog.set_filter(ff)
369
+
370
+ @functools.partial(dialog.connect, "notify::filter")
371
+ def on_notify_filter(*args):
372
+ name = dialog.get_filter().get_name()
373
+ fmt = self.canvas.get_supported_filetypes_grouped()[name][0]
374
+ dialog.set_current_name(
375
+ str(Path(dialog.get_current_name()).with_suffix(f'.{fmt}')))
376
+
377
+ dialog.set_current_folder(mpl.rcParams["savefig.directory"])
378
+ dialog.set_current_name(self.canvas.get_default_filename())
379
+ dialog.set_do_overwrite_confirmation(True)
380
+
381
+ response = dialog.run()
382
+ fname = dialog.get_filename()
383
+ ff = dialog.get_filter() # Doesn't autoadjust to filename :/
384
+ fmt = self.canvas.get_supported_filetypes_grouped()[ff.get_name()][0]
385
+ dialog.destroy()
386
+ if response != Gtk.ResponseType.OK:
387
+ return None
388
+ # Save dir for next time, unless empty str (which means use cwd).
389
+ if mpl.rcParams['savefig.directory']:
390
+ mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
391
+ try:
392
+ self.canvas.figure.savefig(fname, format=fmt)
393
+ return fname
394
+ except Exception as e:
395
+ dialog = Gtk.MessageDialog(
396
+ transient_for=self.canvas.get_toplevel(), text=str(e),
397
+ message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
398
+ dialog.run()
399
+ dialog.destroy()
400
+
401
+
402
+ class ToolbarGTK3(ToolContainerBase, Gtk.Box):
403
+ _icon_extension = '-symbolic.svg'
404
+
405
+ def __init__(self, toolmanager):
406
+ ToolContainerBase.__init__(self, toolmanager)
407
+ Gtk.Box.__init__(self)
408
+ self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
409
+ self._message = Gtk.Label()
410
+ self._message.set_justify(Gtk.Justification.RIGHT)
411
+ self.pack_end(self._message, False, False, 0)
412
+ self.show_all()
413
+ self._groups = {}
414
+ self._toolitems = {}
415
+
416
+ def add_toolitem(self, name, group, position, image_file, description,
417
+ toggle):
418
+ if toggle:
419
+ button = Gtk.ToggleToolButton()
420
+ else:
421
+ button = Gtk.ToolButton()
422
+ button.set_label(name)
423
+
424
+ if image_file is not None:
425
+ image = Gtk.Image.new_from_gicon(
426
+ Gio.Icon.new_for_string(image_file),
427
+ Gtk.IconSize.LARGE_TOOLBAR)
428
+ button.set_icon_widget(image)
429
+
430
+ if position is None:
431
+ position = -1
432
+
433
+ self._add_button(button, group, position)
434
+ signal = button.connect('clicked', self._call_tool, name)
435
+ button.set_tooltip_text(description)
436
+ button.show_all()
437
+ self._toolitems.setdefault(name, [])
438
+ self._toolitems[name].append((button, signal))
439
+
440
+ def _add_button(self, button, group, position):
441
+ if group not in self._groups:
442
+ if self._groups:
443
+ self._add_separator()
444
+ toolbar = Gtk.Toolbar()
445
+ toolbar.set_style(Gtk.ToolbarStyle.ICONS)
446
+ self.pack_start(toolbar, False, False, 0)
447
+ toolbar.show_all()
448
+ self._groups[group] = toolbar
449
+ self._groups[group].insert(button, position)
450
+
451
+ def _call_tool(self, btn, name):
452
+ self.trigger_tool(name)
453
+
454
+ def toggle_toolitem(self, name, toggled):
455
+ if name not in self._toolitems:
456
+ return
457
+ for toolitem, signal in self._toolitems[name]:
458
+ toolitem.handler_block(signal)
459
+ toolitem.set_active(toggled)
460
+ toolitem.handler_unblock(signal)
461
+
462
+ def remove_toolitem(self, name):
463
+ for toolitem, _signal in self._toolitems.pop(name, []):
464
+ for group in self._groups:
465
+ if toolitem in self._groups[group]:
466
+ self._groups[group].remove(toolitem)
467
+
468
+ def _add_separator(self):
469
+ sep = Gtk.Separator()
470
+ sep.set_property("orientation", Gtk.Orientation.VERTICAL)
471
+ self.pack_start(sep, False, True, 0)
472
+ sep.show_all()
473
+
474
+ def set_message(self, s):
475
+ self._message.set_label(s)
476
+
477
+
478
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
479
+ class SaveFigureGTK3(backend_tools.SaveFigureBase):
480
+ def trigger(self, *args, **kwargs):
481
+ NavigationToolbar2GTK3.save_figure(
482
+ self._make_classic_style_pseudo_toolbar())
483
+
484
+
485
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
486
+ class HelpGTK3(backend_tools.ToolHelpBase):
487
+ def _normalize_shortcut(self, key):
488
+ """
489
+ Convert Matplotlib key presses to GTK+ accelerator identifiers.
490
+
491
+ Related to `FigureCanvasGTK3._get_key`.
492
+ """
493
+ special = {
494
+ 'backspace': 'BackSpace',
495
+ 'pagedown': 'Page_Down',
496
+ 'pageup': 'Page_Up',
497
+ 'scroll_lock': 'Scroll_Lock',
498
+ }
499
+
500
+ parts = key.split('+')
501
+ mods = ['<' + mod + '>' for mod in parts[:-1]]
502
+ key = parts[-1]
503
+
504
+ if key in special:
505
+ key = special[key]
506
+ elif len(key) > 1:
507
+ key = key.capitalize()
508
+ elif key.isupper():
509
+ mods += ['<shift>']
510
+
511
+ return ''.join(mods) + key
512
+
513
+ def _is_valid_shortcut(self, key):
514
+ """
515
+ Check for a valid shortcut to be displayed.
516
+
517
+ - GTK will never send 'cmd+' (see `FigureCanvasGTK3._get_key`).
518
+ - The shortcut window only shows keyboard shortcuts, not mouse buttons.
519
+ """
520
+ return 'cmd+' not in key and not key.startswith('MouseButton.')
521
+
522
+ def _show_shortcuts_window(self):
523
+ section = Gtk.ShortcutsSection()
524
+
525
+ for name, tool in sorted(self.toolmanager.tools.items()):
526
+ if not tool.description:
527
+ continue
528
+
529
+ # Putting everything in a separate group allows GTK to
530
+ # automatically split them into separate columns/pages, which is
531
+ # useful because we have lots of shortcuts, some with many keys
532
+ # that are very wide.
533
+ group = Gtk.ShortcutsGroup()
534
+ section.add(group)
535
+ # A hack to remove the title since we have no group naming.
536
+ group.forall(lambda widget, data: widget.set_visible(False), None)
537
+
538
+ shortcut = Gtk.ShortcutsShortcut(
539
+ accelerator=' '.join(
540
+ self._normalize_shortcut(key)
541
+ for key in self.toolmanager.get_tool_keymap(name)
542
+ if self._is_valid_shortcut(key)),
543
+ title=tool.name,
544
+ subtitle=tool.description)
545
+ group.add(shortcut)
546
+
547
+ window = Gtk.ShortcutsWindow(
548
+ title='Help',
549
+ modal=True,
550
+ transient_for=self._figure.canvas.get_toplevel())
551
+ section.show() # Must be done explicitly before add!
552
+ window.add(section)
553
+
554
+ window.show_all()
555
+
556
+ def _show_shortcuts_dialog(self):
557
+ dialog = Gtk.MessageDialog(
558
+ self._figure.canvas.get_toplevel(),
559
+ 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, self._get_help_text(),
560
+ title="Help")
561
+ dialog.run()
562
+ dialog.destroy()
563
+
564
+ def trigger(self, *args):
565
+ if Gtk.check_version(3, 20, 0) is None:
566
+ self._show_shortcuts_window()
567
+ else:
568
+ self._show_shortcuts_dialog()
569
+
570
+
571
+ @backend_tools._register_tool_class(FigureCanvasGTK3)
572
+ class ToolCopyToClipboardGTK3(backend_tools.ToolCopyToClipboardBase):
573
+ def trigger(self, *args, **kwargs):
574
+ clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
575
+ window = self.canvas.get_window()
576
+ x, y, width, height = window.get_geometry()
577
+ pb = Gdk.pixbuf_get_from_window(window, x, y, width, height)
578
+ clipboard.set_image(pb)
579
+
580
+
581
+ Toolbar = ToolbarGTK3
582
+ backend_tools._register_tool_class(
583
+ FigureCanvasGTK3, _backend_gtk.ConfigureSubplotsGTK)
584
+ backend_tools._register_tool_class(
585
+ FigureCanvasGTK3, _backend_gtk.RubberbandGTK)
586
+
587
+
588
+ class FigureManagerGTK3(_FigureManagerGTK):
589
+ _toolbar2_class = NavigationToolbar2GTK3
590
+ _toolmanager_toolbar_class = ToolbarGTK3
591
+
592
+
593
+ @_BackendGTK.export
594
+ class _BackendGTK3(_BackendGTK):
595
+ FigureCanvas = FigureCanvasGTK3
596
+ FigureManager = FigureManagerGTK3
workspace/outputs/audit_venv/lib/python3.11/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 _BackendGTK3Agg(_BackendGTK3):
74
+ FigureCanvas = FigureCanvasGTK3Agg
workspace/outputs/audit_venv/lib/python3.11/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
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, MouseButton,
9
+ KeyEvent, LocationEvent, MouseEvent, ResizeEvent, CloseEvent)
10
+
11
+ try:
12
+ from gi import require_version as gi_require_version
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
+ import gi
26
+ from gi.repository import Gio, GLib, Gtk, Gdk, GdkPixbuf
27
+ from . import _backend_gtk
28
+ from ._backend_gtk import ( # noqa: F401 # pylint: disable=W0611
29
+ _BackendGTK, _FigureCanvasGTK, _FigureManagerGTK, _NavigationToolbar2GTK,
30
+ TimerGTK as TimerGTK4,
31
+ )
32
+
33
+ _GOBJECT_GE_3_47 = gi.version_info >= (3, 47, 0)
34
+ _GTK_GE_4_12 = Gtk.check_version(4, 12, 0) is None
35
+
36
+
37
+ class FigureCanvasGTK4(_FigureCanvasGTK, Gtk.DrawingArea):
38
+ required_interactive_framework = "gtk4"
39
+ supports_blit = False
40
+ manager_class = _api.classproperty(lambda cls: FigureManagerGTK4)
41
+
42
+ def __init__(self, figure=None):
43
+ super().__init__(figure=figure)
44
+
45
+ self.set_hexpand(True)
46
+ self.set_vexpand(True)
47
+
48
+ self._idle_draw_id = 0
49
+ self._rubberband_rect = None
50
+
51
+ self.set_draw_func(self._draw_func)
52
+ self.connect('resize', self.resize_event)
53
+ if _GTK_GE_4_12:
54
+ self.connect('realize', self._realize_event)
55
+ else:
56
+ self.connect('notify::scale-factor', self._update_device_pixel_ratio)
57
+
58
+ click = Gtk.GestureClick()
59
+ click.set_button(0) # All buttons.
60
+ click.connect('pressed', self.button_press_event)
61
+ click.connect('released', self.button_release_event)
62
+ self.add_controller(click)
63
+
64
+ key = Gtk.EventControllerKey()
65
+ key.connect('key-pressed', self.key_press_event)
66
+ key.connect('key-released', self.key_release_event)
67
+ self.add_controller(key)
68
+
69
+ motion = Gtk.EventControllerMotion()
70
+ motion.connect('motion', self.motion_notify_event)
71
+ motion.connect('enter', self.enter_notify_event)
72
+ motion.connect('leave', self.leave_notify_event)
73
+ self.add_controller(motion)
74
+
75
+ scroll = Gtk.EventControllerScroll.new(
76
+ Gtk.EventControllerScrollFlags.VERTICAL)
77
+ scroll.connect('scroll', self.scroll_event)
78
+ self.add_controller(scroll)
79
+
80
+ self.set_focusable(True)
81
+
82
+ css = Gtk.CssProvider()
83
+ style = '.matplotlib-canvas { background-color: white; }'
84
+ if Gtk.check_version(4, 9, 3) is None:
85
+ css.load_from_data(style, -1)
86
+ else:
87
+ css.load_from_data(style.encode('utf-8'))
88
+ style_ctx = self.get_style_context()
89
+ style_ctx.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
90
+ style_ctx.add_class("matplotlib-canvas")
91
+
92
+ def destroy(self):
93
+ CloseEvent("close_event", self)._process()
94
+
95
+ def set_cursor(self, cursor):
96
+ # docstring inherited
97
+ self.set_cursor_from_name(_backend_gtk.mpl_to_gtk_cursor_name(cursor))
98
+
99
+ def _mpl_coords(self, xy=None):
100
+ """
101
+ Convert the *xy* position of a GTK event, or of the current cursor
102
+ position if *xy* is None, to Matplotlib coordinates.
103
+
104
+ GTK use logical pixels, but the figure is scaled to physical pixels for
105
+ rendering. Transform to physical pixels so that all of the down-stream
106
+ transforms work as expected.
107
+
108
+ Also, the origin is different and needs to be corrected.
109
+ """
110
+ if xy is None:
111
+ surface = self.get_native().get_surface()
112
+ is_over, x, y, mask = surface.get_device_position(
113
+ self.get_display().get_default_seat().get_pointer())
114
+ else:
115
+ x, y = xy
116
+ x = x * self.device_pixel_ratio
117
+ # flip y so y=0 is bottom of canvas
118
+ y = self.figure.bbox.height - y * self.device_pixel_ratio
119
+ return x, y
120
+
121
+ def scroll_event(self, controller, dx, dy):
122
+ MouseEvent(
123
+ "scroll_event", self, *self._mpl_coords(), step=dy,
124
+ modifiers=self._mpl_modifiers(controller),
125
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
126
+ )._process()
127
+ return True
128
+
129
+ def button_press_event(self, controller, n_press, x, y):
130
+ MouseEvent(
131
+ "button_press_event", self, *self._mpl_coords((x, y)),
132
+ controller.get_current_button(),
133
+ modifiers=self._mpl_modifiers(controller),
134
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
135
+ )._process()
136
+ self.grab_focus()
137
+
138
+ def button_release_event(self, controller, n_press, x, y):
139
+ MouseEvent(
140
+ "button_release_event", self, *self._mpl_coords((x, y)),
141
+ controller.get_current_button(),
142
+ modifiers=self._mpl_modifiers(controller),
143
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
144
+ )._process()
145
+
146
+ def key_press_event(self, controller, keyval, keycode, state):
147
+ KeyEvent(
148
+ "key_press_event", self, self._get_key(keyval, keycode, state),
149
+ *self._mpl_coords(),
150
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
151
+ )._process()
152
+ return True
153
+
154
+ def key_release_event(self, controller, keyval, keycode, state):
155
+ KeyEvent(
156
+ "key_release_event", self, self._get_key(keyval, keycode, state),
157
+ *self._mpl_coords(),
158
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
159
+ )._process()
160
+ return True
161
+
162
+ def motion_notify_event(self, controller, x, y):
163
+ MouseEvent(
164
+ "motion_notify_event", self, *self._mpl_coords((x, y)),
165
+ buttons=self._mpl_buttons(controller),
166
+ modifiers=self._mpl_modifiers(controller),
167
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
168
+ )._process()
169
+
170
+ def enter_notify_event(self, controller, x, y):
171
+ LocationEvent(
172
+ "figure_enter_event", self, *self._mpl_coords((x, y)),
173
+ modifiers=self._mpl_modifiers(),
174
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
175
+ )._process()
176
+
177
+ def leave_notify_event(self, controller):
178
+ LocationEvent(
179
+ "figure_leave_event", self, *self._mpl_coords(),
180
+ modifiers=self._mpl_modifiers(),
181
+ guiEvent=controller.get_current_event() if _GOBJECT_GE_3_47 else None,
182
+ )._process()
183
+
184
+ def resize_event(self, area, width, height):
185
+ self._update_device_pixel_ratio()
186
+ dpi = self.figure.dpi
187
+ winch = width * self.device_pixel_ratio / dpi
188
+ hinch = height * self.device_pixel_ratio / dpi
189
+ self.figure.set_size_inches(winch, hinch, forward=False)
190
+ ResizeEvent("resize_event", self)._process()
191
+ self.draw_idle()
192
+
193
+ def _mpl_buttons(self, controller):
194
+ # NOTE: This spews "Broken accounting of active state" warnings on
195
+ # right click on macOS.
196
+ surface = self.get_native().get_surface()
197
+ is_over, x, y, event_state = surface.get_device_position(
198
+ self.get_display().get_default_seat().get_pointer())
199
+ # NOTE: alternatively we could use
200
+ # event_state = controller.get_current_event_state()
201
+ # but for button_press/button_release this would report the state
202
+ # *prior* to the event rather than after it; the above reports the
203
+ # state *after* it.
204
+ mod_table = [
205
+ (MouseButton.LEFT, Gdk.ModifierType.BUTTON1_MASK),
206
+ (MouseButton.MIDDLE, Gdk.ModifierType.BUTTON2_MASK),
207
+ (MouseButton.RIGHT, Gdk.ModifierType.BUTTON3_MASK),
208
+ (MouseButton.BACK, Gdk.ModifierType.BUTTON4_MASK),
209
+ (MouseButton.FORWARD, Gdk.ModifierType.BUTTON5_MASK),
210
+ ]
211
+ return {name for name, mask in mod_table if event_state & mask}
212
+
213
+ def _mpl_modifiers(self, controller=None):
214
+ if controller is None:
215
+ surface = self.get_native().get_surface()
216
+ is_over, x, y, event_state = surface.get_device_position(
217
+ self.get_display().get_default_seat().get_pointer())
218
+ else:
219
+ event_state = controller.get_current_event_state()
220
+ mod_table = [
221
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK),
222
+ ("alt", Gdk.ModifierType.ALT_MASK),
223
+ ("shift", Gdk.ModifierType.SHIFT_MASK),
224
+ ("super", Gdk.ModifierType.SUPER_MASK),
225
+ ]
226
+ return [name for name, mask in mod_table if event_state & mask]
227
+
228
+ def _get_key(self, keyval, keycode, state):
229
+ unikey = chr(Gdk.keyval_to_unicode(keyval))
230
+ key = cbook._unikey_or_keysym_to_mplkey(
231
+ unikey,
232
+ Gdk.keyval_name(keyval))
233
+ modifiers = [
234
+ ("ctrl", Gdk.ModifierType.CONTROL_MASK, "control"),
235
+ ("alt", Gdk.ModifierType.ALT_MASK, "alt"),
236
+ ("shift", Gdk.ModifierType.SHIFT_MASK, "shift"),
237
+ ("super", Gdk.ModifierType.SUPER_MASK, "super"),
238
+ ]
239
+ mods = [
240
+ mod for mod, mask, mod_key in modifiers
241
+ if (mod_key != key and state & mask
242
+ and not (mod == "shift" and unikey.isprintable()))]
243
+ return "+".join([*mods, key])
244
+
245
+ def _realize_event(self, obj):
246
+ surface = self.get_native().get_surface()
247
+ surface.connect('notify::scale', self._update_device_pixel_ratio)
248
+ self._update_device_pixel_ratio()
249
+
250
+ def _update_device_pixel_ratio(self, *args, **kwargs):
251
+ # We need to be careful in cases with mixed resolution displays if
252
+ # device_pixel_ratio changes.
253
+ if _GTK_GE_4_12:
254
+ scale = self.get_native().get_surface().get_scale()
255
+ else:
256
+ scale = self.get_scale_factor()
257
+ assert scale is not None
258
+ if self._set_device_pixel_ratio(scale):
259
+ self.draw()
260
+
261
+ def _draw_rubberband(self, rect):
262
+ self._rubberband_rect = rect
263
+ # TODO: Only update the rubberband area.
264
+ self.queue_draw()
265
+
266
+ def _draw_func(self, drawing_area, ctx, width, height):
267
+ self.on_draw_event(self, ctx)
268
+ self._post_draw(self, ctx)
269
+
270
+ def _post_draw(self, widget, ctx):
271
+ if self._rubberband_rect is None:
272
+ return
273
+
274
+ lw = 1
275
+ dash = 3
276
+ x0, y0, w, h = (dim / self.device_pixel_ratio
277
+ for dim in self._rubberband_rect)
278
+ x1 = x0 + w
279
+ y1 = y0 + h
280
+
281
+ # Draw the lines from x0, y0 towards x1, y1 so that the
282
+ # dashes don't "jump" when moving the zoom box.
283
+ ctx.move_to(x0, y0)
284
+ ctx.line_to(x0, y1)
285
+ ctx.move_to(x0, y0)
286
+ ctx.line_to(x1, y0)
287
+ ctx.move_to(x0, y1)
288
+ ctx.line_to(x1, y1)
289
+ ctx.move_to(x1, y0)
290
+ ctx.line_to(x1, y1)
291
+
292
+ ctx.set_antialias(1)
293
+ ctx.set_line_width(lw)
294
+ ctx.set_dash((dash, dash), 0)
295
+ ctx.set_source_rgb(0, 0, 0)
296
+ ctx.stroke_preserve()
297
+
298
+ ctx.set_dash((dash, dash), dash)
299
+ ctx.set_source_rgb(1, 1, 1)
300
+ ctx.stroke()
301
+
302
+ def on_draw_event(self, widget, ctx):
303
+ # to be overwritten by GTK4Agg or GTK4Cairo
304
+ pass
305
+
306
+ def draw(self):
307
+ # docstring inherited
308
+ if self.is_drawable():
309
+ self.queue_draw()
310
+
311
+ def draw_idle(self):
312
+ # docstring inherited
313
+ if self._idle_draw_id != 0:
314
+ return
315
+ def idle_draw(*args):
316
+ try:
317
+ self.draw()
318
+ finally:
319
+ self._idle_draw_id = 0
320
+ return False
321
+ self._idle_draw_id = GLib.idle_add(idle_draw)
322
+
323
+ def flush_events(self):
324
+ # docstring inherited
325
+ context = GLib.MainContext.default()
326
+ while context.pending():
327
+ context.iteration(True)
328
+
329
+
330
+ class NavigationToolbar2GTK4(_NavigationToolbar2GTK, Gtk.Box):
331
+ def __init__(self, canvas):
332
+ Gtk.Box.__init__(self)
333
+
334
+ self.add_css_class('toolbar')
335
+
336
+ self._gtk_ids = {}
337
+ for text, tooltip_text, image_file, callback in self.toolitems:
338
+ if text is None:
339
+ self.append(Gtk.Separator())
340
+ continue
341
+ image = Gtk.Image.new_from_gicon(
342
+ Gio.Icon.new_for_string(
343
+ str(cbook._get_data_path('images',
344
+ f'{image_file}-symbolic.svg'))))
345
+ self._gtk_ids[text] = button = (
346
+ Gtk.ToggleButton() if callback in ['zoom', 'pan'] else
347
+ Gtk.Button())
348
+ button.set_child(image)
349
+ button.add_css_class('flat')
350
+ button.add_css_class('image-button')
351
+ # Save the handler id, so that we can block it as needed.
352
+ button._signal_handler = button.connect(
353
+ 'clicked', getattr(self, callback))
354
+ button.set_tooltip_text(tooltip_text)
355
+ self.append(button)
356
+
357
+ # This filler item ensures the toolbar is always at least two text
358
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
359
+ # over images because those use two-line messages which resize the
360
+ # toolbar.
361
+ label = Gtk.Label()
362
+ label.set_markup(
363
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
364
+ label.set_hexpand(True) # Push real message to the right.
365
+ self.append(label)
366
+
367
+ self.message = Gtk.Label()
368
+ self.message.set_justify(Gtk.Justification.RIGHT)
369
+ self.append(self.message)
370
+
371
+ _NavigationToolbar2GTK.__init__(self, canvas)
372
+
373
+ def save_figure(self, *args):
374
+ dialog = Gtk.FileChooserNative(
375
+ title='Save the figure',
376
+ transient_for=self.canvas.get_root(),
377
+ action=Gtk.FileChooserAction.SAVE,
378
+ modal=True)
379
+ self._save_dialog = dialog # Must keep a reference.
380
+
381
+ ff = Gtk.FileFilter()
382
+ ff.set_name('All files')
383
+ ff.add_pattern('*')
384
+ dialog.add_filter(ff)
385
+ dialog.set_filter(ff)
386
+
387
+ formats = []
388
+ default_format = None
389
+ for i, (name, fmts) in enumerate(
390
+ self.canvas.get_supported_filetypes_grouped().items()):
391
+ ff = Gtk.FileFilter()
392
+ ff.set_name(name)
393
+ for fmt in fmts:
394
+ ff.add_pattern(f'*.{fmt}')
395
+ dialog.add_filter(ff)
396
+ formats.append(name)
397
+ if self.canvas.get_default_filetype() in fmts:
398
+ default_format = i
399
+ # Setting the choice doesn't always work, so make sure the default
400
+ # format is first.
401
+ formats = [formats[default_format], *formats[:default_format],
402
+ *formats[default_format+1:]]
403
+ dialog.add_choice('format', 'File format', formats, formats)
404
+ dialog.set_choice('format', formats[0])
405
+
406
+ dialog.set_current_folder(Gio.File.new_for_path(
407
+ os.path.expanduser(mpl.rcParams['savefig.directory'])))
408
+ dialog.set_current_name(self.canvas.get_default_filename())
409
+
410
+ @functools.partial(dialog.connect, 'response')
411
+ def on_response(dialog, response):
412
+ file = dialog.get_file()
413
+ fmt = dialog.get_choice('format')
414
+ fmt = self.canvas.get_supported_filetypes_grouped()[fmt][0]
415
+ dialog.destroy()
416
+ self._save_dialog = None
417
+ if response != Gtk.ResponseType.ACCEPT:
418
+ return
419
+ # Save dir for next time, unless empty str (which means use cwd).
420
+ if mpl.rcParams['savefig.directory']:
421
+ parent = file.get_parent()
422
+ mpl.rcParams['savefig.directory'] = parent.get_path()
423
+ try:
424
+ self.canvas.figure.savefig(file.get_path(), format=fmt)
425
+ except Exception as e:
426
+ msg = Gtk.MessageDialog(
427
+ transient_for=self.canvas.get_root(),
428
+ message_type=Gtk.MessageType.ERROR,
429
+ buttons=Gtk.ButtonsType.OK, modal=True,
430
+ text=str(e))
431
+ msg.show()
432
+
433
+ dialog.show()
434
+ return self.UNKNOWN_SAVED_STATUS
435
+
436
+
437
+ class ToolbarGTK4(ToolContainerBase, Gtk.Box):
438
+ _icon_extension = '-symbolic.svg'
439
+
440
+ def __init__(self, toolmanager):
441
+ ToolContainerBase.__init__(self, toolmanager)
442
+ Gtk.Box.__init__(self)
443
+ self.set_property('orientation', Gtk.Orientation.HORIZONTAL)
444
+
445
+ # Tool items are created later, but must appear before the message.
446
+ self._tool_box = Gtk.Box()
447
+ self.append(self._tool_box)
448
+ self._groups = {}
449
+ self._toolitems = {}
450
+
451
+ # This filler item ensures the toolbar is always at least two text
452
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
453
+ # over images because those use two-line messages which resize the
454
+ # toolbar.
455
+ label = Gtk.Label()
456
+ label.set_markup(
457
+ '<small>\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}</small>')
458
+ label.set_hexpand(True) # Push real message to the right.
459
+ self.append(label)
460
+
461
+ self._message = Gtk.Label()
462
+ self._message.set_justify(Gtk.Justification.RIGHT)
463
+ self.append(self._message)
464
+
465
+ def add_toolitem(self, name, group, position, image_file, description,
466
+ toggle):
467
+ if toggle:
468
+ button = Gtk.ToggleButton()
469
+ else:
470
+ button = Gtk.Button()
471
+ button.set_label(name)
472
+ button.add_css_class('flat')
473
+
474
+ if image_file is not None:
475
+ image = Gtk.Image.new_from_gicon(
476
+ Gio.Icon.new_for_string(image_file))
477
+ button.set_child(image)
478
+ button.add_css_class('image-button')
479
+
480
+ if position is None:
481
+ position = -1
482
+
483
+ self._add_button(button, group, position)
484
+ signal = button.connect('clicked', self._call_tool, name)
485
+ button.set_tooltip_text(description)
486
+ self._toolitems.setdefault(name, [])
487
+ self._toolitems[name].append((button, signal))
488
+
489
+ def _find_child_at_position(self, group, position):
490
+ children = [None]
491
+ child = self._groups[group].get_first_child()
492
+ while child is not None:
493
+ children.append(child)
494
+ child = child.get_next_sibling()
495
+ return children[position]
496
+
497
+ def _add_button(self, button, group, position):
498
+ if group not in self._groups:
499
+ if self._groups:
500
+ self._add_separator()
501
+ group_box = Gtk.Box()
502
+ self._tool_box.append(group_box)
503
+ self._groups[group] = group_box
504
+ self._groups[group].insert_child_after(
505
+ button, self._find_child_at_position(group, position))
506
+
507
+ def _call_tool(self, btn, name):
508
+ self.trigger_tool(name)
509
+
510
+ def toggle_toolitem(self, name, toggled):
511
+ if name not in self._toolitems:
512
+ return
513
+ for toolitem, signal in self._toolitems[name]:
514
+ toolitem.handler_block(signal)
515
+ toolitem.set_active(toggled)
516
+ toolitem.handler_unblock(signal)
517
+
518
+ def remove_toolitem(self, name):
519
+ for toolitem, _signal in self._toolitems.pop(name, []):
520
+ for group in self._groups:
521
+ if toolitem in self._groups[group]:
522
+ self._groups[group].remove(toolitem)
523
+
524
+ def _add_separator(self):
525
+ sep = Gtk.Separator()
526
+ sep.set_property("orientation", Gtk.Orientation.VERTICAL)
527
+ self._tool_box.append(sep)
528
+
529
+ def set_message(self, s):
530
+ self._message.set_label(s)
531
+
532
+
533
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
534
+ class SaveFigureGTK4(backend_tools.SaveFigureBase):
535
+ def trigger(self, *args, **kwargs):
536
+ NavigationToolbar2GTK4.save_figure(
537
+ self._make_classic_style_pseudo_toolbar())
538
+
539
+
540
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
541
+ class HelpGTK4(backend_tools.ToolHelpBase):
542
+ def _normalize_shortcut(self, key):
543
+ """
544
+ Convert Matplotlib key presses to GTK+ accelerator identifiers.
545
+
546
+ Related to `FigureCanvasGTK4._get_key`.
547
+ """
548
+ special = {
549
+ 'backspace': 'BackSpace',
550
+ 'pagedown': 'Page_Down',
551
+ 'pageup': 'Page_Up',
552
+ 'scroll_lock': 'Scroll_Lock',
553
+ }
554
+
555
+ parts = key.split('+')
556
+ mods = ['<' + mod + '>' for mod in parts[:-1]]
557
+ key = parts[-1]
558
+
559
+ if key in special:
560
+ key = special[key]
561
+ elif len(key) > 1:
562
+ key = key.capitalize()
563
+ elif key.isupper():
564
+ mods += ['<shift>']
565
+
566
+ return ''.join(mods) + key
567
+
568
+ def _is_valid_shortcut(self, key):
569
+ """
570
+ Check for a valid shortcut to be displayed.
571
+
572
+ - GTK will never send 'cmd+' (see `FigureCanvasGTK4._get_key`).
573
+ - The shortcut window only shows keyboard shortcuts, not mouse buttons.
574
+ """
575
+ return 'cmd+' not in key and not key.startswith('MouseButton.')
576
+
577
+ def trigger(self, *args):
578
+ section = Gtk.ShortcutsSection()
579
+
580
+ for name, tool in sorted(self.toolmanager.tools.items()):
581
+ if not tool.description:
582
+ continue
583
+
584
+ # Putting everything in a separate group allows GTK to
585
+ # automatically split them into separate columns/pages, which is
586
+ # useful because we have lots of shortcuts, some with many keys
587
+ # that are very wide.
588
+ group = Gtk.ShortcutsGroup()
589
+ section.append(group)
590
+ # A hack to remove the title since we have no group naming.
591
+ child = group.get_first_child()
592
+ while child is not None:
593
+ child.set_visible(False)
594
+ child = child.get_next_sibling()
595
+
596
+ shortcut = Gtk.ShortcutsShortcut(
597
+ accelerator=' '.join(
598
+ self._normalize_shortcut(key)
599
+ for key in self.toolmanager.get_tool_keymap(name)
600
+ if self._is_valid_shortcut(key)),
601
+ title=tool.name,
602
+ subtitle=tool.description)
603
+ group.append(shortcut)
604
+
605
+ window = Gtk.ShortcutsWindow(
606
+ title='Help',
607
+ modal=True,
608
+ transient_for=self._figure.canvas.get_root())
609
+ window.set_child(section)
610
+
611
+ window.show()
612
+
613
+
614
+ @backend_tools._register_tool_class(FigureCanvasGTK4)
615
+ class ToolCopyToClipboardGTK4(backend_tools.ToolCopyToClipboardBase):
616
+ def trigger(self, *args, **kwargs):
617
+ with io.BytesIO() as f:
618
+ self.canvas.print_rgba(f)
619
+ w, h = self.canvas.get_width_height()
620
+ pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),
621
+ GdkPixbuf.Colorspace.RGB, True,
622
+ 8, w, h, w*4)
623
+ clipboard = self.canvas.get_clipboard()
624
+ clipboard.set(pb)
625
+
626
+
627
+ backend_tools._register_tool_class(
628
+ FigureCanvasGTK4, _backend_gtk.ConfigureSubplotsGTK)
629
+ backend_tools._register_tool_class(
630
+ FigureCanvasGTK4, _backend_gtk.RubberbandGTK)
631
+ Toolbar = ToolbarGTK4
632
+
633
+
634
+ class FigureManagerGTK4(_FigureManagerGTK):
635
+ _toolbar2_class = NavigationToolbar2GTK4
636
+ _toolmanager_toolbar_class = ToolbarGTK4
637
+
638
+
639
+ @_BackendGTK.export
640
+ class _BackendGTK4(_BackendGTK):
641
+ FigureCanvas = FigureCanvasGTK4
642
+ FigureManager = FigureManagerGTK4
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_gtk4agg.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from .. import cbook
4
+ from . import backend_agg, backend_gtk4
5
+ from .backend_gtk4 import GLib, Gtk, _BackendGTK4
6
+
7
+ import cairo # Presence of cairo is already checked by _backend_gtk.
8
+
9
+
10
+ class FigureCanvasGTK4Agg(backend_agg.FigureCanvasAgg,
11
+ backend_gtk4.FigureCanvasGTK4):
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
+ scale = self.device_pixel_ratio
20
+ allocation = self.get_allocation()
21
+
22
+ Gtk.render_background(
23
+ self.get_style_context(), ctx,
24
+ allocation.x, allocation.y,
25
+ allocation.width, allocation.height)
26
+
27
+ buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(
28
+ np.asarray(self.get_renderer().buffer_rgba()))
29
+ height, width, _ = buf.shape
30
+ image = cairo.ImageSurface.create_for_data(
31
+ buf.ravel().data, cairo.FORMAT_ARGB32, width, height)
32
+ image.set_device_scale(scale, scale)
33
+ ctx.set_source_surface(image, 0, 0)
34
+ ctx.paint()
35
+
36
+ return False
37
+
38
+
39
+ @_BackendGTK4.export
40
+ class _BackendGTK4Agg(_BackendGTK4):
41
+ FigureCanvas = FigureCanvasGTK4Agg
workspace/outputs/audit_venv/lib/python3.11/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
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_macosx.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import matplotlib as mpl
4
+ from matplotlib import _api, cbook
5
+ from matplotlib._pylab_helpers import Gcf
6
+ from . import _macosx
7
+ from .backend_agg import FigureCanvasAgg
8
+ from matplotlib.backend_bases import (
9
+ _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
10
+ ResizeEvent, TimerBase, _allow_interrupt)
11
+
12
+
13
+ class TimerMac(_macosx.Timer, TimerBase):
14
+ """Subclass of `.TimerBase` using CFRunLoop timer events."""
15
+ # completely implemented at the C-level (in _macosx.Timer)
16
+
17
+
18
+ def _allow_interrupt_macos():
19
+ """A context manager that allows terminating a plot by sending a SIGINT."""
20
+ return _allow_interrupt(
21
+ lambda rsock: _macosx.wake_on_fd_write(rsock.fileno()), _macosx.stop)
22
+
23
+
24
+ class FigureCanvasMac(FigureCanvasAgg, _macosx.FigureCanvas, FigureCanvasBase):
25
+ # docstring inherited
26
+
27
+ # Ideally this class would be `class FCMacAgg(FCAgg, FCMac)`
28
+ # (FC=FigureCanvas) where FCMac would be an ObjC-implemented mac-specific
29
+ # class also inheriting from FCBase (this is the approach with other GUI
30
+ # toolkits). However, writing an extension type inheriting from a Python
31
+ # base class is slightly tricky (the extension type must be a heap type),
32
+ # and we can just as well lift the FCBase base up one level, keeping it *at
33
+ # the end* to have the right method resolution order.
34
+
35
+ # Events such as button presses, mouse movements, and key presses are
36
+ # handled in C and events (MouseEvent, etc.) are triggered from there.
37
+
38
+ required_interactive_framework = "macosx"
39
+ _timer_cls = TimerMac
40
+ manager_class = _api.classproperty(lambda cls: FigureManagerMac)
41
+
42
+ def __init__(self, figure):
43
+ super().__init__(figure=figure)
44
+ self._draw_pending = False
45
+ self._is_drawing = False
46
+ # Keep track of the timers that are alive
47
+ self._timers = set()
48
+
49
+ def draw(self):
50
+ """Render the figure and update the macosx canvas."""
51
+ # The renderer draw is done here; delaying causes problems with code
52
+ # that uses the result of the draw() to update plot elements.
53
+ if self._is_drawing:
54
+ return
55
+ with cbook._setattr_cm(self, _is_drawing=True):
56
+ super().draw()
57
+ self.update()
58
+
59
+ def draw_idle(self):
60
+ # docstring inherited
61
+ if not (getattr(self, '_draw_pending', False) or
62
+ getattr(self, '_is_drawing', False)):
63
+ self._draw_pending = True
64
+ # Add a singleshot timer to the eventloop that will call back
65
+ # into the Python method _draw_idle to take care of the draw
66
+ self._single_shot_timer(self._draw_idle)
67
+
68
+ def _single_shot_timer(self, callback):
69
+ """Add a single shot timer with the given callback"""
70
+ def callback_func(callback, timer):
71
+ callback()
72
+ self._timers.remove(timer)
73
+ timer = self.new_timer(interval=0)
74
+ timer.single_shot = True
75
+ timer.add_callback(callback_func, callback, timer)
76
+ self._timers.add(timer)
77
+ timer.start()
78
+
79
+ def _draw_idle(self):
80
+ """
81
+ Draw method for singleshot timer
82
+
83
+ This draw method can be added to a singleshot timer, which can
84
+ accumulate draws while the eventloop is spinning. This method will
85
+ then only draw the first time and short-circuit the others.
86
+ """
87
+ with self._idle_draw_cntx():
88
+ if not self._draw_pending:
89
+ # Short-circuit because our draw request has already been
90
+ # taken care of
91
+ return
92
+ self._draw_pending = False
93
+ self.draw()
94
+
95
+ def blit(self, bbox=None):
96
+ # docstring inherited
97
+ super().blit(bbox)
98
+ self.update()
99
+
100
+ def resize(self, width, height):
101
+ # Size from macOS is logical pixels, dpi is physical.
102
+ scale = self.figure.dpi / self.device_pixel_ratio
103
+ width /= scale
104
+ height /= scale
105
+ self.figure.set_size_inches(width, height, forward=False)
106
+ ResizeEvent("resize_event", self)._process()
107
+ self.draw_idle()
108
+
109
+ def start_event_loop(self, timeout=0):
110
+ # docstring inherited
111
+ # Set up a SIGINT handler to allow terminating a plot via CTRL-C.
112
+ with _allow_interrupt_macos():
113
+ self._start_event_loop(timeout=timeout) # Forward to ObjC implementation.
114
+
115
+
116
+ class NavigationToolbar2Mac(_macosx.NavigationToolbar2, NavigationToolbar2):
117
+
118
+ def __init__(self, canvas):
119
+ data_path = cbook._get_data_path('images')
120
+ _, tooltips, image_names, _ = zip(*NavigationToolbar2.toolitems)
121
+ _macosx.NavigationToolbar2.__init__(
122
+ self, canvas,
123
+ tuple(str(data_path / image_name) + ".pdf"
124
+ for image_name in image_names if image_name is not None),
125
+ tuple(tooltip for tooltip in tooltips if tooltip is not None))
126
+ NavigationToolbar2.__init__(self, canvas)
127
+
128
+ def draw_rubberband(self, event, x0, y0, x1, y1):
129
+ self.canvas.set_rubberband(int(x0), int(y0), int(x1), int(y1))
130
+
131
+ def remove_rubberband(self):
132
+ self.canvas.remove_rubberband()
133
+
134
+ def save_figure(self, *args):
135
+ directory = os.path.expanduser(mpl.rcParams['savefig.directory'])
136
+ filename = _macosx.choose_save_file('Save the figure',
137
+ directory,
138
+ self.canvas.get_default_filename())
139
+ if filename is None: # Cancel
140
+ return
141
+ # Save dir for next time, unless empty str (which means use cwd).
142
+ if mpl.rcParams['savefig.directory']:
143
+ mpl.rcParams['savefig.directory'] = os.path.dirname(filename)
144
+ self.canvas.figure.savefig(filename)
145
+ return filename
146
+
147
+
148
+ class FigureManagerMac(_macosx.FigureManager, FigureManagerBase):
149
+ _toolbar2_class = NavigationToolbar2Mac
150
+
151
+ def __init__(self, canvas, num):
152
+ self._shown = False
153
+ _macosx.FigureManager.__init__(self, canvas)
154
+ icon_path = str(cbook._get_data_path('images/matplotlib.pdf'))
155
+ _macosx.FigureManager.set_icon(icon_path)
156
+ FigureManagerBase.__init__(self, canvas, num)
157
+ self._set_window_mode(mpl.rcParams["macosx.window_mode"])
158
+ if self.toolbar is not None:
159
+ self.toolbar.update()
160
+ if mpl.is_interactive():
161
+ self.show()
162
+ self.canvas.draw_idle()
163
+
164
+ def _close_button_pressed(self):
165
+ Gcf.destroy(self)
166
+ self.canvas.flush_events()
167
+
168
+ def destroy(self):
169
+ # We need to clear any pending timers that never fired, otherwise
170
+ # we get a memory leak from the timer callbacks holding a reference
171
+ while self.canvas._timers:
172
+ timer = self.canvas._timers.pop()
173
+ timer.stop()
174
+ super().destroy()
175
+
176
+ @classmethod
177
+ def start_main_loop(cls):
178
+ # Set up a SIGINT handler to allow terminating a plot via CTRL-C.
179
+ with _allow_interrupt_macos():
180
+ _macosx.show()
181
+
182
+ def show(self):
183
+ if self.canvas.figure.stale:
184
+ self.canvas.draw_idle()
185
+ if not self._shown:
186
+ self._show()
187
+ self._shown = True
188
+ if mpl.rcParams["figure.raise_window"]:
189
+ self._raise()
190
+
191
+
192
+ @_Backend.export
193
+ class _BackendMac(_Backend):
194
+ FigureCanvas = FigureCanvasMac
195
+ FigureManager = FigureManagerMac
196
+ mainloop = FigureManagerMac.start_main_loop
workspace/outputs/audit_venv/lib/python3.11/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 : float
25
+ The width of the canvas in logical units
26
+ height : float
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
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_nbagg.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive figures in the IPython notebook."""
2
+ # Note: There is a notebook in
3
+ # lib/matplotlib/backends/web_backend/nbagg_uat.ipynb to help verify
4
+ # that changes made maintain expected behaviour.
5
+
6
+ from base64 import b64encode
7
+ import io
8
+ import json
9
+ import pathlib
10
+ import uuid
11
+
12
+ from ipykernel.comm import Comm
13
+ from IPython.display import display, Javascript, HTML
14
+
15
+ from matplotlib import is_interactive
16
+ from matplotlib._pylab_helpers import Gcf
17
+ from matplotlib.backend_bases import _Backend, CloseEvent, NavigationToolbar2
18
+ from .backend_webagg_core import (
19
+ FigureCanvasWebAggCore, FigureManagerWebAgg, NavigationToolbar2WebAgg)
20
+ from .backend_webagg_core import ( # noqa: F401 # pylint: disable=W0611
21
+ TimerTornado, TimerAsyncio)
22
+
23
+
24
+ def connection_info():
25
+ """
26
+ Return a string showing the figure and connection status for the backend.
27
+
28
+ This is intended as a diagnostic tool, and not for general use.
29
+ """
30
+ result = [
31
+ '{fig} - {socket}'.format(
32
+ fig=(manager.canvas.figure.get_label()
33
+ or f"Figure {manager.num}"),
34
+ socket=manager.web_sockets)
35
+ for manager in Gcf.get_all_fig_managers()
36
+ ]
37
+ if not is_interactive():
38
+ result.append(f'Figures pending show: {len(Gcf.figs)}')
39
+ return '\n'.join(result)
40
+
41
+
42
+ _FONT_AWESOME_CLASSES = { # font-awesome 4 names
43
+ 'home': 'fa fa-home',
44
+ 'back': 'fa fa-arrow-left',
45
+ 'forward': 'fa fa-arrow-right',
46
+ 'zoom_to_rect': 'fa fa-square-o',
47
+ 'move': 'fa fa-arrows',
48
+ 'download': 'fa fa-floppy-o',
49
+ None: None
50
+ }
51
+
52
+
53
+ class NavigationIPy(NavigationToolbar2WebAgg):
54
+
55
+ # Use the standard toolbar items + download button
56
+ toolitems = [(text, tooltip_text,
57
+ _FONT_AWESOME_CLASSES[image_file], name_of_method)
58
+ for text, tooltip_text, image_file, name_of_method
59
+ in (NavigationToolbar2.toolitems +
60
+ (('Download', 'Download plot', 'download', 'download'),))
61
+ if image_file in _FONT_AWESOME_CLASSES]
62
+
63
+
64
+ class FigureManagerNbAgg(FigureManagerWebAgg):
65
+ _toolbar2_class = ToolbarCls = NavigationIPy
66
+
67
+ def __init__(self, canvas, num):
68
+ self._shown = False
69
+ super().__init__(canvas, num)
70
+
71
+ @classmethod
72
+ def create_with_canvas(cls, canvas_class, figure, num):
73
+ canvas = canvas_class(figure)
74
+ manager = cls(canvas, num)
75
+ if is_interactive():
76
+ manager.show()
77
+ canvas.draw_idle()
78
+
79
+ def destroy(event):
80
+ canvas.mpl_disconnect(cid)
81
+ Gcf.destroy(manager)
82
+
83
+ cid = canvas.mpl_connect('close_event', destroy)
84
+ return manager
85
+
86
+ def display_js(self):
87
+ # XXX How to do this just once? It has to deal with multiple
88
+ # browser instances using the same kernel (require.js - but the
89
+ # file isn't static?).
90
+ display(Javascript(FigureManagerNbAgg.get_javascript()))
91
+
92
+ def show(self):
93
+ if not self._shown:
94
+ self.display_js()
95
+ self._create_comm()
96
+ else:
97
+ self.canvas.draw_idle()
98
+ self._shown = True
99
+ # plt.figure adds an event which makes the figure in focus the active
100
+ # one. Disable this behaviour, as it results in figures being put as
101
+ # the active figure after they have been shown, even in non-interactive
102
+ # mode.
103
+ if hasattr(self, '_cidgcf'):
104
+ self.canvas.mpl_disconnect(self._cidgcf)
105
+ if not is_interactive():
106
+ from matplotlib._pylab_helpers import Gcf
107
+ Gcf.figs.pop(self.num, None)
108
+
109
+ def reshow(self):
110
+ """
111
+ A special method to re-show the figure in the notebook.
112
+
113
+ """
114
+ self._shown = False
115
+ self.show()
116
+
117
+ @property
118
+ def connected(self):
119
+ return bool(self.web_sockets)
120
+
121
+ @classmethod
122
+ def get_javascript(cls, stream=None):
123
+ if stream is None:
124
+ output = io.StringIO()
125
+ else:
126
+ output = stream
127
+ super().get_javascript(stream=output)
128
+ output.write((pathlib.Path(__file__).parent
129
+ / "web_backend/js/nbagg_mpl.js")
130
+ .read_text(encoding="utf-8"))
131
+ if stream is None:
132
+ return output.getvalue()
133
+
134
+ def _create_comm(self):
135
+ comm = CommSocket(self)
136
+ self.add_web_socket(comm)
137
+ return comm
138
+
139
+ def destroy(self):
140
+ self._send_event('close')
141
+ # need to copy comms as callbacks will modify this list
142
+ for comm in list(self.web_sockets):
143
+ comm.on_close()
144
+ self.clearup_closed()
145
+
146
+ def clearup_closed(self):
147
+ """Clear up any closed Comms."""
148
+ self.web_sockets = {socket for socket in self.web_sockets
149
+ if socket.is_open()}
150
+
151
+ if len(self.web_sockets) == 0:
152
+ CloseEvent("close_event", self.canvas)._process()
153
+
154
+ def remove_comm(self, comm_id):
155
+ self.web_sockets = {socket for socket in self.web_sockets
156
+ if socket.comm.comm_id != comm_id}
157
+
158
+
159
+ class FigureCanvasNbAgg(FigureCanvasWebAggCore):
160
+ manager_class = FigureManagerNbAgg
161
+
162
+
163
+ class CommSocket:
164
+ """
165
+ Manages the Comm connection between IPython and the browser (client).
166
+
167
+ Comms are 2 way, with the CommSocket being able to publish a message
168
+ via the send_json method, and handle a message with on_message. On the
169
+ JS side figure.send_message and figure.ws.onmessage do the sending and
170
+ receiving respectively.
171
+
172
+ """
173
+ def __init__(self, manager):
174
+ self.supports_binary = None
175
+ self.manager = manager
176
+ self.uuid = str(uuid.uuid4())
177
+ # Publish an output area with a unique ID. The javascript can then
178
+ # hook into this area.
179
+ display(HTML("<div id=%r></div>" % self.uuid))
180
+ try:
181
+ self.comm = Comm('matplotlib', data={'id': self.uuid})
182
+ except AttributeError as err:
183
+ raise RuntimeError('Unable to create an IPython notebook Comm '
184
+ 'instance. Are you in the IPython '
185
+ 'notebook?') from err
186
+ self.comm.on_msg(self.on_message)
187
+
188
+ manager = self.manager
189
+ self._ext_close = False
190
+
191
+ def _on_close(close_message):
192
+ self._ext_close = True
193
+ manager.remove_comm(close_message['content']['comm_id'])
194
+ manager.clearup_closed()
195
+
196
+ self.comm.on_close(_on_close)
197
+
198
+ def is_open(self):
199
+ return not (self._ext_close or self.comm._closed)
200
+
201
+ def on_close(self):
202
+ # When the socket is closed, deregister the websocket with
203
+ # the FigureManager.
204
+ if self.is_open():
205
+ try:
206
+ self.comm.close()
207
+ except KeyError:
208
+ # apparently already cleaned it up?
209
+ pass
210
+
211
+ def send_json(self, content):
212
+ self.comm.send({'data': json.dumps(content)})
213
+
214
+ def send_binary(self, blob):
215
+ if self.supports_binary:
216
+ self.comm.send({'blob': 'image/png'}, buffers=[blob])
217
+ else:
218
+ # The comm is ASCII, so we send the image in base64 encoded data
219
+ # URL form.
220
+ data = b64encode(blob).decode('ascii')
221
+ data_uri = f"data:image/png;base64,{data}"
222
+ self.comm.send({'data': data_uri})
223
+
224
+ def on_message(self, message):
225
+ # The 'supports_binary' message is relevant to the
226
+ # websocket itself. The other messages get passed along
227
+ # to matplotlib as-is.
228
+
229
+ # Every message has a "type" and a "figure_id".
230
+ message = json.loads(message['content']['data'])
231
+ if message['type'] == 'closing':
232
+ self.on_close()
233
+ self.manager.clearup_closed()
234
+ elif message['type'] == 'supports_binary':
235
+ self.supports_binary = message['value']
236
+ else:
237
+ self.manager.handle_json(message)
238
+
239
+
240
+ @_Backend.export
241
+ class _BackendNbAgg(_Backend):
242
+ FigureCanvas = FigureCanvasNbAgg
243
+ FigureManager = FigureManagerNbAgg
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_pdf.py ADDED
The diff for this file is too large to render. See raw diff
 
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py ADDED
@@ -0,0 +1,1010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ import datetime
3
+ import functools
4
+ from io import BytesIO
5
+ import logging
6
+ import math
7
+ import os
8
+ import pathlib
9
+ import shutil
10
+ import subprocess
11
+ from tempfile import TemporaryDirectory
12
+ import weakref
13
+
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
+ )
21
+ from matplotlib.backends.backend_mixed import MixedModeRenderer
22
+ from matplotlib.backends.backend_pdf import (
23
+ _create_pdf_info_dict, _datetime_to_pdf)
24
+ from matplotlib.path import Path
25
+ from matplotlib.figure import Figure
26
+ from matplotlib.font_manager import FontProperties
27
+ from matplotlib._pylab_helpers import Gcf
28
+
29
+ _log = logging.getLogger(__name__)
30
+
31
+
32
+ _DOCUMENTCLASS = r"\documentclass{article}"
33
+
34
+
35
+ # Note: When formatting floating point values, it is important to use the
36
+ # %f/{:f} format rather than %s/{} to avoid triggering scientific notation,
37
+ # which is not recognized by TeX.
38
+
39
+ def _get_preamble():
40
+ """Prepare a LaTeX preamble based on the rcParams configuration."""
41
+ font_size_pt = FontProperties(
42
+ size=mpl.rcParams["font.size"]
43
+ ).get_size_in_points()
44
+ return "\n".join([
45
+ # Remove Matplotlib's custom command \mathdefault. (Not using
46
+ # \mathnormal instead since this looks odd with Computer Modern.)
47
+ r"\def\mathdefault#1{#1}",
48
+ # Use displaystyle for all math.
49
+ r"\everymath=\expandafter{\the\everymath\displaystyle}",
50
+ # Set up font sizes to match font.size setting.
51
+ # If present, use the KOMA package scrextend to adjust the standard
52
+ # LaTeX font commands (\tiny, ..., \normalsize, ..., \Huge) accordingly.
53
+ # Otherwise, only set \normalsize, manually.
54
+ r"\IfFileExists{scrextend.sty}{",
55
+ r" \usepackage[fontsize=%fpt]{scrextend}" % font_size_pt,
56
+ r"}{",
57
+ r" \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}"
58
+ % (font_size_pt, 1.2 * font_size_pt),
59
+ r" \normalsize",
60
+ r"}",
61
+ # Allow pgf.preamble to override the above definitions.
62
+ mpl.rcParams["pgf.preamble"],
63
+ *([
64
+ r"\ifdefined\pdftexversion\else % non-pdftex case.",
65
+ r" \usepackage{fontspec}",
66
+ ] + [
67
+ r" \%s{%s}[Path=\detokenize{%s/}]"
68
+ % (command, path.name, path.parent.as_posix())
69
+ for command, path in zip(
70
+ ["setmainfont", "setsansfont", "setmonofont"],
71
+ [pathlib.Path(fm.findfont(family))
72
+ for family in ["serif", "sans\\-serif", "monospace"]]
73
+ )
74
+ ] + [r"\fi"] if mpl.rcParams["pgf.rcfonts"] else []),
75
+ # Documented as "must come last".
76
+ mpl.texmanager._usepackage_if_not_loaded("underscore", option="strings"),
77
+ ])
78
+
79
+
80
+ # It's better to use only one unit for all coordinates, since the
81
+ # arithmetic in latex seems to produce inaccurate conversions.
82
+ latex_pt_to_in = 1. / 72.27
83
+ latex_in_to_pt = 1. / latex_pt_to_in
84
+ mpl_pt_to_in = 1. / 72.
85
+ mpl_in_to_pt = 1. / mpl_pt_to_in
86
+
87
+
88
+ def _tex_escape(text):
89
+ r"""
90
+ Do some necessary and/or useful substitutions for texts to be included in
91
+ LaTeX documents.
92
+ """
93
+ return text.replace("\N{MINUS SIGN}", r"\ensuremath{-}")
94
+
95
+
96
+ def _writeln(fh, line):
97
+ # Ending lines with a % prevents TeX from inserting spurious spaces
98
+ # (https://tex.stackexchange.com/questions/7453).
99
+ fh.write(line)
100
+ fh.write("%\n")
101
+
102
+
103
+ def _escape_and_apply_props(s, prop):
104
+ """
105
+ Generate a TeX string that renders string *s* with font properties *prop*,
106
+ also applying any required escapes to *s*.
107
+ """
108
+ commands = []
109
+
110
+ families = {"serif": r"\rmfamily", "sans": r"\sffamily",
111
+ "sans-serif": r"\sffamily", "monospace": r"\ttfamily"}
112
+ family = prop.get_family()[0]
113
+ if family in families:
114
+ commands.append(families[family])
115
+ elif not mpl.rcParams["pgf.rcfonts"]:
116
+ commands.append(r"\fontfamily{\familydefault}")
117
+ elif any(font.name == family for font in fm.fontManager.ttflist):
118
+ commands.append(
119
+ r"\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fi" % family)
120
+ else:
121
+ _log.warning("Ignoring unknown font: %s", family)
122
+
123
+ size = prop.get_size_in_points()
124
+ commands.append(r"\fontsize{%f}{%f}" % (size, size * 1.2))
125
+
126
+ styles = {"normal": r"", "italic": r"\itshape", "oblique": r"\slshape"}
127
+ commands.append(styles[prop.get_style()])
128
+
129
+ boldstyles = ["semibold", "demibold", "demi", "bold", "heavy",
130
+ "extra bold", "black"]
131
+ if prop.get_weight() in boldstyles:
132
+ commands.append(r"\bfseries")
133
+
134
+ commands.append(r"\selectfont")
135
+ return (
136
+ "{"
137
+ + "".join(commands)
138
+ + r"\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}"
139
+ # It should normally be enough to set the catcode of % to 12 ("normal
140
+ # character"); this works on TeXLive 2021 but not on 2018, so we just
141
+ # make it active too.
142
+ + r"\catcode`\%=\active\def%{\%}"
143
+ + _tex_escape(s)
144
+ + "}"
145
+ )
146
+
147
+
148
+ def _metadata_to_str(key, value):
149
+ """Convert metadata key/value to a form that hyperref accepts."""
150
+ if isinstance(value, datetime.datetime):
151
+ value = _datetime_to_pdf(value)
152
+ elif key == 'Trapped':
153
+ value = value.name.decode('ascii')
154
+ else:
155
+ value = str(value)
156
+ return f'{key}={{{value}}}'
157
+
158
+
159
+ def make_pdf_to_png_converter():
160
+ """Return a function that converts a pdf file to a png file."""
161
+ try:
162
+ mpl._get_executable_info("pdftocairo")
163
+ except mpl.ExecutableNotFoundError:
164
+ pass
165
+ else:
166
+ return lambda pdffile, pngfile, dpi: subprocess.check_output(
167
+ ["pdftocairo", "-singlefile", "-transp", "-png", "-r", "%d" % dpi,
168
+ pdffile, os.path.splitext(pngfile)[0]],
169
+ stderr=subprocess.STDOUT)
170
+ try:
171
+ gs_info = mpl._get_executable_info("gs")
172
+ except mpl.ExecutableNotFoundError:
173
+ pass
174
+ else:
175
+ return lambda pdffile, pngfile, dpi: subprocess.check_output(
176
+ [gs_info.executable,
177
+ '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT',
178
+ '-dUseCIEColor', '-dTextAlphaBits=4',
179
+ '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE',
180
+ '-sDEVICE=pngalpha', '-sOutputFile=%s' % pngfile,
181
+ '-r%d' % dpi, pdffile],
182
+ stderr=subprocess.STDOUT)
183
+ raise RuntimeError("No suitable pdf to png renderer found.")
184
+
185
+
186
+ class LatexError(Exception):
187
+ def __init__(self, message, latex_output=""):
188
+ super().__init__(message)
189
+ self.latex_output = latex_output
190
+
191
+ def __str__(self):
192
+ s, = self.args
193
+ if self.latex_output:
194
+ s += "\n" + self.latex_output
195
+ return s
196
+
197
+
198
+ class LatexManager:
199
+ """
200
+ The LatexManager opens an instance of the LaTeX application for
201
+ determining the metrics of text elements. The LaTeX environment can be
202
+ modified by setting fonts and/or a custom preamble in `.rcParams`.
203
+ """
204
+
205
+ @staticmethod
206
+ def _build_latex_header():
207
+ latex_header = [
208
+ _DOCUMENTCLASS,
209
+ # Include TeX program name as a comment for cache invalidation.
210
+ # TeX does not allow this to be the first line.
211
+ rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}",
212
+ # Test whether \includegraphics supports interpolate option.
213
+ r"\usepackage{graphicx}",
214
+ _get_preamble(),
215
+ r"\begin{document}",
216
+ r"\typeout{pgf_backend_query_start}",
217
+ ]
218
+ return "\n".join(latex_header)
219
+
220
+ @classmethod
221
+ def _get_cached_or_new(cls):
222
+ """
223
+ Return the previous LatexManager if the header and tex system did not
224
+ change, or a new instance otherwise.
225
+ """
226
+ return cls._get_cached_or_new_impl(cls._build_latex_header())
227
+
228
+ @classmethod
229
+ @functools.lru_cache(1)
230
+ def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new.
231
+ return cls()
232
+
233
+ def _stdin_writeln(self, s):
234
+ if self.latex is None:
235
+ self._setup_latex_process()
236
+ self.latex.stdin.write(s)
237
+ self.latex.stdin.write("\n")
238
+ self.latex.stdin.flush()
239
+
240
+ def _expect(self, s):
241
+ s = list(s)
242
+ chars = []
243
+ while True:
244
+ c = self.latex.stdout.read(1)
245
+ chars.append(c)
246
+ if chars[-len(s):] == s:
247
+ break
248
+ if not c:
249
+ self.latex.kill()
250
+ self.latex = None
251
+ raise LatexError("LaTeX process halted", "".join(chars))
252
+ return "".join(chars)
253
+
254
+ def _expect_prompt(self):
255
+ return self._expect("\n*")
256
+
257
+ def __init__(self):
258
+ # create a tmp directory for running latex, register it for deletion
259
+ self._tmpdir = TemporaryDirectory()
260
+ self.tmpdir = self._tmpdir.name
261
+ self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup)
262
+
263
+ # test the LaTeX setup to ensure a clean startup of the subprocess
264
+ self._setup_latex_process(expect_reply=False)
265
+ stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n")
266
+ if self.latex.returncode != 0:
267
+ raise LatexError(
268
+ f"LaTeX errored (probably missing font or error in preamble) "
269
+ f"while processing the following input:\n"
270
+ f"{self._build_latex_header()}",
271
+ stdout)
272
+ self.latex = None # Will be set up on first use.
273
+ # Per-instance cache.
274
+ self._get_box_metrics = functools.lru_cache(self._get_box_metrics)
275
+
276
+ def _setup_latex_process(self, *, expect_reply=True):
277
+ # Open LaTeX process for real work; register it for deletion. On
278
+ # Windows, we must ensure that the subprocess has quit before being
279
+ # able to delete the tmpdir in which it runs; in order to do so, we
280
+ # must first `kill()` it, and then `communicate()` with or `wait()` on
281
+ # it.
282
+ try:
283
+ self.latex = subprocess.Popen(
284
+ [mpl.rcParams["pgf.texsystem"], "-halt-on-error"],
285
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
286
+ encoding="utf-8", cwd=self.tmpdir)
287
+ except FileNotFoundError as err:
288
+ raise RuntimeError(
289
+ f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change "
290
+ f"rcParams['pgf.texsystem'] to an available TeX implementation"
291
+ ) from err
292
+ except OSError as err:
293
+ raise RuntimeError(
294
+ f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err
295
+
296
+ def finalize_latex(latex):
297
+ latex.kill()
298
+ try:
299
+ latex.communicate()
300
+ except RuntimeError:
301
+ latex.wait()
302
+
303
+ self._finalize_latex = weakref.finalize(
304
+ self, finalize_latex, self.latex)
305
+ # write header with 'pgf_backend_query_start' token
306
+ self._stdin_writeln(self._build_latex_header())
307
+ if expect_reply: # read until 'pgf_backend_query_start' token appears
308
+ self._expect("*pgf_backend_query_start")
309
+ self._expect_prompt()
310
+
311
+ def get_width_height_descent(self, text, prop):
312
+ """
313
+ Get the width, total height, and descent (in TeX points) for a text
314
+ typeset by the current LaTeX environment.
315
+ """
316
+ return self._get_box_metrics(_escape_and_apply_props(text, prop))
317
+
318
+ def _get_box_metrics(self, tex):
319
+ """
320
+ Get the width, total height and descent (in TeX points) for a TeX
321
+ command's output in the current LaTeX environment.
322
+ """
323
+ # This method gets wrapped in __init__ for per-instance caching.
324
+ self._stdin_writeln( # Send textbox to TeX & request metrics typeout.
325
+ # \sbox doesn't handle catcode assignments inside its argument,
326
+ # so repeat the assignment of the catcode of "^" and "%" outside.
327
+ r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}"
328
+ r"\typeout{\the\wd0,\the\ht0,\the\dp0}}"
329
+ % tex)
330
+ try:
331
+ answer = self._expect_prompt()
332
+ except LatexError as err:
333
+ # Here and below, use '{}' instead of {!r} to avoid doubling all
334
+ # backslashes.
335
+ raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
336
+ .format(tex, err.latex_output)) from err
337
+ try:
338
+ # Parse metrics from the answer string. Last line is prompt, and
339
+ # next-to-last-line is blank line from \typeout.
340
+ width, height, offset = answer.splitlines()[-3].split(",")
341
+ except Exception as err:
342
+ raise ValueError("Error measuring {}\nLaTeX Output:\n{}"
343
+ .format(tex, answer)) from err
344
+ w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2])
345
+ # The height returned from LaTeX goes from base to top;
346
+ # the height Matplotlib expects goes from bottom to top.
347
+ return w, h + o, o
348
+
349
+
350
+ @functools.lru_cache(1)
351
+ def _get_image_inclusion_command():
352
+ man = LatexManager._get_cached_or_new()
353
+ man._stdin_writeln(
354
+ r"\includegraphics[interpolate=true]{%s}"
355
+ # Don't mess with backslashes on Windows.
356
+ % cbook._get_data_path("images/matplotlib.png").as_posix())
357
+ try:
358
+ man._expect_prompt()
359
+ return r"\includegraphics"
360
+ except LatexError:
361
+ # Discard the broken manager.
362
+ LatexManager._get_cached_or_new_impl.cache_clear()
363
+ return r"\pgfimage"
364
+
365
+
366
+ class RendererPgf(RendererBase):
367
+
368
+ def __init__(self, figure, fh):
369
+ """
370
+ Create a new PGF renderer that translates any drawing instruction
371
+ into text commands to be interpreted in a latex pgfpicture environment.
372
+
373
+ Attributes
374
+ ----------
375
+ figure : `~matplotlib.figure.Figure`
376
+ Matplotlib figure to initialize height, width and dpi from.
377
+ fh : file-like
378
+ File handle for the output of the drawing commands.
379
+ """
380
+
381
+ super().__init__()
382
+ self.dpi = figure.dpi
383
+ self.fh = fh
384
+ self.figure = figure
385
+ self.image_counter = 0
386
+
387
+ def draw_markers(self, gc, marker_path, marker_trans, path, trans,
388
+ rgbFace=None):
389
+ # docstring inherited
390
+
391
+ _writeln(self.fh, r"\begin{pgfscope}")
392
+
393
+ # convert from display units to in
394
+ f = 1. / self.dpi
395
+
396
+ # set style and clip
397
+ self._print_pgf_clip(gc)
398
+ self._print_pgf_path_styles(gc, rgbFace)
399
+
400
+ # build marker definition
401
+ bl, tr = marker_path.get_extents(marker_trans).get_points()
402
+ coords = bl[0] * f, bl[1] * f, tr[0] * f, tr[1] * f
403
+ _writeln(self.fh,
404
+ r"\pgfsys@defobject{currentmarker}"
405
+ r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{" % coords)
406
+ self._print_pgf_path(None, marker_path, marker_trans)
407
+ self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
408
+ fill=rgbFace is not None)
409
+ _writeln(self.fh, r"}")
410
+
411
+ maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
412
+ clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
413
+
414
+ # draw marker for each vertex
415
+ for point, code in path.iter_segments(trans, simplify=False,
416
+ clip=clip):
417
+ x, y = point[0] * f, point[1] * f
418
+ _writeln(self.fh, r"\begin{pgfscope}")
419
+ _writeln(self.fh, r"\pgfsys@transformshift{%fin}{%fin}" % (x, y))
420
+ _writeln(self.fh, r"\pgfsys@useobject{currentmarker}{}")
421
+ _writeln(self.fh, r"\end{pgfscope}")
422
+
423
+ _writeln(self.fh, r"\end{pgfscope}")
424
+
425
+ def draw_path(self, gc, path, transform, rgbFace=None):
426
+ # docstring inherited
427
+ _writeln(self.fh, r"\begin{pgfscope}")
428
+ # draw the path
429
+ self._print_pgf_clip(gc)
430
+ self._print_pgf_path_styles(gc, rgbFace)
431
+ self._print_pgf_path(gc, path, transform, rgbFace)
432
+ self._pgf_path_draw(stroke=gc.get_linewidth() != 0.0,
433
+ fill=rgbFace is not None)
434
+ _writeln(self.fh, r"\end{pgfscope}")
435
+
436
+ # if present, draw pattern on top
437
+ if gc.get_hatch():
438
+ _writeln(self.fh, r"\begin{pgfscope}")
439
+ self._print_pgf_path_styles(gc, rgbFace)
440
+
441
+ # combine clip and path for clipping
442
+ self._print_pgf_clip(gc)
443
+ self._print_pgf_path(gc, path, transform, rgbFace)
444
+ _writeln(self.fh, r"\pgfusepath{clip}")
445
+
446
+ # build pattern definition
447
+ _writeln(self.fh,
448
+ r"\pgfsys@defobject{currentpattern}"
449
+ r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{")
450
+ _writeln(self.fh, r"\begin{pgfscope}")
451
+ _writeln(self.fh,
452
+ r"\pgfpathrectangle"
453
+ r"{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}")
454
+ _writeln(self.fh, r"\pgfusepath{clip}")
455
+ scale = mpl.transforms.Affine2D().scale(self.dpi)
456
+ self._print_pgf_path(None, gc.get_hatch_path(), scale)
457
+ self._pgf_path_draw(stroke=True)
458
+ _writeln(self.fh, r"\end{pgfscope}")
459
+ _writeln(self.fh, r"}")
460
+ # repeat pattern, filling the bounding rect of the path
461
+ f = 1. / self.dpi
462
+ (xmin, ymin), (xmax, ymax) = \
463
+ path.get_extents(transform).get_points()
464
+ xmin, xmax = f * xmin, f * xmax
465
+ ymin, ymax = f * ymin, f * ymax
466
+ repx, repy = math.ceil(xmax - xmin), math.ceil(ymax - ymin)
467
+ _writeln(self.fh,
468
+ r"\pgfsys@transformshift{%fin}{%fin}" % (xmin, ymin))
469
+ for iy in range(repy):
470
+ for ix in range(repx):
471
+ _writeln(self.fh, r"\pgfsys@useobject{currentpattern}{}")
472
+ _writeln(self.fh, r"\pgfsys@transformshift{1in}{0in}")
473
+ _writeln(self.fh, r"\pgfsys@transformshift{-%din}{0in}" % repx)
474
+ _writeln(self.fh, r"\pgfsys@transformshift{0in}{1in}")
475
+
476
+ _writeln(self.fh, r"\end{pgfscope}")
477
+
478
+ def _print_pgf_clip(self, gc):
479
+ f = 1. / self.dpi
480
+ # check for clip box
481
+ bbox = gc.get_clip_rectangle()
482
+ if bbox:
483
+ p1, p2 = bbox.get_points()
484
+ w, h = p2 - p1
485
+ coords = p1[0] * f, p1[1] * f, w * f, h * f
486
+ _writeln(self.fh,
487
+ r"\pgfpathrectangle"
488
+ r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
489
+ % coords)
490
+ _writeln(self.fh, r"\pgfusepath{clip}")
491
+
492
+ # check for clip path
493
+ clippath, clippath_trans = gc.get_clip_path()
494
+ if clippath is not None:
495
+ self._print_pgf_path(gc, clippath, clippath_trans)
496
+ _writeln(self.fh, r"\pgfusepath{clip}")
497
+
498
+ def _print_pgf_path_styles(self, gc, rgbFace):
499
+ # cap style
500
+ capstyles = {"butt": r"\pgfsetbuttcap",
501
+ "round": r"\pgfsetroundcap",
502
+ "projecting": r"\pgfsetrectcap"}
503
+ _writeln(self.fh, capstyles[gc.get_capstyle()])
504
+
505
+ # join style
506
+ joinstyles = {"miter": r"\pgfsetmiterjoin",
507
+ "round": r"\pgfsetroundjoin",
508
+ "bevel": r"\pgfsetbeveljoin"}
509
+ _writeln(self.fh, joinstyles[gc.get_joinstyle()])
510
+
511
+ # filling
512
+ has_fill = rgbFace is not None
513
+
514
+ if gc.get_forced_alpha():
515
+ fillopacity = strokeopacity = gc.get_alpha()
516
+ else:
517
+ strokeopacity = gc.get_rgb()[3]
518
+ fillopacity = rgbFace[3] if has_fill and len(rgbFace) > 3 else 1.0
519
+
520
+ if has_fill:
521
+ _writeln(self.fh,
522
+ r"\definecolor{currentfill}{rgb}{%f,%f,%f}"
523
+ % tuple(rgbFace[:3]))
524
+ _writeln(self.fh, r"\pgfsetfillcolor{currentfill}")
525
+ if has_fill and fillopacity != 1.0:
526
+ _writeln(self.fh, r"\pgfsetfillopacity{%f}" % fillopacity)
527
+
528
+ # linewidth and color
529
+ lw = gc.get_linewidth() * mpl_pt_to_in * latex_in_to_pt
530
+ stroke_rgba = gc.get_rgb()
531
+ _writeln(self.fh, r"\pgfsetlinewidth{%fpt}" % lw)
532
+ _writeln(self.fh,
533
+ r"\definecolor{currentstroke}{rgb}{%f,%f,%f}"
534
+ % stroke_rgba[:3])
535
+ _writeln(self.fh, r"\pgfsetstrokecolor{currentstroke}")
536
+ if strokeopacity != 1.0:
537
+ _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % strokeopacity)
538
+
539
+ # line style
540
+ dash_offset, dash_list = gc.get_dashes()
541
+ if dash_list is None:
542
+ _writeln(self.fh, r"\pgfsetdash{}{0pt}")
543
+ else:
544
+ _writeln(self.fh,
545
+ r"\pgfsetdash{%s}{%fpt}"
546
+ % ("".join(r"{%fpt}" % dash for dash in dash_list),
547
+ dash_offset))
548
+
549
+ def _print_pgf_path(self, gc, path, transform, rgbFace=None):
550
+ f = 1. / self.dpi
551
+ # check for clip box / ignore clip for filled paths
552
+ bbox = gc.get_clip_rectangle() if gc else None
553
+ maxcoord = 16383 / 72.27 * self.dpi # Max dimensions in LaTeX.
554
+ if bbox and (rgbFace is None):
555
+ p1, p2 = bbox.get_points()
556
+ clip = (max(p1[0], -maxcoord), max(p1[1], -maxcoord),
557
+ min(p2[0], maxcoord), min(p2[1], maxcoord))
558
+ else:
559
+ clip = (-maxcoord, -maxcoord, maxcoord, maxcoord)
560
+ # build path
561
+ for points, code in path.iter_segments(transform, clip=clip):
562
+ if code == Path.MOVETO:
563
+ x, y = tuple(points)
564
+ _writeln(self.fh,
565
+ r"\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}" %
566
+ (f * x, f * y))
567
+ elif code == Path.CLOSEPOLY:
568
+ _writeln(self.fh, r"\pgfpathclose")
569
+ elif code == Path.LINETO:
570
+ x, y = tuple(points)
571
+ _writeln(self.fh,
572
+ r"\pgfpathlineto{\pgfqpoint{%fin}{%fin}}" %
573
+ (f * x, f * y))
574
+ elif code == Path.CURVE3:
575
+ cx, cy, px, py = tuple(points)
576
+ coords = cx * f, cy * f, px * f, py * f
577
+ _writeln(self.fh,
578
+ r"\pgfpathquadraticcurveto"
579
+ r"{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}"
580
+ % coords)
581
+ elif code == Path.CURVE4:
582
+ c1x, c1y, c2x, c2y, px, py = tuple(points)
583
+ coords = c1x * f, c1y * f, c2x * f, c2y * f, px * f, py * f
584
+ _writeln(self.fh,
585
+ r"\pgfpathcurveto"
586
+ r"{\pgfqpoint{%fin}{%fin}}"
587
+ r"{\pgfqpoint{%fin}{%fin}}"
588
+ r"{\pgfqpoint{%fin}{%fin}}"
589
+ % coords)
590
+
591
+ # apply pgf decorators
592
+ sketch_params = gc.get_sketch_params() if gc else None
593
+ if sketch_params is not None:
594
+ # Only "length" directly maps to "segment length" in PGF's API.
595
+ # PGF uses "amplitude" to pass the combined deviation in both x-
596
+ # and y-direction, while matplotlib only varies the length of the
597
+ # wiggle along the line ("randomness" and "length" parameters)
598
+ # and has a separate "scale" argument for the amplitude.
599
+ # -> Use "randomness" as PRNG seed to allow the user to force the
600
+ # same shape on multiple sketched lines
601
+ scale, length, randomness = sketch_params
602
+ if scale is not None:
603
+ # make matplotlib and PGF rendering visually similar
604
+ length *= 0.5
605
+ scale *= 2
606
+ # PGF guarantees that repeated loading is a no-op
607
+ _writeln(self.fh, r"\usepgfmodule{decorations}")
608
+ _writeln(self.fh, r"\usepgflibrary{decorations.pathmorphing}")
609
+ _writeln(self.fh, r"\pgfkeys{/pgf/decoration/.cd, "
610
+ f"segment length = {(length * f):f}in, "
611
+ f"amplitude = {(scale * f):f}in}}")
612
+ _writeln(self.fh, f"\\pgfmathsetseed{{{int(randomness)}}}")
613
+ _writeln(self.fh, r"\pgfdecoratecurrentpath{random steps}")
614
+
615
+ def _pgf_path_draw(self, stroke=True, fill=False):
616
+ actions = []
617
+ if stroke:
618
+ actions.append("stroke")
619
+ if fill:
620
+ actions.append("fill")
621
+ _writeln(self.fh, r"\pgfusepath{%s}" % ",".join(actions))
622
+
623
+ def option_scale_image(self):
624
+ # docstring inherited
625
+ return True
626
+
627
+ def option_image_nocomposite(self):
628
+ # docstring inherited
629
+ return not mpl.rcParams['image.composite_image']
630
+
631
+ def draw_image(self, gc, x, y, im, transform=None):
632
+ # docstring inherited
633
+
634
+ h, w = im.shape[:2]
635
+ if w == 0 or h == 0:
636
+ return
637
+
638
+ if not os.path.exists(getattr(self.fh, "name", "")):
639
+ raise ValueError(
640
+ "streamed pgf-code does not support raster graphics, consider "
641
+ "using the pgf-to-pdf option")
642
+
643
+ # save the images to png files
644
+ path = pathlib.Path(self.fh.name)
645
+ fname_img = "%s-img%d.png" % (path.stem, self.image_counter)
646
+ Image.fromarray(im[::-1]).save(path.parent / fname_img)
647
+ self.image_counter += 1
648
+
649
+ # reference the image in the pgf picture
650
+ _writeln(self.fh, r"\begin{pgfscope}")
651
+ self._print_pgf_clip(gc)
652
+ f = 1. / self.dpi # from display coords to inch
653
+ if transform is None:
654
+ _writeln(self.fh,
655
+ r"\pgfsys@transformshift{%fin}{%fin}" % (x * f, y * f))
656
+ w, h = w * f, h * f
657
+ else:
658
+ tr1, tr2, tr3, tr4, tr5, tr6 = transform.frozen().to_values()
659
+ _writeln(self.fh,
660
+ r"\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}" %
661
+ (tr1 * f, tr2 * f, tr3 * f, tr4 * f,
662
+ (tr5 + x) * f, (tr6 + y) * f))
663
+ w = h = 1 # scale is already included in the transform
664
+ interp = str(transform is None).lower() # interpolation in PDF reader
665
+ _writeln(self.fh,
666
+ r"\pgftext[left,bottom]"
667
+ r"{%s[interpolate=%s,width=%fin,height=%fin]{%s}}" %
668
+ (_get_image_inclusion_command(),
669
+ interp, w, h, fname_img))
670
+ _writeln(self.fh, r"\end{pgfscope}")
671
+
672
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
673
+ # docstring inherited
674
+ self.draw_text(gc, x, y, s, prop, angle, ismath="TeX", mtext=mtext)
675
+
676
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
677
+ # docstring inherited
678
+
679
+ # prepare string for tex
680
+ s = _escape_and_apply_props(s, prop)
681
+
682
+ _writeln(self.fh, r"\begin{pgfscope}")
683
+ self._print_pgf_clip(gc)
684
+
685
+ alpha = gc.get_alpha()
686
+ if alpha != 1.0:
687
+ _writeln(self.fh, r"\pgfsetfillopacity{%f}" % alpha)
688
+ _writeln(self.fh, r"\pgfsetstrokeopacity{%f}" % alpha)
689
+ rgb = tuple(gc.get_rgb())[:3]
690
+ _writeln(self.fh, r"\definecolor{textcolor}{rgb}{%f,%f,%f}" % rgb)
691
+ _writeln(self.fh, r"\pgfsetstrokecolor{textcolor}")
692
+ _writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
693
+ s = r"\color{textcolor}" + s
694
+
695
+ dpi = self.figure.dpi
696
+ text_args = []
697
+ if mtext and (
698
+ (angle == 0 or
699
+ mtext.get_rotation_mode() == "anchor") and
700
+ mtext.get_verticalalignment() != "center_baseline"):
701
+ # if text anchoring can be supported, get the original coordinates
702
+ # and add alignment information
703
+ pos = mtext.get_unitless_position()
704
+ x, y = mtext.get_transform().transform(pos)
705
+ halign = {"left": "left", "right": "right", "center": ""}
706
+ valign = {"top": "top", "bottom": "bottom",
707
+ "baseline": "base", "center": ""}
708
+ text_args.extend([
709
+ f"x={x/dpi:f}in",
710
+ f"y={y/dpi:f}in",
711
+ halign[mtext.get_horizontalalignment()],
712
+ valign[mtext.get_verticalalignment()],
713
+ ])
714
+ else:
715
+ # if not, use the text layout provided by Matplotlib.
716
+ text_args.append(f"x={x/dpi:f}in, y={y/dpi:f}in, left, base")
717
+
718
+ if angle != 0:
719
+ text_args.append("rotate=%f" % angle)
720
+
721
+ _writeln(self.fh, r"\pgftext[%s]{%s}" % (",".join(text_args), s))
722
+ _writeln(self.fh, r"\end{pgfscope}")
723
+
724
+ def get_text_width_height_descent(self, s, prop, ismath):
725
+ # docstring inherited
726
+ # get text metrics in units of latex pt, convert to display units
727
+ w, h, d = (LatexManager._get_cached_or_new()
728
+ .get_width_height_descent(s, prop))
729
+ # TODO: this should be latex_pt_to_in instead of mpl_pt_to_in
730
+ # but having a little bit more space around the text looks better,
731
+ # plus the bounding box reported by LaTeX is VERY narrow
732
+ f = mpl_pt_to_in * self.dpi
733
+ return w * f, h * f, d * f
734
+
735
+ def flipy(self):
736
+ # docstring inherited
737
+ return False
738
+
739
+ def get_canvas_width_height(self):
740
+ # docstring inherited
741
+ return (self.figure.get_figwidth() * self.dpi,
742
+ self.figure.get_figheight() * self.dpi)
743
+
744
+ def points_to_pixels(self, points):
745
+ # docstring inherited
746
+ return points * mpl_pt_to_in * self.dpi
747
+
748
+
749
+ class FigureCanvasPgf(FigureCanvasBase):
750
+ filetypes = {"pgf": "LaTeX PGF picture",
751
+ "pdf": "LaTeX compiled PGF picture",
752
+ "png": "Portable Network Graphics", }
753
+
754
+ def get_default_filetype(self):
755
+ return 'pdf'
756
+
757
+ def _print_pgf_to_fh(self, fh, *, bbox_inches_restore=None):
758
+
759
+ header_text = """%% Creator: Matplotlib, PGF backend
760
+ %%
761
+ %% To include the figure in your LaTeX document, write
762
+ %% \\input{<filename>.pgf}
763
+ %%
764
+ %% Make sure the required packages are loaded in your preamble
765
+ %% \\usepackage{pgf}
766
+ %%
767
+ %% Also ensure that all the required font packages are loaded; for instance,
768
+ %% the lmodern package is sometimes necessary when using math font.
769
+ %% \\usepackage{lmodern}
770
+ %%
771
+ %% Figures using additional raster images can only be included by \\input if
772
+ %% they are in the same directory as the main LaTeX file. For loading figures
773
+ %% from other directories you can use the `import` package
774
+ %% \\usepackage{import}
775
+ %%
776
+ %% and then include the figures with
777
+ %% \\import{<path to file>}{<filename>.pgf}
778
+ %%
779
+ """
780
+
781
+ # append the preamble used by the backend as a comment for debugging
782
+ header_info_preamble = ["%% Matplotlib used the following preamble"]
783
+ for line in _get_preamble().splitlines():
784
+ header_info_preamble.append("%% " + line)
785
+ header_info_preamble.append("%%")
786
+ header_info_preamble = "\n".join(header_info_preamble)
787
+
788
+ # get figure size in inch
789
+ w, h = self.figure.get_figwidth(), self.figure.get_figheight()
790
+ dpi = self.figure.dpi
791
+
792
+ # create pgfpicture environment and write the pgf code
793
+ fh.write(header_text)
794
+ fh.write(header_info_preamble)
795
+ fh.write("\n")
796
+ _writeln(fh, r"\begingroup")
797
+ _writeln(fh, r"\makeatletter")
798
+ _writeln(fh, r"\begin{pgfpicture}")
799
+ _writeln(fh,
800
+ r"\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}"
801
+ % (w, h))
802
+ _writeln(fh, r"\pgfusepath{use as bounding box, clip}")
803
+ renderer = MixedModeRenderer(self.figure, w, h, dpi,
804
+ RendererPgf(self.figure, fh),
805
+ bbox_inches_restore=bbox_inches_restore)
806
+ self.figure.draw(renderer)
807
+
808
+ # end the pgfpicture environment
809
+ _writeln(fh, r"\end{pgfpicture}")
810
+ _writeln(fh, r"\makeatother")
811
+ _writeln(fh, r"\endgroup")
812
+
813
+ def print_pgf(self, fname_or_fh, **kwargs):
814
+ """
815
+ Output pgf macros for drawing the figure so it can be included and
816
+ rendered in latex documents.
817
+ """
818
+ with cbook.open_file_cm(fname_or_fh, "w", encoding="utf-8") as file:
819
+ if not cbook.file_requires_unicode(file):
820
+ file = codecs.getwriter("utf-8")(file)
821
+ self._print_pgf_to_fh(file, **kwargs)
822
+
823
+ def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
824
+ """Use LaTeX to compile a pgf generated figure to pdf."""
825
+ w, h = self.figure.get_size_inches()
826
+
827
+ info_dict = _create_pdf_info_dict('pgf', metadata or {})
828
+ pdfinfo = ','.join(
829
+ _metadata_to_str(k, v) for k, v in info_dict.items())
830
+
831
+ # print figure to pgf and compile it with latex
832
+ with TemporaryDirectory() as tmpdir:
833
+ tmppath = pathlib.Path(tmpdir)
834
+ self.print_pgf(tmppath / "figure.pgf", **kwargs)
835
+ (tmppath / "figure.tex").write_text(
836
+ "\n".join([
837
+ _DOCUMENTCLASS,
838
+ r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
839
+ r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
840
+ % (w, h),
841
+ r"\usepackage{pgf}",
842
+ _get_preamble(),
843
+ r"\begin{document}",
844
+ r"\centering",
845
+ r"\input{figure.pgf}",
846
+ r"\end{document}",
847
+ ]), encoding="utf-8")
848
+ texcommand = mpl.rcParams["pgf.texsystem"]
849
+ cbook._check_and_log_subprocess(
850
+ [texcommand, "-interaction=nonstopmode", "-halt-on-error",
851
+ "figure.tex"], _log, cwd=tmpdir)
852
+ with ((tmppath / "figure.pdf").open("rb") as orig,
853
+ cbook.open_file_cm(fname_or_fh, "wb") as dest):
854
+ shutil.copyfileobj(orig, dest) # copy file contents to target
855
+
856
+ def print_png(self, fname_or_fh, **kwargs):
857
+ """Use LaTeX to compile a pgf figure to pdf and convert it to png."""
858
+ converter = make_pdf_to_png_converter()
859
+ with TemporaryDirectory() as tmpdir:
860
+ tmppath = pathlib.Path(tmpdir)
861
+ pdf_path = tmppath / "figure.pdf"
862
+ png_path = tmppath / "figure.png"
863
+ self.print_pdf(pdf_path, **kwargs)
864
+ converter(pdf_path, png_path, dpi=self.figure.dpi)
865
+ with (png_path.open("rb") as orig,
866
+ cbook.open_file_cm(fname_or_fh, "wb") as dest):
867
+ shutil.copyfileobj(orig, dest) # copy file contents to target
868
+
869
+ def get_renderer(self):
870
+ return RendererPgf(self.figure, None)
871
+
872
+ def draw(self):
873
+ self.figure.draw_without_rendering()
874
+ return super().draw()
875
+
876
+
877
+ FigureManagerPgf = FigureManagerBase
878
+
879
+
880
+ @_Backend.export
881
+ class _BackendPgf(_Backend):
882
+ FigureCanvas = FigureCanvasPgf
883
+
884
+
885
+ class PdfPages:
886
+ """
887
+ A multi-page PDF file using the pgf backend
888
+
889
+ Examples
890
+ --------
891
+ >>> import matplotlib.pyplot as plt
892
+ >>> # Initialize:
893
+ >>> with PdfPages('foo.pdf') as pdf:
894
+ ... # As many times as you like, create a figure fig and save it:
895
+ ... fig = plt.figure()
896
+ ... pdf.savefig(fig)
897
+ ... # When no figure is specified the current figure is saved
898
+ ... pdf.savefig()
899
+ """
900
+
901
+ def __init__(self, filename, *, metadata=None):
902
+ """
903
+ Create a new PdfPages object.
904
+
905
+ Parameters
906
+ ----------
907
+ filename : str or path-like
908
+ Plots using `PdfPages.savefig` will be written to a file at this
909
+ location. Any older file with the same name is overwritten.
910
+
911
+ metadata : dict, optional
912
+ Information dictionary object (see PDF reference section 10.2.1
913
+ 'Document Information Dictionary'), e.g.:
914
+ ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
915
+
916
+ The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
917
+ 'Creator', 'Producer', 'CreationDate', 'ModDate', and
918
+ 'Trapped'. Values have been predefined for 'Creator', 'Producer'
919
+ and 'CreationDate'. They can be removed by setting them to `None`.
920
+
921
+ Note that some versions of LaTeX engines may ignore the 'Producer'
922
+ key and set it to themselves.
923
+ """
924
+ self._output_name = filename
925
+ self._n_figures = 0
926
+ self._metadata = (metadata or {}).copy()
927
+ self._info_dict = _create_pdf_info_dict('pgf', self._metadata)
928
+ self._file = BytesIO()
929
+
930
+ def _write_header(self, width_inches, height_inches):
931
+ pdfinfo = ','.join(
932
+ _metadata_to_str(k, v) for k, v in self._info_dict.items())
933
+ latex_header = "\n".join([
934
+ _DOCUMENTCLASS,
935
+ r"\usepackage[pdfinfo={%s}]{hyperref}" % pdfinfo,
936
+ r"\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}"
937
+ % (width_inches, height_inches),
938
+ r"\usepackage{pgf}",
939
+ _get_preamble(),
940
+ r"\setlength{\parindent}{0pt}",
941
+ r"\begin{document}%",
942
+ ])
943
+ self._file.write(latex_header.encode('utf-8'))
944
+
945
+ def __enter__(self):
946
+ return self
947
+
948
+ def __exit__(self, exc_type, exc_val, exc_tb):
949
+ self.close()
950
+
951
+ def close(self):
952
+ """
953
+ Finalize this object, running LaTeX in a temporary directory
954
+ and moving the final pdf file to *filename*.
955
+ """
956
+ self._file.write(rb'\end{document}\n')
957
+ if self._n_figures > 0:
958
+ self._run_latex()
959
+ self._file.close()
960
+
961
+ def _run_latex(self):
962
+ texcommand = mpl.rcParams["pgf.texsystem"]
963
+ with TemporaryDirectory() as tmpdir:
964
+ tex_source = pathlib.Path(tmpdir, "pdf_pages.tex")
965
+ tex_source.write_bytes(self._file.getvalue())
966
+ cbook._check_and_log_subprocess(
967
+ [texcommand, "-interaction=nonstopmode", "-halt-on-error",
968
+ tex_source],
969
+ _log, cwd=tmpdir)
970
+ shutil.move(tex_source.with_suffix(".pdf"), self._output_name)
971
+
972
+ def savefig(self, figure=None, **kwargs):
973
+ """
974
+ Save a `.Figure` to this file as a new page.
975
+
976
+ Any other keyword arguments are passed to `~.Figure.savefig`.
977
+
978
+ Parameters
979
+ ----------
980
+ figure : `.Figure` or int, default: the active figure
981
+ The figure, or index of the figure, that is saved to the file.
982
+ """
983
+ if not isinstance(figure, Figure):
984
+ if figure is None:
985
+ manager = Gcf.get_active()
986
+ else:
987
+ manager = Gcf.get_fig_manager(figure)
988
+ if manager is None:
989
+ raise ValueError(f"No figure {figure}")
990
+ figure = manager.canvas.figure
991
+
992
+ width, height = figure.get_size_inches()
993
+ if self._n_figures == 0:
994
+ self._write_header(width, height)
995
+ else:
996
+ # \pdfpagewidth and \pdfpageheight exist on pdftex, xetex, and
997
+ # luatex<0.85; they were renamed to \pagewidth and \pageheight
998
+ # on luatex>=0.85.
999
+ self._file.write(
1000
+ rb'\newpage'
1001
+ rb'\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%fin'
1002
+ rb'\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin'
1003
+ b'%%\n' % (width, height)
1004
+ )
1005
+ figure.savefig(self._file, format="pgf", backend="pgf", **kwargs)
1006
+ self._n_figures += 1
1007
+
1008
+ def get_pagecount(self):
1009
+ """Return the current number of pages in the multipage pdf file."""
1010
+ return self._n_figures
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_ps.py ADDED
@@ -0,0 +1,1481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A PostScript backend, which can produce both PostScript .ps and .eps.
3
+ """
4
+
5
+ import bisect
6
+ import codecs
7
+ import datetime
8
+ from enum import Enum
9
+ import functools
10
+ from io import StringIO
11
+ import itertools
12
+ import logging
13
+ import math
14
+ import os
15
+ import pathlib
16
+ import shutil
17
+ import struct
18
+ from tempfile import TemporaryDirectory
19
+ import textwrap
20
+ import time
21
+
22
+ import fontTools
23
+ import numpy as np
24
+
25
+ import matplotlib as mpl
26
+ from matplotlib import _api, cbook, _path, _text_helpers
27
+ from matplotlib._afm import AFM
28
+ from matplotlib.backend_bases import (
29
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
30
+ from matplotlib.cbook import is_writable_file_like, file_requires_unicode
31
+ from matplotlib.font_manager import get_font
32
+ from matplotlib.ft2font import LoadFlags
33
+ from matplotlib._mathtext_data import uni2type1
34
+ from matplotlib.path import Path
35
+ from matplotlib.texmanager import TexManager
36
+ from matplotlib.transforms import Affine2D
37
+ from matplotlib.backends.backend_mixed import MixedModeRenderer
38
+ from . import _backend_pdf_ps
39
+
40
+
41
+ _log = logging.getLogger(__name__)
42
+ debugPS = False
43
+
44
+
45
+ papersize = {'letter': (8.5, 11),
46
+ 'legal': (8.5, 14),
47
+ 'ledger': (11, 17),
48
+ 'a0': (33.11, 46.81),
49
+ 'a1': (23.39, 33.11),
50
+ 'a2': (16.54, 23.39),
51
+ 'a3': (11.69, 16.54),
52
+ 'a4': (8.27, 11.69),
53
+ 'a5': (5.83, 8.27),
54
+ 'a6': (4.13, 5.83),
55
+ 'a7': (2.91, 4.13),
56
+ 'a8': (2.05, 2.91),
57
+ 'a9': (1.46, 2.05),
58
+ 'a10': (1.02, 1.46),
59
+ 'b0': (40.55, 57.32),
60
+ 'b1': (28.66, 40.55),
61
+ 'b2': (20.27, 28.66),
62
+ 'b3': (14.33, 20.27),
63
+ 'b4': (10.11, 14.33),
64
+ 'b5': (7.16, 10.11),
65
+ 'b6': (5.04, 7.16),
66
+ 'b7': (3.58, 5.04),
67
+ 'b8': (2.51, 3.58),
68
+ 'b9': (1.76, 2.51),
69
+ 'b10': (1.26, 1.76)}
70
+
71
+
72
+ def _nums_to_str(*args, sep=" "):
73
+ return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
74
+
75
+
76
+ def _move_path_to_path_or_stream(src, dst):
77
+ """
78
+ Move the contents of file at *src* to path-or-filelike *dst*.
79
+
80
+ If *dst* is a path, the metadata of *src* are *not* copied.
81
+ """
82
+ if is_writable_file_like(dst):
83
+ fh = (open(src, encoding='latin-1')
84
+ if file_requires_unicode(dst)
85
+ else open(src, 'rb'))
86
+ with fh:
87
+ shutil.copyfileobj(fh, dst)
88
+ else:
89
+ shutil.move(src, dst, copy_function=shutil.copyfile)
90
+
91
+
92
+ def _font_to_ps_type3(font_path, chars):
93
+ """
94
+ Subset *chars* from the font at *font_path* into a Type 3 font.
95
+
96
+ Parameters
97
+ ----------
98
+ font_path : path-like
99
+ Path to the font to be subsetted.
100
+ chars : str
101
+ The characters to include in the subsetted font.
102
+
103
+ Returns
104
+ -------
105
+ str
106
+ The string representation of a Type 3 font, which can be included
107
+ verbatim into a PostScript file.
108
+ """
109
+ font = get_font(font_path, hinting_factor=1)
110
+ glyph_ids = [font.get_char_index(c) for c in chars]
111
+
112
+ preamble = """\
113
+ %!PS-Adobe-3.0 Resource-Font
114
+ %%Creator: Converted from TrueType to Type 3 by Matplotlib.
115
+ 10 dict begin
116
+ /FontName /{font_name} def
117
+ /PaintType 0 def
118
+ /FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
119
+ /FontBBox [{bbox}] def
120
+ /FontType 3 def
121
+ /Encoding [{encoding}] def
122
+ /CharStrings {num_glyphs} dict dup begin
123
+ /.notdef 0 def
124
+ """.format(font_name=font.postscript_name,
125
+ inv_units_per_em=1 / font.units_per_EM,
126
+ bbox=" ".join(map(str, font.bbox)),
127
+ encoding=" ".join(f"/{font.get_glyph_name(glyph_id)}"
128
+ for glyph_id in glyph_ids),
129
+ num_glyphs=len(glyph_ids) + 1)
130
+ postamble = """
131
+ end readonly def
132
+
133
+ /BuildGlyph {
134
+ exch begin
135
+ CharStrings exch
136
+ 2 copy known not {pop /.notdef} if
137
+ true 3 1 roll get exec
138
+ end
139
+ } _d
140
+
141
+ /BuildChar {
142
+ 1 index /Encoding get exch get
143
+ 1 index /BuildGlyph get exec
144
+ } _d
145
+
146
+ FontName currentdict end definefont pop
147
+ """
148
+
149
+ entries = []
150
+ for glyph_id in glyph_ids:
151
+ g = font.load_glyph(glyph_id, LoadFlags.NO_SCALE)
152
+ v, c = font.get_path()
153
+ entries.append(
154
+ "/%(name)s{%(bbox)s sc\n" % {
155
+ "name": font.get_glyph_name(glyph_id),
156
+ "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
157
+ }
158
+ + _path.convert_to_string(
159
+ # Convert back to TrueType's internal units (1/64's).
160
+ # (Other dimensions are already in these units.)
161
+ Path(v * 64, c), None, None, False, None, 0,
162
+ # No code for quad Beziers triggers auto-conversion to cubics.
163
+ # Drop intermediate closepolys (relying on the outline
164
+ # decomposer always explicitly moving to the closing point
165
+ # first).
166
+ [b"m", b"l", b"", b"c", b""], True).decode("ascii")
167
+ + "ce} _d"
168
+ )
169
+
170
+ return preamble + "\n".join(entries) + postamble
171
+
172
+
173
+ def _font_to_ps_type42(font_path, chars, fh):
174
+ """
175
+ Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.
176
+
177
+ Parameters
178
+ ----------
179
+ font_path : path-like
180
+ Path to the font to be subsetted.
181
+ chars : str
182
+ The characters to include in the subsetted font.
183
+ fh : file-like
184
+ Where to write the font.
185
+ """
186
+ subset_str = ''.join(chr(c) for c in chars)
187
+ _log.debug("SUBSET %s characters: %s", font_path, subset_str)
188
+ try:
189
+ kw = {}
190
+ # fix this once we support loading more fonts from a collection
191
+ # https://github.com/matplotlib/matplotlib/issues/3135#issuecomment-571085541
192
+ if font_path.endswith('.ttc'):
193
+ kw['fontNumber'] = 0
194
+ with (fontTools.ttLib.TTFont(font_path, **kw) as font,
195
+ _backend_pdf_ps.get_glyphs_subset(font_path, subset_str) as subset):
196
+ fontdata = _backend_pdf_ps.font_as_file(subset).getvalue()
197
+ _log.debug(
198
+ "SUBSET %s %d -> %d", font_path, os.stat(font_path).st_size,
199
+ len(fontdata)
200
+ )
201
+ fh.write(_serialize_type42(font, subset, fontdata))
202
+ except RuntimeError:
203
+ _log.warning(
204
+ "The PostScript backend does not currently support the selected font (%s).",
205
+ font_path)
206
+ raise
207
+
208
+
209
+ def _serialize_type42(font, subset, fontdata):
210
+ """
211
+ Output a PostScript Type-42 format representation of font
212
+
213
+ Parameters
214
+ ----------
215
+ font : fontTools.ttLib.ttFont.TTFont
216
+ The original font object
217
+ subset : fontTools.ttLib.ttFont.TTFont
218
+ The subset font object
219
+ fontdata : bytes
220
+ The raw font data in TTF format
221
+
222
+ Returns
223
+ -------
224
+ str
225
+ The Type-42 formatted font
226
+ """
227
+ version, breakpoints = _version_and_breakpoints(font.get('loca'), fontdata)
228
+ post = font['post']
229
+ name = font['name']
230
+ chars = _generate_charstrings(subset)
231
+ sfnts = _generate_sfnts(fontdata, subset, breakpoints)
232
+ return textwrap.dedent(f"""
233
+ %%!PS-TrueTypeFont-{version[0]}.{version[1]}-{font['head'].fontRevision:.7f}
234
+ 10 dict begin
235
+ /FontType 42 def
236
+ /FontMatrix [1 0 0 1 0 0] def
237
+ /FontName /{name.getDebugName(6)} def
238
+ /FontInfo 7 dict dup begin
239
+ /FullName ({name.getDebugName(4)}) def
240
+ /FamilyName ({name.getDebugName(1)}) def
241
+ /Version ({name.getDebugName(5)}) def
242
+ /ItalicAngle {post.italicAngle} def
243
+ /isFixedPitch {'true' if post.isFixedPitch else 'false'} def
244
+ /UnderlinePosition {post.underlinePosition} def
245
+ /UnderlineThickness {post.underlineThickness} def
246
+ end readonly def
247
+ /Encoding StandardEncoding def
248
+ /FontBBox [{_nums_to_str(*_bounds(font))}] def
249
+ /PaintType 0 def
250
+ /CIDMap 0 def
251
+ {chars}
252
+ {sfnts}
253
+ FontName currentdict end definefont pop
254
+ """)
255
+
256
+
257
+ def _version_and_breakpoints(loca, fontdata):
258
+ """
259
+ Read the version number of the font and determine sfnts breakpoints.
260
+
261
+ When a TrueType font file is written as a Type 42 font, it has to be
262
+ broken into substrings of at most 65535 bytes. These substrings must
263
+ begin at font table boundaries or glyph boundaries in the glyf table.
264
+ This function determines all possible breakpoints and it is the caller's
265
+ responsibility to do the splitting.
266
+
267
+ Helper function for _font_to_ps_type42.
268
+
269
+ Parameters
270
+ ----------
271
+ loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None
272
+ The loca table of the font if available
273
+ fontdata : bytes
274
+ The raw data of the font
275
+
276
+ Returns
277
+ -------
278
+ version : tuple[int, int]
279
+ A 2-tuple of the major version number and minor version number.
280
+ breakpoints : list[int]
281
+ The breakpoints is a sorted list of offsets into fontdata; if loca is not
282
+ available, just the table boundaries.
283
+ """
284
+ v1, v2, numTables = struct.unpack('>3h', fontdata[:6])
285
+ version = (v1, v2)
286
+
287
+ tables = {}
288
+ for i in range(numTables):
289
+ tag, _, offset, _ = struct.unpack('>4sIII', fontdata[12 + i*16:12 + (i+1)*16])
290
+ tables[tag.decode('ascii')] = offset
291
+ if loca is not None:
292
+ glyf_breakpoints = {tables['glyf'] + offset for offset in loca.locations[:-1]}
293
+ else:
294
+ glyf_breakpoints = set()
295
+ breakpoints = sorted({*tables.values(), *glyf_breakpoints, len(fontdata)})
296
+
297
+ return version, breakpoints
298
+
299
+
300
+ def _bounds(font):
301
+ """
302
+ Compute the font bounding box, as if all glyphs were written
303
+ at the same start position.
304
+
305
+ Helper function for _font_to_ps_type42.
306
+
307
+ Parameters
308
+ ----------
309
+ font : fontTools.ttLib.ttFont.TTFont
310
+ The font
311
+
312
+ Returns
313
+ -------
314
+ tuple
315
+ (xMin, yMin, xMax, yMax) of the combined bounding box
316
+ of all the glyphs in the font
317
+ """
318
+ gs = font.getGlyphSet(False)
319
+ pen = fontTools.pens.boundsPen.BoundsPen(gs)
320
+ for name in gs.keys():
321
+ gs[name].draw(pen)
322
+ return pen.bounds or (0, 0, 0, 0)
323
+
324
+
325
+ def _generate_charstrings(font):
326
+ """
327
+ Transform font glyphs into CharStrings
328
+
329
+ Helper function for _font_to_ps_type42.
330
+
331
+ Parameters
332
+ ----------
333
+ font : fontTools.ttLib.ttFont.TTFont
334
+ The font
335
+
336
+ Returns
337
+ -------
338
+ str
339
+ A definition of the CharStrings dictionary in PostScript
340
+ """
341
+ go = font.getGlyphOrder()
342
+ s = f'/CharStrings {len(go)} dict dup begin\n'
343
+ for i, name in enumerate(go):
344
+ s += f'/{name} {i} def\n'
345
+ s += 'end readonly def'
346
+ return s
347
+
348
+
349
+ def _generate_sfnts(fontdata, font, breakpoints):
350
+ """
351
+ Transform font data into PostScript sfnts format.
352
+
353
+ Helper function for _font_to_ps_type42.
354
+
355
+ Parameters
356
+ ----------
357
+ fontdata : bytes
358
+ The raw data of the font
359
+ font : fontTools.ttLib.ttFont.TTFont
360
+ The fontTools font object
361
+ breakpoints : list
362
+ Sorted offsets of possible breakpoints
363
+
364
+ Returns
365
+ -------
366
+ str
367
+ The sfnts array for the font definition, consisting
368
+ of hex-encoded strings in PostScript format
369
+ """
370
+ s = '/sfnts['
371
+ pos = 0
372
+ while pos < len(fontdata):
373
+ i = bisect.bisect_left(breakpoints, pos + 65534)
374
+ newpos = breakpoints[i-1]
375
+ if newpos <= pos:
376
+ # have to accept a larger string
377
+ newpos = breakpoints[-1]
378
+ s += f'<{fontdata[pos:newpos].hex()}00>' # Always NUL terminate.
379
+ pos = newpos
380
+ s += ']def'
381
+ return '\n'.join(s[i:i+100] for i in range(0, len(s), 100))
382
+
383
+
384
+ def _log_if_debug_on(meth):
385
+ """
386
+ Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
387
+ if the global flag `debugPS` is set.
388
+ """
389
+ @functools.wraps(meth)
390
+ def wrapper(self, *args, **kwargs):
391
+ if debugPS:
392
+ self._pswriter.write(f"% {meth.__name__}\n")
393
+ return meth(self, *args, **kwargs)
394
+
395
+ return wrapper
396
+
397
+
398
+ class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
399
+ """
400
+ The renderer handles all the drawing primitives using a graphics
401
+ context instance that controls the colors/styles.
402
+ """
403
+
404
+ _afm_font_dir = cbook._get_data_path("fonts/afm")
405
+ _use_afm_rc_name = "ps.useafm"
406
+
407
+ def __init__(self, width, height, pswriter, imagedpi=72):
408
+ # Although postscript itself is dpi independent, we need to inform the
409
+ # image code about a requested dpi to generate high resolution images
410
+ # and them scale them before embedding them.
411
+ super().__init__(width, height)
412
+ self._pswriter = pswriter
413
+ if mpl.rcParams['text.usetex']:
414
+ self.textcnt = 0
415
+ self.psfrag = []
416
+ self.imagedpi = imagedpi
417
+
418
+ # current renderer state (None=uninitialised)
419
+ self.color = None
420
+ self.linewidth = None
421
+ self.linejoin = None
422
+ self.linecap = None
423
+ self.linedash = None
424
+ self.fontname = None
425
+ self.fontsize = None
426
+ self._hatches = {}
427
+ self.image_magnification = imagedpi / 72
428
+ self._clip_paths = {}
429
+ self._path_collection_id = 0
430
+
431
+ self._character_tracker = _backend_pdf_ps.CharacterTracker()
432
+ self._logwarn_once = functools.cache(_log.warning)
433
+
434
+ def _is_transparent(self, rgb_or_rgba):
435
+ if rgb_or_rgba is None:
436
+ return True # Consistent with rgbFace semantics.
437
+ elif len(rgb_or_rgba) == 4:
438
+ if rgb_or_rgba[3] == 0:
439
+ return True
440
+ if rgb_or_rgba[3] != 1:
441
+ self._logwarn_once(
442
+ "The PostScript backend does not support transparency; "
443
+ "partially transparent artists will be rendered opaque.")
444
+ return False
445
+ else: # len() == 3.
446
+ return False
447
+
448
+ def set_color(self, r, g, b, store=True):
449
+ if (r, g, b) != self.color:
450
+ self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
451
+ if r == g == b else
452
+ f"{_nums_to_str(r, g, b)} setrgbcolor\n")
453
+ if store:
454
+ self.color = (r, g, b)
455
+
456
+ def set_linewidth(self, linewidth, store=True):
457
+ linewidth = float(linewidth)
458
+ if linewidth != self.linewidth:
459
+ self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
460
+ if store:
461
+ self.linewidth = linewidth
462
+
463
+ @staticmethod
464
+ def _linejoin_cmd(linejoin):
465
+ # Support for directly passing integer values is for backcompat.
466
+ linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
467
+ linejoin]
468
+ return f"{linejoin:d} setlinejoin\n"
469
+
470
+ def set_linejoin(self, linejoin, store=True):
471
+ if linejoin != self.linejoin:
472
+ self._pswriter.write(self._linejoin_cmd(linejoin))
473
+ if store:
474
+ self.linejoin = linejoin
475
+
476
+ @staticmethod
477
+ def _linecap_cmd(linecap):
478
+ # Support for directly passing integer values is for backcompat.
479
+ linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
480
+ linecap]
481
+ return f"{linecap:d} setlinecap\n"
482
+
483
+ def set_linecap(self, linecap, store=True):
484
+ if linecap != self.linecap:
485
+ self._pswriter.write(self._linecap_cmd(linecap))
486
+ if store:
487
+ self.linecap = linecap
488
+
489
+ def set_linedash(self, offset, seq, store=True):
490
+ if self.linedash is not None:
491
+ oldo, oldseq = self.linedash
492
+ if np.array_equal(seq, oldseq) and oldo == offset:
493
+ return
494
+
495
+ self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
496
+ if seq is not None and len(seq) else
497
+ "[] 0 setdash\n")
498
+ if store:
499
+ self.linedash = (offset, seq)
500
+
501
+ def set_font(self, fontname, fontsize, store=True):
502
+ if (fontname, fontsize) != (self.fontname, self.fontsize):
503
+ self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
504
+ if store:
505
+ self.fontname = fontname
506
+ self.fontsize = fontsize
507
+
508
+ def create_hatch(self, hatch, linewidth):
509
+ sidelen = 72
510
+ if hatch in self._hatches:
511
+ return self._hatches[hatch]
512
+ name = 'H%d' % len(self._hatches)
513
+ pageheight = self.height * 72
514
+ self._pswriter.write(f"""\
515
+ << /PatternType 1
516
+ /PaintType 2
517
+ /TilingType 2
518
+ /BBox[0 0 {sidelen:d} {sidelen:d}]
519
+ /XStep {sidelen:d}
520
+ /YStep {sidelen:d}
521
+
522
+ /PaintProc {{
523
+ pop
524
+ {linewidth:g} setlinewidth
525
+ {self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
526
+ gsave
527
+ fill
528
+ grestore
529
+ stroke
530
+ }} bind
531
+ >>
532
+ matrix
533
+ 0 {pageheight:g} translate
534
+ makepattern
535
+ /{name} exch def
536
+ """)
537
+ self._hatches[hatch] = name
538
+ return name
539
+
540
+ def get_image_magnification(self):
541
+ """
542
+ Get the factor by which to magnify images passed to draw_image.
543
+ Allows a backend to have images at a different resolution to other
544
+ artists.
545
+ """
546
+ return self.image_magnification
547
+
548
+ def _convert_path(self, path, transform, clip=False, simplify=None):
549
+ if clip:
550
+ clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
551
+ else:
552
+ clip = None
553
+ return _path.convert_to_string(
554
+ path, transform, clip, simplify, None,
555
+ 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
556
+
557
+ def _get_clip_cmd(self, gc):
558
+ clip = []
559
+ rect = gc.get_clip_rectangle()
560
+ if rect is not None:
561
+ clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
562
+ path, trf = gc.get_clip_path()
563
+ if path is not None:
564
+ key = (path, id(trf))
565
+ custom_clip_cmd = self._clip_paths.get(key)
566
+ if custom_clip_cmd is None:
567
+ custom_clip_cmd = "c%d" % len(self._clip_paths)
568
+ self._pswriter.write(f"""\
569
+ /{custom_clip_cmd} {{
570
+ {self._convert_path(path, trf, simplify=False)}
571
+ clip
572
+ newpath
573
+ }} bind def
574
+ """)
575
+ self._clip_paths[key] = custom_clip_cmd
576
+ clip.append(f"{custom_clip_cmd}\n")
577
+ return "".join(clip)
578
+
579
+ @_log_if_debug_on
580
+ def draw_image(self, gc, x, y, im, transform=None):
581
+ # docstring inherited
582
+
583
+ h, w = im.shape[:2]
584
+ imagecmd = "false 3 colorimage"
585
+ data = im[::-1, :, :3] # Vertically flipped rgb values.
586
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
587
+
588
+ if transform is None:
589
+ matrix = "1 0 0 1 0 0"
590
+ xscale = w / self.image_magnification
591
+ yscale = h / self.image_magnification
592
+ else:
593
+ matrix = " ".join(map(str, transform.frozen().to_values()))
594
+ xscale = 1.0
595
+ yscale = 1.0
596
+
597
+ self._pswriter.write(f"""\
598
+ gsave
599
+ {self._get_clip_cmd(gc)}
600
+ {x:g} {y:g} translate
601
+ [{matrix}] concat
602
+ {xscale:g} {yscale:g} scale
603
+ /DataString {w:d} string def
604
+ {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
605
+ {{
606
+ currentfile DataString readhexstring pop
607
+ }} bind {imagecmd}
608
+ {hexdata}
609
+ grestore
610
+ """)
611
+
612
+ @_log_if_debug_on
613
+ def draw_path(self, gc, path, transform, rgbFace=None):
614
+ # docstring inherited
615
+ clip = rgbFace is None and gc.get_hatch_path() is None
616
+ simplify = path.should_simplify and clip
617
+ ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
618
+ self._draw_ps(ps, gc, rgbFace)
619
+
620
+ @_log_if_debug_on
621
+ def draw_markers(
622
+ self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
623
+ # docstring inherited
624
+
625
+ ps_color = (
626
+ None
627
+ if self._is_transparent(rgbFace)
628
+ else f'{_nums_to_str(rgbFace[0])} setgray'
629
+ if rgbFace[0] == rgbFace[1] == rgbFace[2]
630
+ else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
631
+
632
+ # construct the generic marker command:
633
+
634
+ # don't want the translate to be global
635
+ ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
636
+
637
+ lw = gc.get_linewidth()
638
+ alpha = (gc.get_alpha()
639
+ if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
640
+ else gc.get_rgb()[3])
641
+ stroke = lw > 0 and alpha > 0
642
+ if stroke:
643
+ ps_cmd.append('%.1f setlinewidth' % lw)
644
+ ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
645
+ ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
646
+
647
+ ps_cmd.append(self._convert_path(marker_path, marker_trans,
648
+ simplify=False))
649
+
650
+ if rgbFace:
651
+ if stroke:
652
+ ps_cmd.append('gsave')
653
+ if ps_color:
654
+ ps_cmd.extend([ps_color, 'fill'])
655
+ if stroke:
656
+ ps_cmd.append('grestore')
657
+
658
+ if stroke:
659
+ ps_cmd.append('stroke')
660
+ ps_cmd.extend(['grestore', '} bind def'])
661
+
662
+ for vertices, code in path.iter_segments(
663
+ trans,
664
+ clip=(0, 0, self.width*72, self.height*72),
665
+ simplify=False):
666
+ if len(vertices):
667
+ x, y = vertices[-2:]
668
+ ps_cmd.append(f"{x:g} {y:g} o")
669
+
670
+ ps = '\n'.join(ps_cmd)
671
+ self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
672
+
673
+ @_log_if_debug_on
674
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
675
+ offsets, offset_trans, facecolors, edgecolors,
676
+ linewidths, linestyles, antialiaseds, urls,
677
+ offset_position):
678
+ # Is the optimization worth it? Rough calculation:
679
+ # cost of emitting a path in-line is
680
+ # (len_path + 2) * uses_per_path
681
+ # cost of definition+use is
682
+ # (len_path + 3) + 3 * uses_per_path
683
+ len_path = len(paths[0].vertices) if len(paths) > 0 else 0
684
+ uses_per_path = self._iter_collection_uses_per_path(
685
+ paths, all_transforms, offsets, facecolors, edgecolors)
686
+ should_do_optimization = \
687
+ len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
688
+ if not should_do_optimization:
689
+ return RendererBase.draw_path_collection(
690
+ self, gc, master_transform, paths, all_transforms,
691
+ offsets, offset_trans, facecolors, edgecolors,
692
+ linewidths, linestyles, antialiaseds, urls,
693
+ offset_position)
694
+
695
+ path_codes = []
696
+ for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
697
+ master_transform, paths, all_transforms)):
698
+ name = 'p%d_%d' % (self._path_collection_id, i)
699
+ path_bytes = self._convert_path(path, transform, simplify=False)
700
+ self._pswriter.write(f"""\
701
+ /{name} {{
702
+ newpath
703
+ translate
704
+ {path_bytes}
705
+ }} bind def
706
+ """)
707
+ path_codes.append(name)
708
+
709
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
710
+ gc, path_codes, offsets, offset_trans,
711
+ facecolors, edgecolors, linewidths, linestyles,
712
+ antialiaseds, urls, offset_position):
713
+ ps = f"{xo:g} {yo:g} {path_id}"
714
+ self._draw_ps(ps, gc0, rgbFace)
715
+
716
+ self._path_collection_id += 1
717
+
718
+ @_log_if_debug_on
719
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
720
+ # docstring inherited
721
+ if self._is_transparent(gc.get_rgb()):
722
+ return # Special handling for fully transparent.
723
+
724
+ if not hasattr(self, "psfrag"):
725
+ self._logwarn_once(
726
+ "The PS backend determines usetex status solely based on "
727
+ "rcParams['text.usetex'] and does not support having "
728
+ "usetex=True only for some elements; this element will thus "
729
+ "be rendered as if usetex=False.")
730
+ self.draw_text(gc, x, y, s, prop, angle, False, mtext)
731
+ return
732
+
733
+ w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
734
+ fontsize = prop.get_size_in_points()
735
+ thetext = 'psmarker%d' % self.textcnt
736
+ color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
737
+ fontcmd = {'sans-serif': r'{\sffamily %s}',
738
+ 'monospace': r'{\ttfamily %s}'}.get(
739
+ mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
740
+ s = fontcmd % s
741
+ tex = r'\color[rgb]{%s} %s' % (color, s)
742
+
743
+ # Stick to bottom-left alignment, so subtract descent from the text-normal
744
+ # direction since text is normally positioned by its baseline.
745
+ rangle = np.radians(angle + 90)
746
+ pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
747
+ self.psfrag.append(
748
+ r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
749
+ thetext, angle, fontsize, fontsize*1.25, tex))
750
+
751
+ self._pswriter.write(f"""\
752
+ gsave
753
+ {pos} moveto
754
+ ({thetext})
755
+ show
756
+ grestore
757
+ """)
758
+ self.textcnt += 1
759
+
760
+ @_log_if_debug_on
761
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
762
+ # docstring inherited
763
+
764
+ if self._is_transparent(gc.get_rgb()):
765
+ return # Special handling for fully transparent.
766
+
767
+ if ismath == 'TeX':
768
+ return self.draw_tex(gc, x, y, s, prop, angle)
769
+
770
+ if ismath:
771
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
772
+
773
+ stream = [] # list of (ps_name, x, char_name)
774
+
775
+ if mpl.rcParams['ps.useafm']:
776
+ font = self._get_font_afm(prop)
777
+ ps_name = (font.postscript_name.encode("ascii", "replace")
778
+ .decode("ascii"))
779
+ scale = 0.001 * prop.get_size_in_points()
780
+ thisx = 0
781
+ last_name = None # kerns returns 0 for None.
782
+ for c in s:
783
+ name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
784
+ try:
785
+ width = font.get_width_from_char_name(name)
786
+ except KeyError:
787
+ name = 'question'
788
+ width = font.get_width_char('?')
789
+ kern = font.get_kern_dist_from_name(last_name, name)
790
+ last_name = name
791
+ thisx += kern * scale
792
+ stream.append((ps_name, thisx, name))
793
+ thisx += width * scale
794
+
795
+ else:
796
+ font = self._get_font_ttf(prop)
797
+ self._character_tracker.track(font, s)
798
+ for item in _text_helpers.layout(s, font):
799
+ ps_name = (item.ft_object.postscript_name
800
+ .encode("ascii", "replace").decode("ascii"))
801
+ glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
802
+ stream.append((ps_name, item.x, glyph_name))
803
+ self.set_color(*gc.get_rgb())
804
+
805
+ for ps_name, group in itertools. \
806
+ groupby(stream, lambda entry: entry[0]):
807
+ self.set_font(ps_name, prop.get_size_in_points(), False)
808
+ thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
809
+ for _, x, name in group)
810
+ self._pswriter.write(f"""\
811
+ gsave
812
+ {self._get_clip_cmd(gc)}
813
+ {x:g} {y:g} translate
814
+ {angle:g} rotate
815
+ {thetext}
816
+ grestore
817
+ """)
818
+
819
+ @_log_if_debug_on
820
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
821
+ """Draw the math text using matplotlib.mathtext."""
822
+ width, height, descent, glyphs, rects = \
823
+ self._text2path.mathtext_parser.parse(s, 72, prop)
824
+ self.set_color(*gc.get_rgb())
825
+ self._pswriter.write(
826
+ f"gsave\n"
827
+ f"{x:g} {y:g} translate\n"
828
+ f"{angle:g} rotate\n")
829
+ lastfont = None
830
+ for font, fontsize, num, ox, oy in glyphs:
831
+ self._character_tracker.track_glyph(font, num)
832
+ if (font.postscript_name, fontsize) != lastfont:
833
+ lastfont = font.postscript_name, fontsize
834
+ self._pswriter.write(
835
+ f"/{font.postscript_name} {fontsize} selectfont\n")
836
+ glyph_name = (
837
+ font.get_name_char(chr(num)) if isinstance(font, AFM) else
838
+ font.get_glyph_name(font.get_char_index(num)))
839
+ self._pswriter.write(
840
+ f"{ox:g} {oy:g} moveto\n"
841
+ f"/{glyph_name} glyphshow\n")
842
+ for ox, oy, w, h in rects:
843
+ self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
844
+ self._pswriter.write("grestore\n")
845
+
846
+ @_log_if_debug_on
847
+ def draw_gouraud_triangles(self, gc, points, colors, trans):
848
+ assert len(points) == len(colors)
849
+ if len(points) == 0:
850
+ return
851
+ assert points.ndim == 3
852
+ assert points.shape[1] == 3
853
+ assert points.shape[2] == 2
854
+ assert colors.ndim == 3
855
+ assert colors.shape[1] == 3
856
+ assert colors.shape[2] == 4
857
+
858
+ shape = points.shape
859
+ flat_points = points.reshape((shape[0] * shape[1], 2))
860
+ flat_points = trans.transform(flat_points)
861
+ flat_colors = colors.reshape((shape[0] * shape[1], 4))
862
+ points_min = np.min(flat_points, axis=0) - (1 << 12)
863
+ points_max = np.max(flat_points, axis=0) + (1 << 12)
864
+ factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
865
+
866
+ xmin, ymin = points_min
867
+ xmax, ymax = points_max
868
+
869
+ data = np.empty(
870
+ shape[0] * shape[1],
871
+ dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
872
+ data['flags'] = 0
873
+ data['points'] = (flat_points - points_min) * factor
874
+ data['colors'] = flat_colors[:, :3] * 255.0
875
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
876
+
877
+ self._pswriter.write(f"""\
878
+ gsave
879
+ << /ShadingType 4
880
+ /ColorSpace [/DeviceRGB]
881
+ /BitsPerCoordinate 32
882
+ /BitsPerComponent 8
883
+ /BitsPerFlag 8
884
+ /AntiAlias true
885
+ /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
886
+ /DataSource <
887
+ {hexdata}
888
+ >
889
+ >>
890
+ shfill
891
+ grestore
892
+ """)
893
+
894
+ def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
895
+ """
896
+ Emit the PostScript snippet *ps* with all the attributes from *gc*
897
+ applied. *ps* must consist of PostScript commands to construct a path.
898
+
899
+ The *fill* and/or *stroke* kwargs can be set to False if the *ps*
900
+ string already includes filling and/or stroking, in which case
901
+ `_draw_ps` is just supplying properties and clipping.
902
+ """
903
+ write = self._pswriter.write
904
+ mightstroke = (gc.get_linewidth() > 0
905
+ and not self._is_transparent(gc.get_rgb()))
906
+ if not mightstroke:
907
+ stroke = False
908
+ if self._is_transparent(rgbFace):
909
+ fill = False
910
+ hatch = gc.get_hatch()
911
+
912
+ if mightstroke:
913
+ self.set_linewidth(gc.get_linewidth())
914
+ self.set_linejoin(gc.get_joinstyle())
915
+ self.set_linecap(gc.get_capstyle())
916
+ self.set_linedash(*gc.get_dashes())
917
+ if mightstroke or hatch:
918
+ self.set_color(*gc.get_rgb()[:3])
919
+ write('gsave\n')
920
+
921
+ write(self._get_clip_cmd(gc))
922
+
923
+ write(ps.strip())
924
+ write("\n")
925
+
926
+ if fill:
927
+ if stroke or hatch:
928
+ write("gsave\n")
929
+ self.set_color(*rgbFace[:3], store=False)
930
+ write("fill\n")
931
+ if stroke or hatch:
932
+ write("grestore\n")
933
+
934
+ if hatch:
935
+ hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth())
936
+ write("gsave\n")
937
+ write(_nums_to_str(*gc.get_hatch_color()[:3]))
938
+ write(f" {hatch_name} setpattern fill grestore\n")
939
+
940
+ if stroke:
941
+ write("stroke\n")
942
+
943
+ write("grestore\n")
944
+
945
+
946
+ class _Orientation(Enum):
947
+ portrait, landscape = range(2)
948
+
949
+ def swap_if_landscape(self, shape):
950
+ return shape[::-1] if self.name == "landscape" else shape
951
+
952
+
953
+ class FigureCanvasPS(FigureCanvasBase):
954
+ fixed_dpi = 72
955
+ filetypes = {'ps': 'Postscript',
956
+ 'eps': 'Encapsulated Postscript'}
957
+
958
+ def get_default_filetype(self):
959
+ return 'ps'
960
+
961
+ def _print_ps(
962
+ self, fmt, outfile, *,
963
+ metadata=None, papertype=None, orientation='portrait',
964
+ bbox_inches_restore=None, **kwargs):
965
+
966
+ dpi = self.figure.dpi
967
+ self.figure.dpi = 72 # Override the dpi kwarg
968
+
969
+ dsc_comments = {}
970
+ if isinstance(outfile, (str, os.PathLike)):
971
+ filename = pathlib.Path(outfile).name
972
+ dsc_comments["Title"] = \
973
+ filename.encode("ascii", "replace").decode("ascii")
974
+ dsc_comments["Creator"] = (metadata or {}).get(
975
+ "Creator",
976
+ f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
977
+ # See https://reproducible-builds.org/specs/source-date-epoch/
978
+ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
979
+ dsc_comments["CreationDate"] = (
980
+ datetime.datetime.fromtimestamp(
981
+ int(source_date_epoch),
982
+ datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
983
+ if source_date_epoch
984
+ else time.ctime())
985
+ dsc_comments = "\n".join(
986
+ f"%%{k}: {v}" for k, v in dsc_comments.items())
987
+
988
+ if papertype is None:
989
+ papertype = mpl.rcParams['ps.papersize']
990
+ papertype = papertype.lower()
991
+ _api.check_in_list(['figure', *papersize], papertype=papertype)
992
+
993
+ orientation = _api.check_getitem(
994
+ _Orientation, orientation=orientation.lower())
995
+
996
+ printer = (self._print_figure_tex
997
+ if mpl.rcParams['text.usetex'] else
998
+ self._print_figure)
999
+ printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
1000
+ orientation=orientation, papertype=papertype,
1001
+ bbox_inches_restore=bbox_inches_restore, **kwargs)
1002
+
1003
+ def _print_figure(
1004
+ self, fmt, outfile, *,
1005
+ dpi, dsc_comments, orientation, papertype,
1006
+ bbox_inches_restore=None):
1007
+ """
1008
+ Render the figure to a filesystem path or a file-like object.
1009
+
1010
+ Parameters are as for `.print_figure`, except that *dsc_comments* is a
1011
+ string containing Document Structuring Convention comments,
1012
+ generated from the *metadata* parameter to `.print_figure`.
1013
+ """
1014
+ is_eps = fmt == 'eps'
1015
+ if not (isinstance(outfile, (str, os.PathLike))
1016
+ or is_writable_file_like(outfile)):
1017
+ raise ValueError("outfile must be a path or a file-like object")
1018
+
1019
+ # find the appropriate papertype
1020
+ width, height = self.figure.get_size_inches()
1021
+ if is_eps or papertype == 'figure':
1022
+ paper_width, paper_height = width, height
1023
+ else:
1024
+ paper_width, paper_height = orientation.swap_if_landscape(
1025
+ papersize[papertype])
1026
+
1027
+ # center the figure on the paper
1028
+ xo = 72 * 0.5 * (paper_width - width)
1029
+ yo = 72 * 0.5 * (paper_height - height)
1030
+
1031
+ llx = xo
1032
+ lly = yo
1033
+ urx = llx + self.figure.bbox.width
1034
+ ury = lly + self.figure.bbox.height
1035
+ rotation = 0
1036
+ if orientation is _Orientation.landscape:
1037
+ llx, lly, urx, ury = lly, llx, ury, urx
1038
+ xo, yo = 72 * paper_height - yo, xo
1039
+ rotation = 90
1040
+ bbox = (llx, lly, urx, ury)
1041
+
1042
+ self._pswriter = StringIO()
1043
+
1044
+ # mixed mode rendering
1045
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
1046
+ renderer = MixedModeRenderer(
1047
+ self.figure, width, height, dpi, ps_renderer,
1048
+ bbox_inches_restore=bbox_inches_restore)
1049
+
1050
+ self.figure.draw(renderer)
1051
+
1052
+ def print_figure_impl(fh):
1053
+ # write the PostScript headers
1054
+ if is_eps:
1055
+ print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
1056
+ else:
1057
+ print("%!PS-Adobe-3.0", file=fh)
1058
+ if papertype != 'figure':
1059
+ print(f"%%DocumentPaperSizes: {papertype}", file=fh)
1060
+ print("%%Pages: 1", file=fh)
1061
+ print(f"%%LanguageLevel: 3\n"
1062
+ f"{dsc_comments}\n"
1063
+ f"%%Orientation: {orientation.name}\n"
1064
+ f"{_get_bbox_header(bbox)}\n"
1065
+ f"%%EndComments\n",
1066
+ end="", file=fh)
1067
+
1068
+ Ndict = len(_psDefs)
1069
+ print("%%BeginProlog", file=fh)
1070
+ if not mpl.rcParams['ps.useafm']:
1071
+ Ndict += len(ps_renderer._character_tracker.used)
1072
+ print("/mpldict %d dict def" % Ndict, file=fh)
1073
+ print("mpldict begin", file=fh)
1074
+ print("\n".join(_psDefs), file=fh)
1075
+ if not mpl.rcParams['ps.useafm']:
1076
+ for font_path, chars \
1077
+ in ps_renderer._character_tracker.used.items():
1078
+ if not chars:
1079
+ continue
1080
+ fonttype = mpl.rcParams['ps.fonttype']
1081
+ # Can't use more than 255 chars from a single Type 3 font.
1082
+ if len(chars) > 255:
1083
+ fonttype = 42
1084
+ fh.flush()
1085
+ if fonttype == 3:
1086
+ fh.write(_font_to_ps_type3(font_path, chars))
1087
+ else: # Type 42 only.
1088
+ _font_to_ps_type42(font_path, chars, fh)
1089
+ print("end", file=fh)
1090
+ print("%%EndProlog", file=fh)
1091
+
1092
+ if not is_eps:
1093
+ print("%%Page: 1 1", file=fh)
1094
+ print("mpldict begin", file=fh)
1095
+
1096
+ print("%s translate" % _nums_to_str(xo, yo), file=fh)
1097
+ if rotation:
1098
+ print("%d rotate" % rotation, file=fh)
1099
+ print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
1100
+
1101
+ # write the figure
1102
+ print(self._pswriter.getvalue(), file=fh)
1103
+
1104
+ # write the trailer
1105
+ print("end", file=fh)
1106
+ print("showpage", file=fh)
1107
+ if not is_eps:
1108
+ print("%%EOF", file=fh)
1109
+ fh.flush()
1110
+
1111
+ if mpl.rcParams['ps.usedistiller']:
1112
+ # We are going to use an external program to process the output.
1113
+ # Write to a temporary file.
1114
+ with TemporaryDirectory() as tmpdir:
1115
+ tmpfile = os.path.join(tmpdir, "tmp.ps")
1116
+ with open(tmpfile, 'w', encoding='latin-1') as fh:
1117
+ print_figure_impl(fh)
1118
+ if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
1119
+ _try_distill(gs_distill,
1120
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
1121
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
1122
+ _try_distill(xpdf_distill,
1123
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
1124
+ _move_path_to_path_or_stream(tmpfile, outfile)
1125
+
1126
+ else: # Write directly to outfile.
1127
+ with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
1128
+ if not file_requires_unicode(file):
1129
+ file = codecs.getwriter("latin-1")(file)
1130
+ print_figure_impl(file)
1131
+
1132
+ def _print_figure_tex(
1133
+ self, fmt, outfile, *,
1134
+ dpi, dsc_comments, orientation, papertype,
1135
+ bbox_inches_restore=None):
1136
+ """
1137
+ If :rc:`text.usetex` is True, a temporary pair of tex/eps files
1138
+ are created to allow tex to manage the text layout via the PSFrags
1139
+ package. These files are processed to yield the final ps or eps file.
1140
+
1141
+ The rest of the behavior is as for `._print_figure`.
1142
+ """
1143
+ is_eps = fmt == 'eps'
1144
+
1145
+ width, height = self.figure.get_size_inches()
1146
+ xo = 0
1147
+ yo = 0
1148
+
1149
+ llx = xo
1150
+ lly = yo
1151
+ urx = llx + self.figure.bbox.width
1152
+ ury = lly + self.figure.bbox.height
1153
+ bbox = (llx, lly, urx, ury)
1154
+
1155
+ self._pswriter = StringIO()
1156
+
1157
+ # mixed mode rendering
1158
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
1159
+ renderer = MixedModeRenderer(self.figure,
1160
+ width, height, dpi, ps_renderer,
1161
+ bbox_inches_restore=bbox_inches_restore)
1162
+
1163
+ self.figure.draw(renderer)
1164
+
1165
+ # write to a temp file, we'll move it to outfile when done
1166
+ with TemporaryDirectory() as tmpdir:
1167
+ tmppath = pathlib.Path(tmpdir, "tmp.ps")
1168
+ tmppath.write_text(
1169
+ f"""\
1170
+ %!PS-Adobe-3.0 EPSF-3.0
1171
+ %%LanguageLevel: 3
1172
+ {dsc_comments}
1173
+ {_get_bbox_header(bbox)}
1174
+ %%EndComments
1175
+ %%BeginProlog
1176
+ /mpldict {len(_psDefs)} dict def
1177
+ mpldict begin
1178
+ {"".join(_psDefs)}
1179
+ end
1180
+ %%EndProlog
1181
+ mpldict begin
1182
+ {_nums_to_str(xo, yo)} translate
1183
+ 0 0 {_nums_to_str(width*72, height*72)} rectclip
1184
+ {self._pswriter.getvalue()}
1185
+ end
1186
+ showpage
1187
+ """,
1188
+ encoding="latin-1")
1189
+
1190
+ if orientation is _Orientation.landscape: # now, ready to rotate
1191
+ width, height = height, width
1192
+ bbox = (lly, llx, ury, urx)
1193
+
1194
+ # set the paper size to the figure size if is_eps. The
1195
+ # resulting ps file has the given size with correct bounding
1196
+ # box so that there is no need to call 'pstoeps'
1197
+ if is_eps or papertype == 'figure':
1198
+ paper_width, paper_height = orientation.swap_if_landscape(
1199
+ self.figure.get_size_inches())
1200
+ else:
1201
+ paper_width, paper_height = papersize[papertype]
1202
+
1203
+ psfrag_rotated = _convert_psfrags(
1204
+ tmppath, ps_renderer.psfrag, paper_width, paper_height,
1205
+ orientation.name)
1206
+
1207
+ if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
1208
+ or mpl.rcParams['text.usetex']):
1209
+ _try_distill(gs_distill,
1210
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1211
+ rotated=psfrag_rotated)
1212
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
1213
+ _try_distill(xpdf_distill,
1214
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1215
+ rotated=psfrag_rotated)
1216
+
1217
+ _move_path_to_path_or_stream(tmppath, outfile)
1218
+
1219
+ print_ps = functools.partialmethod(_print_ps, "ps")
1220
+ print_eps = functools.partialmethod(_print_ps, "eps")
1221
+
1222
+ def draw(self):
1223
+ self.figure.draw_without_rendering()
1224
+ return super().draw()
1225
+
1226
+
1227
+ def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
1228
+ """
1229
+ When we want to use the LaTeX backend with postscript, we write PSFrag tags
1230
+ to a temporary postscript file, each one marking a position for LaTeX to
1231
+ render some text. convert_psfrags generates a LaTeX document containing the
1232
+ commands to convert those tags to text. LaTeX/dvips produces the postscript
1233
+ file that includes the actual text.
1234
+ """
1235
+ with mpl.rc_context({
1236
+ "text.latex.preamble":
1237
+ mpl.rcParams["text.latex.preamble"] +
1238
+ mpl.texmanager._usepackage_if_not_loaded("color") +
1239
+ mpl.texmanager._usepackage_if_not_loaded("graphicx") +
1240
+ mpl.texmanager._usepackage_if_not_loaded("psfrag") +
1241
+ r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
1242
+ % {"width": paper_width, "height": paper_height}
1243
+ }):
1244
+ dvifile = TexManager().make_dvi(
1245
+ "\n"
1246
+ r"\begin{figure}""\n"
1247
+ r" \centering\leavevmode""\n"
1248
+ r" %(psfrags)s""\n"
1249
+ r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
1250
+ r"\end{figure}"
1251
+ % {
1252
+ "psfrags": "\n".join(psfrags),
1253
+ "angle": 90 if orientation == 'landscape' else 0,
1254
+ "epsfile": tmppath.resolve().as_posix(),
1255
+ },
1256
+ fontsize=10) # tex's default fontsize.
1257
+
1258
+ with TemporaryDirectory() as tmpdir:
1259
+ psfile = os.path.join(tmpdir, "tmp.ps")
1260
+ cbook._check_and_log_subprocess(
1261
+ ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
1262
+ shutil.move(psfile, tmppath)
1263
+
1264
+ # check if the dvips created a ps in landscape paper. Somehow,
1265
+ # above latex+dvips results in a ps file in a landscape mode for a
1266
+ # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
1267
+ # bounding box of the final output got messed up. We check see if
1268
+ # the generated ps file is in landscape and return this
1269
+ # information. The return value is used in pstoeps step to recover
1270
+ # the correct bounding box. 2010-06-05 JJL
1271
+ with open(tmppath) as fh:
1272
+ psfrag_rotated = "Landscape" in fh.read(1000)
1273
+ return psfrag_rotated
1274
+
1275
+
1276
+ def _try_distill(func, tmppath, *args, **kwargs):
1277
+ try:
1278
+ func(str(tmppath), *args, **kwargs)
1279
+ except mpl.ExecutableNotFoundError as exc:
1280
+ _log.warning("%s. Distillation step skipped.", exc)
1281
+
1282
+
1283
+ def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1284
+ """
1285
+ Use ghostscript's pswrite or epswrite device to distill a file.
1286
+ This yields smaller files without illegal encapsulated postscript
1287
+ operators. The output is low-level, converting text to outlines.
1288
+ """
1289
+
1290
+ if eps:
1291
+ paper_option = ["-dEPSCrop"]
1292
+ elif ptype == "figure":
1293
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1294
+ # corner corresponds with paper size.
1295
+ paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
1296
+ f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
1297
+ else:
1298
+ paper_option = [f"-sPAPERSIZE={ptype}"]
1299
+
1300
+ psfile = tmpfile + '.ps'
1301
+ dpi = mpl.rcParams['ps.distiller.res']
1302
+
1303
+ cbook._check_and_log_subprocess(
1304
+ [mpl._get_executable_info("gs").executable,
1305
+ "-dBATCH", "-dNOPAUSE", "-r%d" % dpi, "-sDEVICE=ps2write",
1306
+ *paper_option, f"-sOutputFile={psfile}", tmpfile],
1307
+ _log)
1308
+
1309
+ os.remove(tmpfile)
1310
+ shutil.move(psfile, tmpfile)
1311
+
1312
+ # While it is best if above steps preserve the original bounding
1313
+ # box, there seem to be cases when it is not. For those cases,
1314
+ # the original bbox can be restored during the pstoeps step.
1315
+
1316
+ if eps:
1317
+ # For some versions of gs, above steps result in a ps file where the
1318
+ # original bbox is no more correct. Do not adjust bbox for now.
1319
+ pstoeps(tmpfile, bbox, rotated=rotated)
1320
+
1321
+
1322
+ def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1323
+ """
1324
+ Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
1325
+ This yields smaller files without illegal encapsulated postscript
1326
+ operators. This distiller is preferred, generating high-level postscript
1327
+ output that treats text as text.
1328
+ """
1329
+ mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
1330
+ mpl._get_executable_info("pdftops")
1331
+
1332
+ if eps:
1333
+ paper_option = ["-dEPSCrop"]
1334
+ elif ptype == "figure":
1335
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1336
+ # corner corresponds with paper size.
1337
+ paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
1338
+ f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
1339
+ else:
1340
+ paper_option = [f"-sPAPERSIZE#{ptype}"]
1341
+
1342
+ with TemporaryDirectory() as tmpdir:
1343
+ tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
1344
+ tmpps = pathlib.Path(tmpdir, "tmp.ps")
1345
+ # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
1346
+ # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
1347
+ cbook._check_and_log_subprocess(
1348
+ ["ps2pdf",
1349
+ "-dAutoFilterColorImages#false",
1350
+ "-dAutoFilterGrayImages#false",
1351
+ "-sAutoRotatePages#None",
1352
+ "-sGrayImageFilter#FlateEncode",
1353
+ "-sColorImageFilter#FlateEncode",
1354
+ *paper_option,
1355
+ tmpfile, tmppdf], _log)
1356
+ cbook._check_and_log_subprocess(
1357
+ ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
1358
+ shutil.move(tmpps, tmpfile)
1359
+ if eps:
1360
+ pstoeps(tmpfile)
1361
+
1362
+
1363
+ @_api.deprecated("3.9")
1364
+ def get_bbox_header(lbrt, rotated=False):
1365
+ """
1366
+ Return a postscript header string for the given bbox lbrt=(l, b, r, t).
1367
+ Optionally, return rotate command.
1368
+ """
1369
+ return _get_bbox_header(lbrt), (_get_rotate_command(lbrt) if rotated else "")
1370
+
1371
+
1372
+ def _get_bbox_header(lbrt):
1373
+ """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t)."""
1374
+ l, b, r, t = lbrt
1375
+ return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n"
1376
+ f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}")
1377
+
1378
+
1379
+ def _get_rotate_command(lbrt):
1380
+ """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t)."""
1381
+ l, b, r, t = lbrt
1382
+ return f"{l+r:.2f} {0:.2f} translate\n90 rotate"
1383
+
1384
+
1385
+ def pstoeps(tmpfile, bbox=None, rotated=False):
1386
+ """
1387
+ Convert the postscript to encapsulated postscript. The bbox of
1388
+ the eps file will be replaced with the given *bbox* argument. If
1389
+ None, original bbox will be used.
1390
+ """
1391
+
1392
+ epsfile = tmpfile + '.eps'
1393
+ with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
1394
+ write = epsh.write
1395
+ # Modify the header:
1396
+ for line in tmph:
1397
+ if line.startswith(b'%!PS'):
1398
+ write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
1399
+ if bbox:
1400
+ write(_get_bbox_header(bbox).encode('ascii') + b'\n')
1401
+ elif line.startswith(b'%%EndComments'):
1402
+ write(line)
1403
+ write(b'%%BeginProlog\n'
1404
+ b'save\n'
1405
+ b'countdictstack\n'
1406
+ b'mark\n'
1407
+ b'newpath\n'
1408
+ b'/showpage {} def\n'
1409
+ b'/setpagedevice {pop} def\n'
1410
+ b'%%EndProlog\n'
1411
+ b'%%Page 1 1\n')
1412
+ if rotated: # The output eps file need to be rotated.
1413
+ write(_get_rotate_command(bbox).encode('ascii') + b'\n')
1414
+ break
1415
+ elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
1416
+ b'%%DocumentMedia', b'%%Pages')):
1417
+ pass
1418
+ else:
1419
+ write(line)
1420
+ # Now rewrite the rest of the file, and modify the trailer.
1421
+ # This is done in a second loop such that the header of the embedded
1422
+ # eps file is not modified.
1423
+ for line in tmph:
1424
+ if line.startswith(b'%%EOF'):
1425
+ write(b'cleartomark\n'
1426
+ b'countdictstack\n'
1427
+ b'exch sub { end } repeat\n'
1428
+ b'restore\n'
1429
+ b'showpage\n'
1430
+ b'%%EOF\n')
1431
+ elif line.startswith(b'%%PageBoundingBox'):
1432
+ pass
1433
+ else:
1434
+ write(line)
1435
+
1436
+ os.remove(tmpfile)
1437
+ shutil.move(epsfile, tmpfile)
1438
+
1439
+
1440
+ FigureManagerPS = FigureManagerBase
1441
+
1442
+
1443
+ # The following Python dictionary psDefs contains the entries for the
1444
+ # PostScript dictionary mpldict. This dictionary implements most of
1445
+ # the matplotlib primitives and some abbreviations.
1446
+ #
1447
+ # References:
1448
+ # https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
1449
+ # http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
1450
+ # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
1451
+ #
1452
+
1453
+ # The usage comments use the notation of the operator summary
1454
+ # in the PostScript Language reference manual.
1455
+ _psDefs = [
1456
+ # name proc *_d* -
1457
+ # Note that this cannot be bound to /d, because when embedding a Type3 font
1458
+ # we may want to define a "d" glyph using "/d{...} d" which would locally
1459
+ # overwrite the definition.
1460
+ "/_d { bind def } bind def",
1461
+ # x y *m* -
1462
+ "/m { moveto } _d",
1463
+ # x y *l* -
1464
+ "/l { lineto } _d",
1465
+ # x y *r* -
1466
+ "/r { rlineto } _d",
1467
+ # x1 y1 x2 y2 x y *c* -
1468
+ "/c { curveto } _d",
1469
+ # *cl* -
1470
+ "/cl { closepath } _d",
1471
+ # *ce* -
1472
+ "/ce { closepath eofill } _d",
1473
+ # wx wy llx lly urx ury *setcachedevice* -
1474
+ "/sc { setcachedevice } _d",
1475
+ ]
1476
+
1477
+
1478
+ @_Backend.export
1479
+ class _BackendPS(_Backend):
1480
+ backend_version = 'Level II'
1481
+ FigureCanvas = FigureCanvasPS
workspace/outputs/audit_venv/lib/python3.11/site-packages/matplotlib/backends/backend_qt.py ADDED
@@ -0,0 +1,1089 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # We return the QSocketNotifier so that the caller holds a reference, and we
173
+ # also explicitly clean it up in handle_sigint(). Without doing both, deletion
174
+ # of the socket notifier can happen prematurely or not at all.
175
+ return sn
176
+
177
+ def handle_sigint(sn):
178
+ sn.deleteLater()
179
+ QtCore.QCoreApplication.sendPostedEvents(sn, QtCore.QEvent.Type.DeferredDelete)
180
+ if hasattr(qapp_or_eventloop, 'closeAllWindows'):
181
+ qapp_or_eventloop.closeAllWindows()
182
+ qapp_or_eventloop.quit()
183
+
184
+ return _allow_interrupt(prepare_notifier, handle_sigint)
185
+
186
+
187
+ class TimerQT(TimerBase):
188
+ """Subclass of `.TimerBase` using QTimer events."""
189
+
190
+ def __init__(self, *args, **kwargs):
191
+ # Create a new timer and connect the timeout() signal to the
192
+ # _on_timer method.
193
+ self._timer = QtCore.QTimer()
194
+ self._timer.timeout.connect(self._on_timer)
195
+ super().__init__(*args, **kwargs)
196
+
197
+ def __del__(self):
198
+ # The check for deletedness is needed to avoid an error at animation
199
+ # shutdown with PySide2.
200
+ if not _isdeleted(self._timer):
201
+ self._timer_stop()
202
+
203
+ def _timer_set_single_shot(self):
204
+ self._timer.setSingleShot(self._single)
205
+
206
+ def _timer_set_interval(self):
207
+ self._timer.setInterval(self._interval)
208
+
209
+ def _timer_start(self):
210
+ self._timer.start()
211
+
212
+ def _timer_stop(self):
213
+ self._timer.stop()
214
+
215
+
216
+ class FigureCanvasQT(FigureCanvasBase, QtWidgets.QWidget):
217
+ required_interactive_framework = "qt"
218
+ _timer_cls = TimerQT
219
+ manager_class = _api.classproperty(lambda cls: FigureManagerQT)
220
+
221
+ buttond = {
222
+ getattr(QtCore.Qt.MouseButton, k): v for k, v in [
223
+ ("LeftButton", MouseButton.LEFT),
224
+ ("RightButton", MouseButton.RIGHT),
225
+ ("MiddleButton", MouseButton.MIDDLE),
226
+ ("XButton1", MouseButton.BACK),
227
+ ("XButton2", MouseButton.FORWARD),
228
+ ]
229
+ }
230
+
231
+ def __init__(self, figure=None):
232
+ _create_qApp()
233
+ super().__init__(figure=figure)
234
+
235
+ self._draw_pending = False
236
+ self._is_drawing = False
237
+ self._draw_rect_callback = lambda painter: None
238
+ self._in_resize_event = False
239
+
240
+ self.setAttribute(QtCore.Qt.WidgetAttribute.WA_OpaquePaintEvent)
241
+ self.setMouseTracking(True)
242
+ self.resize(*self.get_width_height())
243
+
244
+ palette = QtGui.QPalette(QtGui.QColor("white"))
245
+ self.setPalette(palette)
246
+
247
+ @QtCore.Slot()
248
+ def _update_pixel_ratio(self):
249
+ if self._set_device_pixel_ratio(
250
+ self.devicePixelRatioF() or 1): # rarely, devicePixelRatioF=0
251
+ # The easiest way to resize the canvas is to emit a resizeEvent
252
+ # since we implement all the logic for resizing the canvas for
253
+ # that event.
254
+ event = QtGui.QResizeEvent(self.size(), self.size())
255
+ self.resizeEvent(event)
256
+
257
+ @QtCore.Slot(QtGui.QScreen)
258
+ def _update_screen(self, screen):
259
+ # Handler for changes to a window's attached screen.
260
+ self._update_pixel_ratio()
261
+ if screen is not None:
262
+ screen.physicalDotsPerInchChanged.connect(self._update_pixel_ratio)
263
+ screen.logicalDotsPerInchChanged.connect(self._update_pixel_ratio)
264
+
265
+ def eventFilter(self, source, event):
266
+ if event.type() == QtCore.QEvent.Type.DevicePixelRatioChange:
267
+ self._update_pixel_ratio()
268
+ return super().eventFilter(source, event)
269
+
270
+ def showEvent(self, event):
271
+ # Set up correct pixel ratio, and connect to any signal changes for it,
272
+ # once the window is shown (and thus has these attributes).
273
+ window = self.window().windowHandle()
274
+ current_version = tuple(int(x) for x in QtCore.qVersion().split('.', 2)[:2])
275
+ if current_version >= (6, 6):
276
+ self._update_pixel_ratio()
277
+ window.installEventFilter(self)
278
+ else:
279
+ window.screenChanged.connect(self._update_screen)
280
+ self._update_screen(window.screen())
281
+
282
+ def set_cursor(self, cursor):
283
+ # docstring inherited
284
+ self.setCursor(_api.check_getitem(cursord, cursor=cursor))
285
+
286
+ def mouseEventCoords(self, pos=None):
287
+ """
288
+ Calculate mouse coordinates in physical pixels.
289
+
290
+ Qt uses logical pixels, but the figure is scaled to physical
291
+ pixels for rendering. Transform to physical pixels so that
292
+ all of the down-stream transforms work as expected.
293
+
294
+ Also, the origin is different and needs to be corrected.
295
+ """
296
+ if pos is None:
297
+ pos = self.mapFromGlobal(QtGui.QCursor.pos())
298
+ elif hasattr(pos, "position"): # qt6 QtGui.QEvent
299
+ pos = pos.position()
300
+ elif hasattr(pos, "pos"): # qt5 QtCore.QEvent
301
+ pos = pos.pos()
302
+ # (otherwise, it's already a QPoint)
303
+ x = pos.x()
304
+ # flip y so y=0 is bottom of canvas
305
+ y = self.figure.bbox.height / self.device_pixel_ratio - pos.y()
306
+ return x * self.device_pixel_ratio, y * self.device_pixel_ratio
307
+
308
+ def enterEvent(self, event):
309
+ # Force querying of the modifiers, as the cached modifier state can
310
+ # have been invalidated while the window was out of focus.
311
+ mods = QtWidgets.QApplication.instance().queryKeyboardModifiers()
312
+ if self.figure is None:
313
+ return
314
+ LocationEvent("figure_enter_event", self,
315
+ *self.mouseEventCoords(event),
316
+ modifiers=self._mpl_modifiers(mods),
317
+ guiEvent=event)._process()
318
+
319
+ def leaveEvent(self, event):
320
+ QtWidgets.QApplication.restoreOverrideCursor()
321
+ if self.figure is None:
322
+ return
323
+ LocationEvent("figure_leave_event", self,
324
+ *self.mouseEventCoords(),
325
+ modifiers=self._mpl_modifiers(),
326
+ guiEvent=event)._process()
327
+
328
+ def mousePressEvent(self, event):
329
+ button = self.buttond.get(event.button())
330
+ if button is not None and self.figure is not None:
331
+ MouseEvent("button_press_event", self,
332
+ *self.mouseEventCoords(event), button,
333
+ modifiers=self._mpl_modifiers(),
334
+ guiEvent=event)._process()
335
+
336
+ def mouseDoubleClickEvent(self, event):
337
+ button = self.buttond.get(event.button())
338
+ if button is not None and self.figure is not None:
339
+ MouseEvent("button_press_event", self,
340
+ *self.mouseEventCoords(event), button, dblclick=True,
341
+ modifiers=self._mpl_modifiers(),
342
+ guiEvent=event)._process()
343
+
344
+ def mouseMoveEvent(self, event):
345
+ if self.figure is None:
346
+ return
347
+ MouseEvent("motion_notify_event", self,
348
+ *self.mouseEventCoords(event),
349
+ buttons=self._mpl_buttons(event.buttons()),
350
+ modifiers=self._mpl_modifiers(),
351
+ guiEvent=event)._process()
352
+
353
+ def mouseReleaseEvent(self, event):
354
+ button = self.buttond.get(event.button())
355
+ if button is not None and self.figure is not None:
356
+ MouseEvent("button_release_event", self,
357
+ *self.mouseEventCoords(event), button,
358
+ modifiers=self._mpl_modifiers(),
359
+ guiEvent=event)._process()
360
+
361
+ def wheelEvent(self, event):
362
+ # from QWheelEvent::pixelDelta doc: pixelDelta is sometimes not
363
+ # provided (`isNull()`) and is unreliable on X11 ("xcb").
364
+ if (event.pixelDelta().isNull()
365
+ or QtWidgets.QApplication.instance().platformName() == "xcb"):
366
+ steps = event.angleDelta().y() / 120
367
+ else:
368
+ steps = event.pixelDelta().y()
369
+ if steps and self.figure is not None:
370
+ MouseEvent("scroll_event", self,
371
+ *self.mouseEventCoords(event), step=steps,
372
+ modifiers=self._mpl_modifiers(),
373
+ guiEvent=event)._process()
374
+
375
+ def keyPressEvent(self, event):
376
+ key = self._get_key(event)
377
+ if key is not None and self.figure is not None:
378
+ KeyEvent("key_press_event", self,
379
+ key, *self.mouseEventCoords(),
380
+ guiEvent=event)._process()
381
+
382
+ def keyReleaseEvent(self, event):
383
+ key = self._get_key(event)
384
+ if key is not None and self.figure is not None:
385
+ KeyEvent("key_release_event", self,
386
+ key, *self.mouseEventCoords(),
387
+ guiEvent=event)._process()
388
+
389
+ def resizeEvent(self, event):
390
+ if self._in_resize_event: # Prevent PyQt6 recursion
391
+ return
392
+ if self.figure is None:
393
+ return
394
+ self._in_resize_event = True
395
+ try:
396
+ w = event.size().width() * self.device_pixel_ratio
397
+ h = event.size().height() * self.device_pixel_ratio
398
+ dpival = self.figure.dpi
399
+ winch = w / dpival
400
+ hinch = h / dpival
401
+ self.figure.set_size_inches(winch, hinch, forward=False)
402
+ # pass back into Qt to let it finish
403
+ QtWidgets.QWidget.resizeEvent(self, event)
404
+ # emit our resize events
405
+ ResizeEvent("resize_event", self)._process()
406
+ self.draw_idle()
407
+ finally:
408
+ self._in_resize_event = False
409
+
410
+ def sizeHint(self):
411
+ w, h = self.get_width_height()
412
+ return QtCore.QSize(w, h)
413
+
414
+ def minimumSizeHint(self):
415
+ return QtCore.QSize(10, 10)
416
+
417
+ @staticmethod
418
+ def _mpl_buttons(buttons):
419
+ buttons = _to_int(buttons)
420
+ # State *after* press/release.
421
+ return {button for mask, button in FigureCanvasQT.buttond.items()
422
+ if _to_int(mask) & buttons}
423
+
424
+ @staticmethod
425
+ def _mpl_modifiers(modifiers=None, *, exclude=None):
426
+ if modifiers is None:
427
+ modifiers = QtWidgets.QApplication.instance().keyboardModifiers()
428
+ modifiers = _to_int(modifiers)
429
+ # get names of the pressed modifier keys
430
+ # 'control' is named 'control' when a standalone key, but 'ctrl' when a
431
+ # modifier
432
+ # bit twiddling to pick out modifier keys from modifiers bitmask,
433
+ # if exclude is a MODIFIER, it should not be duplicated in mods
434
+ return [SPECIAL_KEYS[key].replace('control', 'ctrl')
435
+ for mask, key in _MODIFIER_KEYS
436
+ if exclude != key and modifiers & mask]
437
+
438
+ def _get_key(self, event):
439
+ event_key = event.key()
440
+ mods = self._mpl_modifiers(exclude=event_key)
441
+ try:
442
+ # for certain keys (enter, left, backspace, etc) use a word for the
443
+ # key, rather than Unicode
444
+ key = SPECIAL_KEYS[event_key]
445
+ except KeyError:
446
+ # Unicode defines code points up to 0x10ffff (sys.maxunicode)
447
+ # QT will use Key_Codes larger than that for keyboard keys that are
448
+ # not Unicode characters (like multimedia keys)
449
+ # skip these
450
+ # if you really want them, you should add them to SPECIAL_KEYS
451
+ if event_key > sys.maxunicode:
452
+ return None
453
+
454
+ key = chr(event_key)
455
+ # qt delivers capitalized letters. fix capitalization
456
+ # note that capslock is ignored
457
+ if 'shift' in mods:
458
+ mods.remove('shift')
459
+ else:
460
+ key = key.lower()
461
+
462
+ return '+'.join(mods + [key])
463
+
464
+ def flush_events(self):
465
+ # docstring inherited
466
+ QtWidgets.QApplication.instance().processEvents()
467
+
468
+ def start_event_loop(self, timeout=0):
469
+ # docstring inherited
470
+ if hasattr(self, "_event_loop") and self._event_loop.isRunning():
471
+ raise RuntimeError("Event loop already running")
472
+ self._event_loop = event_loop = QtCore.QEventLoop()
473
+ if timeout > 0:
474
+ _ = QtCore.QTimer.singleShot(int(timeout * 1000), event_loop.quit)
475
+
476
+ with _allow_interrupt_qt(event_loop):
477
+ qt_compat._exec(event_loop)
478
+
479
+ def stop_event_loop(self, event=None):
480
+ # docstring inherited
481
+ if hasattr(self, "_event_loop"):
482
+ self._event_loop.quit()
483
+
484
+ def draw(self):
485
+ """Render the figure, and queue a request for a Qt draw."""
486
+ # The renderer draw is done here; delaying causes problems with code
487
+ # that uses the result of the draw() to update plot elements.
488
+ if self._is_drawing:
489
+ return
490
+ with cbook._setattr_cm(self, _is_drawing=True):
491
+ super().draw()
492
+ self.update()
493
+
494
+ def draw_idle(self):
495
+ """Queue redraw of the Agg buffer and request Qt paintEvent."""
496
+ # The Agg draw needs to be handled by the same thread Matplotlib
497
+ # modifies the scene graph from. Post Agg draw request to the
498
+ # current event loop in order to ensure thread affinity and to
499
+ # accumulate multiple draw requests from event handling.
500
+ # TODO: queued signal connection might be safer than singleShot
501
+ if not (getattr(self, '_draw_pending', False) or
502
+ getattr(self, '_is_drawing', False)):
503
+ self._draw_pending = True
504
+ QtCore.QTimer.singleShot(0, self._draw_idle)
505
+
506
+ def blit(self, bbox=None):
507
+ # docstring inherited
508
+ if bbox is None and self.figure:
509
+ bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
510
+ # repaint uses logical pixels, not physical pixels like the renderer.
511
+ l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds)
512
+ t = b + h
513
+ self.repaint(l, self.rect().height() - t, w, h)
514
+
515
+ def _draw_idle(self):
516
+ with self._idle_draw_cntx():
517
+ if not self._draw_pending:
518
+ return
519
+ self._draw_pending = False
520
+ if _isdeleted(self) or self.height() <= 0 or self.width() <= 0:
521
+ return
522
+ try:
523
+ self.draw()
524
+ except Exception:
525
+ # Uncaught exceptions are fatal for PyQt5, so catch them.
526
+ traceback.print_exc()
527
+
528
+ def drawRectangle(self, rect):
529
+ # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
530
+ # to be called at the end of paintEvent.
531
+ if rect is not None:
532
+ x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect)
533
+ x1 = x0 + w
534
+ y1 = y0 + h
535
+ def _draw_rect_callback(painter):
536
+ pen = QtGui.QPen(
537
+ QtGui.QColor("black"),
538
+ 1 / self.device_pixel_ratio
539
+ )
540
+
541
+ pen.setDashPattern([3, 3])
542
+ for color, offset in [
543
+ (QtGui.QColor("black"), 0),
544
+ (QtGui.QColor("white"), 3),
545
+ ]:
546
+ pen.setDashOffset(offset)
547
+ pen.setColor(color)
548
+ painter.setPen(pen)
549
+ # Draw the lines from x0, y0 towards x1, y1 so that the
550
+ # dashes don't "jump" when moving the zoom box.
551
+ painter.drawLine(x0, y0, x0, y1)
552
+ painter.drawLine(x0, y0, x1, y0)
553
+ painter.drawLine(x0, y1, x1, y1)
554
+ painter.drawLine(x1, y0, x1, y1)
555
+ else:
556
+ def _draw_rect_callback(painter):
557
+ return
558
+ self._draw_rect_callback = _draw_rect_callback
559
+ self.update()
560
+
561
+
562
+ class MainWindow(QtWidgets.QMainWindow):
563
+ closing = QtCore.Signal()
564
+
565
+ def closeEvent(self, event):
566
+ self.closing.emit()
567
+ super().closeEvent(event)
568
+
569
+
570
+ class FigureManagerQT(FigureManagerBase):
571
+ """
572
+ Attributes
573
+ ----------
574
+ canvas : `FigureCanvas`
575
+ The FigureCanvas instance
576
+ num : int or str
577
+ The Figure number
578
+ toolbar : qt.QToolBar
579
+ The qt.QToolBar
580
+ window : qt.QMainWindow
581
+ The qt.QMainWindow
582
+ """
583
+
584
+ def __init__(self, canvas, num):
585
+ self.window = MainWindow()
586
+ super().__init__(canvas, num)
587
+ self.window.closing.connect(self._widgetclosed)
588
+
589
+ if sys.platform != "darwin":
590
+ image = str(cbook._get_data_path('images/matplotlib.svg'))
591
+ icon = QtGui.QIcon(image)
592
+ self.window.setWindowIcon(icon)
593
+
594
+ self.window._destroying = False
595
+
596
+ if self.toolbar:
597
+ self.window.addToolBar(self.toolbar)
598
+ tbs_height = self.toolbar.sizeHint().height()
599
+ else:
600
+ tbs_height = 0
601
+
602
+ # resize the main window so it will display the canvas with the
603
+ # requested size:
604
+ cs = canvas.sizeHint()
605
+ cs_height = cs.height()
606
+ height = cs_height + tbs_height
607
+ self.window.resize(cs.width(), height)
608
+
609
+ self.window.setCentralWidget(self.canvas)
610
+
611
+ if mpl.is_interactive():
612
+ self.window.show()
613
+ self.canvas.draw_idle()
614
+
615
+ # Give the keyboard focus to the figure instead of the manager:
616
+ # StrongFocus accepts both tab and click to focus and will enable the
617
+ # canvas to process event without clicking.
618
+ # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum
619
+ self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus)
620
+ self.canvas.setFocus()
621
+
622
+ self.window.raise_()
623
+
624
+ def full_screen_toggle(self):
625
+ if self.window.isFullScreen():
626
+ self.window.showNormal()
627
+ else:
628
+ self.window.showFullScreen()
629
+
630
+ def _widgetclosed(self):
631
+ CloseEvent("close_event", self.canvas)._process()
632
+ if self.window._destroying:
633
+ return
634
+ self.window._destroying = True
635
+ try:
636
+ Gcf.destroy(self)
637
+ except AttributeError:
638
+ pass
639
+ # It seems that when the python session is killed,
640
+ # Gcf can get destroyed before the Gcf.destroy
641
+ # line is run, leading to a useless AttributeError.
642
+
643
+ def resize(self, width, height):
644
+ # The Qt methods return sizes in 'virtual' pixels so we do need to
645
+ # rescale from physical to logical pixels.
646
+ width = int(width / self.canvas.device_pixel_ratio)
647
+ height = int(height / self.canvas.device_pixel_ratio)
648
+ extra_width = self.window.width() - self.canvas.width()
649
+ extra_height = self.window.height() - self.canvas.height()
650
+ self.canvas.resize(width, height)
651
+ self.window.resize(width + extra_width, height + extra_height)
652
+
653
+ @classmethod
654
+ def start_main_loop(cls):
655
+ qapp = QtWidgets.QApplication.instance()
656
+ if qapp:
657
+ with _allow_interrupt_qt(qapp):
658
+ qt_compat._exec(qapp)
659
+
660
+ def show(self):
661
+ self.window._destroying = False
662
+ self.window.show()
663
+ if mpl.rcParams['figure.raise_window']:
664
+ self.window.activateWindow()
665
+ self.window.raise_()
666
+
667
+ def destroy(self, *args):
668
+ # check for qApp first, as PySide deletes it in its atexit handler
669
+ if QtWidgets.QApplication.instance() is None:
670
+ return
671
+ if self.window._destroying:
672
+ return
673
+ self.window._destroying = True
674
+ if self.toolbar:
675
+ self.toolbar.destroy()
676
+ self.window.close()
677
+
678
+ def get_window_title(self):
679
+ return self.window.windowTitle()
680
+
681
+ def set_window_title(self, title):
682
+ self.window.setWindowTitle(title)
683
+
684
+
685
+ class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar):
686
+ toolitems = [*NavigationToolbar2.toolitems]
687
+ toolitems.insert(
688
+ # Add 'customize' action after 'subplots'
689
+ [name for name, *_ in toolitems].index("Subplots") + 1,
690
+ ("Customize", "Edit axis, curve and image parameters",
691
+ "qt4_editor_options", "edit_parameters"))
692
+
693
+ def __init__(self, canvas, parent=None, coordinates=True):
694
+ """coordinates: should we show the coordinates on the right?"""
695
+ QtWidgets.QToolBar.__init__(self, parent)
696
+ self.setAllowedAreas(QtCore.Qt.ToolBarArea(
697
+ _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
698
+ _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
699
+ self.coordinates = coordinates
700
+ self._actions = {} # mapping of toolitem method names to QActions.
701
+ self._subplot_dialog = None
702
+
703
+ for text, tooltip_text, image_file, callback in self.toolitems:
704
+ if text is None:
705
+ self.addSeparator()
706
+ else:
707
+ slot = getattr(self, callback)
708
+ # https://bugreports.qt.io/browse/PYSIDE-2512
709
+ slot = functools.wraps(slot)(functools.partial(slot))
710
+ slot = QtCore.Slot()(slot)
711
+
712
+ a = self.addAction(self._icon(image_file + '.png'),
713
+ text, slot)
714
+ self._actions[callback] = a
715
+ if callback in ['zoom', 'pan']:
716
+ a.setCheckable(True)
717
+ if tooltip_text is not None:
718
+ a.setToolTip(tooltip_text)
719
+
720
+ # Add the (x, y) location widget at the right side of the toolbar
721
+ # The stretch factor is 1 which means any resizing of the toolbar
722
+ # will resize this label instead of the buttons.
723
+ if self.coordinates:
724
+ self.locLabel = QtWidgets.QLabel("", self)
725
+ self.locLabel.setAlignment(QtCore.Qt.AlignmentFlag(
726
+ _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
727
+ _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
728
+
729
+ self.locLabel.setSizePolicy(QtWidgets.QSizePolicy(
730
+ QtWidgets.QSizePolicy.Policy.Expanding,
731
+ QtWidgets.QSizePolicy.Policy.Ignored,
732
+ ))
733
+ labelAction = self.addWidget(self.locLabel)
734
+ labelAction.setVisible(True)
735
+
736
+ NavigationToolbar2.__init__(self, canvas)
737
+
738
+ def _icon(self, name):
739
+ """
740
+ Construct a `.QIcon` from an image file *name*, including the extension
741
+ and relative to Matplotlib's "images" data directory.
742
+ """
743
+ # use a high-resolution icon with suffix '_large' if available
744
+ # note: user-provided icons may not have '_large' versions
745
+ path_regular = cbook._get_data_path('images', name)
746
+ path_large = path_regular.with_name(
747
+ path_regular.name.replace('.png', '_large.png'))
748
+ filename = str(path_large if path_large.exists() else path_regular)
749
+
750
+ pm = QtGui.QPixmap(filename)
751
+ pm.setDevicePixelRatio(
752
+ self.devicePixelRatioF() or 1) # rarely, devicePixelRatioF=0
753
+ if self.palette().color(self.backgroundRole()).value() < 128:
754
+ icon_color = self.palette().color(self.foregroundRole())
755
+ mask = pm.createMaskFromColor(
756
+ QtGui.QColor('black'),
757
+ QtCore.Qt.MaskMode.MaskOutColor)
758
+ pm.fill(icon_color)
759
+ pm.setMask(mask)
760
+ return QtGui.QIcon(pm)
761
+
762
+ def edit_parameters(self):
763
+ axes = self.canvas.figure.get_axes()
764
+ if not axes:
765
+ QtWidgets.QMessageBox.warning(
766
+ self.canvas.parent(), "Error", "There are no Axes to edit.")
767
+ return
768
+ elif len(axes) == 1:
769
+ ax, = axes
770
+ else:
771
+ titles = [
772
+ ax.get_label() or
773
+ ax.get_title() or
774
+ ax.get_title("left") or
775
+ ax.get_title("right") or
776
+ " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
777
+ f"<anonymous {type(ax).__name__}>"
778
+ for ax in axes]
779
+ duplicate_titles = [
780
+ title for title in titles if titles.count(title) > 1]
781
+ for i, ax in enumerate(axes):
782
+ if titles[i] in duplicate_titles:
783
+ titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles.
784
+ item, ok = QtWidgets.QInputDialog.getItem(
785
+ self.canvas.parent(),
786
+ 'Customize', 'Select Axes:', titles, 0, False)
787
+ if not ok:
788
+ return
789
+ ax = axes[titles.index(item)]
790
+ figureoptions.figure_edit(ax, self)
791
+
792
+ def _update_buttons_checked(self):
793
+ # sync button checkstates to match active mode
794
+ if 'pan' in self._actions:
795
+ self._actions['pan'].setChecked(self.mode.name == 'PAN')
796
+ if 'zoom' in self._actions:
797
+ self._actions['zoom'].setChecked(self.mode.name == 'ZOOM')
798
+
799
+ def pan(self, *args):
800
+ super().pan(*args)
801
+ self._update_buttons_checked()
802
+
803
+ def zoom(self, *args):
804
+ super().zoom(*args)
805
+ self._update_buttons_checked()
806
+
807
+ def set_message(self, s):
808
+ if self.coordinates:
809
+ self.locLabel.setText(s)
810
+
811
+ def draw_rubberband(self, event, x0, y0, x1, y1):
812
+ height = self.canvas.figure.bbox.height
813
+ y1 = height - y1
814
+ y0 = height - y0
815
+ rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
816
+ self.canvas.drawRectangle(rect)
817
+
818
+ def remove_rubberband(self):
819
+ self.canvas.drawRectangle(None)
820
+
821
+ def configure_subplots(self):
822
+ if self._subplot_dialog is None:
823
+ self._subplot_dialog = SubplotToolQt(
824
+ self.canvas.figure, self.canvas.parent())
825
+ self.canvas.mpl_connect(
826
+ "close_event", lambda e: self._subplot_dialog.reject())
827
+ self._subplot_dialog.update_from_current_subplotpars()
828
+ self._subplot_dialog.setModal(True)
829
+ self._subplot_dialog.show()
830
+ return self._subplot_dialog
831
+
832
+ def save_figure(self, *args):
833
+ filetypes = self.canvas.get_supported_filetypes_grouped()
834
+ sorted_filetypes = sorted(filetypes.items())
835
+ default_filetype = self.canvas.get_default_filetype()
836
+
837
+ startpath = os.path.expanduser(mpl.rcParams['savefig.directory'])
838
+ start = os.path.join(startpath, self.canvas.get_default_filename())
839
+ filters = []
840
+ selectedFilter = None
841
+ for name, exts in sorted_filetypes:
842
+ exts_list = " ".join(['*.%s' % ext for ext in exts])
843
+ filter = f'{name} ({exts_list})'
844
+ if default_filetype in exts:
845
+ selectedFilter = filter
846
+ filters.append(filter)
847
+ filters = ';;'.join(filters)
848
+
849
+ fname, filter = QtWidgets.QFileDialog.getSaveFileName(
850
+ self.canvas.parent(), "Choose a filename to save to", start,
851
+ filters, selectedFilter)
852
+ if fname:
853
+ # Save dir for next time, unless empty str (i.e., use cwd).
854
+ if startpath != "":
855
+ mpl.rcParams['savefig.directory'] = os.path.dirname(fname)
856
+ try:
857
+ self.canvas.figure.savefig(fname)
858
+ except Exception as e:
859
+ QtWidgets.QMessageBox.critical(
860
+ self, "Error saving file", str(e),
861
+ QtWidgets.QMessageBox.StandardButton.Ok,
862
+ QtWidgets.QMessageBox.StandardButton.NoButton)
863
+ return fname
864
+
865
+ def set_history_buttons(self):
866
+ can_backward = self._nav_stack._pos > 0
867
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
868
+ if 'back' in self._actions:
869
+ self._actions['back'].setEnabled(can_backward)
870
+ if 'forward' in self._actions:
871
+ self._actions['forward'].setEnabled(can_forward)
872
+
873
+
874
+ class SubplotToolQt(QtWidgets.QDialog):
875
+ def __init__(self, targetfig, parent):
876
+ super().__init__(parent)
877
+ self.setWindowIcon(QtGui.QIcon(
878
+ str(cbook._get_data_path("images/matplotlib.png"))))
879
+ self.setObjectName("SubplotTool")
880
+ self._spinboxes = {}
881
+ main_layout = QtWidgets.QHBoxLayout()
882
+ self.setLayout(main_layout)
883
+ for group, spinboxes, buttons in [
884
+ ("Borders",
885
+ ["top", "bottom", "left", "right"],
886
+ [("Export values", self._export_values)]),
887
+ ("Spacings",
888
+ ["hspace", "wspace"],
889
+ [("Tight layout", self._tight_layout),
890
+ ("Reset", self._reset),
891
+ ("Close", self.close)])]:
892
+ layout = QtWidgets.QVBoxLayout()
893
+ main_layout.addLayout(layout)
894
+ box = QtWidgets.QGroupBox(group)
895
+ layout.addWidget(box)
896
+ inner = QtWidgets.QFormLayout(box)
897
+ for name in spinboxes:
898
+ self._spinboxes[name] = spinbox = QtWidgets.QDoubleSpinBox()
899
+ spinbox.setRange(0, 1)
900
+ spinbox.setDecimals(3)
901
+ spinbox.setSingleStep(0.005)
902
+ spinbox.setKeyboardTracking(False)
903
+ spinbox.valueChanged.connect(self._on_value_changed)
904
+ inner.addRow(name, spinbox)
905
+ layout.addStretch(1)
906
+ for name, method in buttons:
907
+ button = QtWidgets.QPushButton(name)
908
+ # Don't trigger on <enter>, which is used to input values.
909
+ button.setAutoDefault(False)
910
+ button.clicked.connect(method)
911
+ layout.addWidget(button)
912
+ if name == "Close":
913
+ button.setFocus()
914
+ self._figure = targetfig
915
+ self._defaults = {}
916
+ self._export_values_dialog = None
917
+ self.update_from_current_subplotpars()
918
+
919
+ def update_from_current_subplotpars(self):
920
+ self._defaults = {spinbox: getattr(self._figure.subplotpars, name)
921
+ for name, spinbox in self._spinboxes.items()}
922
+ self._reset() # Set spinbox current values without triggering signals.
923
+
924
+ def _export_values(self):
925
+ # Explicitly round to 3 decimals (which is also the spinbox precision)
926
+ # to avoid numbers of the form 0.100...001.
927
+ self._export_values_dialog = QtWidgets.QDialog()
928
+ layout = QtWidgets.QVBoxLayout()
929
+ self._export_values_dialog.setLayout(layout)
930
+ text = QtWidgets.QPlainTextEdit()
931
+ text.setReadOnly(True)
932
+ layout.addWidget(text)
933
+ text.setPlainText(
934
+ ",\n".join(f"{attr}={spinbox.value():.3}"
935
+ for attr, spinbox in self._spinboxes.items()))
936
+ # Adjust the height of the text widget to fit the whole text, plus
937
+ # some padding.
938
+ size = text.maximumSize()
939
+ size.setHeight(
940
+ QtGui.QFontMetrics(text.document().defaultFont())
941
+ .size(0, text.toPlainText()).height() + 20)
942
+ text.setMaximumSize(size)
943
+ self._export_values_dialog.show()
944
+
945
+ def _on_value_changed(self):
946
+ spinboxes = self._spinboxes
947
+ # Set all mins and maxes, so that this can also be used in _reset().
948
+ for lower, higher in [("bottom", "top"), ("left", "right")]:
949
+ spinboxes[higher].setMinimum(spinboxes[lower].value() + .001)
950
+ spinboxes[lower].setMaximum(spinboxes[higher].value() - .001)
951
+ self._figure.subplots_adjust(
952
+ **{attr: spinbox.value() for attr, spinbox in spinboxes.items()})
953
+ self._figure.canvas.draw_idle()
954
+
955
+ def _tight_layout(self):
956
+ self._figure.tight_layout()
957
+ for attr, spinbox in self._spinboxes.items():
958
+ spinbox.blockSignals(True)
959
+ spinbox.setValue(getattr(self._figure.subplotpars, attr))
960
+ spinbox.blockSignals(False)
961
+ self._figure.canvas.draw_idle()
962
+
963
+ def _reset(self):
964
+ for spinbox, value in self._defaults.items():
965
+ spinbox.setRange(0, 1)
966
+ spinbox.blockSignals(True)
967
+ spinbox.setValue(value)
968
+ spinbox.blockSignals(False)
969
+ self._on_value_changed()
970
+
971
+
972
+ class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar):
973
+ def __init__(self, toolmanager, parent=None):
974
+ ToolContainerBase.__init__(self, toolmanager)
975
+ QtWidgets.QToolBar.__init__(self, parent)
976
+ self.setAllowedAreas(QtCore.Qt.ToolBarArea(
977
+ _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) |
978
+ _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea)))
979
+ message_label = QtWidgets.QLabel("")
980
+ message_label.setAlignment(QtCore.Qt.AlignmentFlag(
981
+ _to_int(QtCore.Qt.AlignmentFlag.AlignRight) |
982
+ _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter)))
983
+ message_label.setSizePolicy(QtWidgets.QSizePolicy(
984
+ QtWidgets.QSizePolicy.Policy.Expanding,
985
+ QtWidgets.QSizePolicy.Policy.Ignored,
986
+ ))
987
+ self._message_action = self.addWidget(message_label)
988
+ self._toolitems = {}
989
+ self._groups = {}
990
+
991
+ def add_toolitem(
992
+ self, name, group, position, image_file, description, toggle):
993
+
994
+ button = QtWidgets.QToolButton(self)
995
+ if image_file:
996
+ button.setIcon(NavigationToolbar2QT._icon(self, image_file))
997
+ button.setText(name)
998
+ if description:
999
+ button.setToolTip(description)
1000
+
1001
+ def handler():
1002
+ self.trigger_tool(name)
1003
+ if toggle:
1004
+ button.setCheckable(True)
1005
+ button.toggled.connect(handler)
1006
+ else:
1007
+ button.clicked.connect(handler)
1008
+
1009
+ self._toolitems.setdefault(name, [])
1010
+ self._add_to_group(group, name, button, position)
1011
+ self._toolitems[name].append((button, handler))
1012
+
1013
+ def _add_to_group(self, group, name, button, position):
1014
+ gr = self._groups.get(group, [])
1015
+ if not gr:
1016
+ sep = self.insertSeparator(self._message_action)
1017
+ gr.append(sep)
1018
+ before = gr[position]
1019
+ widget = self.insertWidget(before, button)
1020
+ gr.insert(position, widget)
1021
+ self._groups[group] = gr
1022
+
1023
+ def toggle_toolitem(self, name, toggled):
1024
+ if name not in self._toolitems:
1025
+ return
1026
+ for button, handler in self._toolitems[name]:
1027
+ button.toggled.disconnect(handler)
1028
+ button.setChecked(toggled)
1029
+ button.toggled.connect(handler)
1030
+
1031
+ def remove_toolitem(self, name):
1032
+ for button, handler in self._toolitems.pop(name, []):
1033
+ button.setParent(None)
1034
+
1035
+ def set_message(self, s):
1036
+ self.widgetForAction(self._message_action).setText(s)
1037
+
1038
+
1039
+ @backend_tools._register_tool_class(FigureCanvasQT)
1040
+ class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase):
1041
+ def __init__(self, *args, **kwargs):
1042
+ super().__init__(*args, **kwargs)
1043
+ self._subplot_dialog = None
1044
+
1045
+ def trigger(self, *args):
1046
+ NavigationToolbar2QT.configure_subplots(self)
1047
+
1048
+
1049
+ @backend_tools._register_tool_class(FigureCanvasQT)
1050
+ class SaveFigureQt(backend_tools.SaveFigureBase):
1051
+ def trigger(self, *args):
1052
+ NavigationToolbar2QT.save_figure(
1053
+ self._make_classic_style_pseudo_toolbar())
1054
+
1055
+
1056
+ @backend_tools._register_tool_class(FigureCanvasQT)
1057
+ class RubberbandQt(backend_tools.RubberbandBase):
1058
+ def draw_rubberband(self, x0, y0, x1, y1):
1059
+ NavigationToolbar2QT.draw_rubberband(
1060
+ self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
1061
+
1062
+ def remove_rubberband(self):
1063
+ NavigationToolbar2QT.remove_rubberband(
1064
+ self._make_classic_style_pseudo_toolbar())
1065
+
1066
+
1067
+ @backend_tools._register_tool_class(FigureCanvasQT)
1068
+ class HelpQt(backend_tools.ToolHelpBase):
1069
+ def trigger(self, *args):
1070
+ QtWidgets.QMessageBox.information(None, "Help", self._get_help_html())
1071
+
1072
+
1073
+ @backend_tools._register_tool_class(FigureCanvasQT)
1074
+ class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase):
1075
+ def trigger(self, *args, **kwargs):
1076
+ pixmap = self.canvas.grab()
1077
+ QtWidgets.QApplication.instance().clipboard().setPixmap(pixmap)
1078
+
1079
+
1080
+ FigureManagerQT._toolbar2_class = NavigationToolbar2QT
1081
+ FigureManagerQT._toolmanager_toolbar_class = ToolbarQt
1082
+
1083
+
1084
+ @_Backend.export
1085
+ class _BackendQT(_Backend):
1086
+ backend_version = __version__
1087
+ FigureCanvas = FigureCanvasQT
1088
+ FigureManager = FigureManagerQT
1089
+ mainloop = FigureManagerQT.start_main_loop
workspace/outputs/audit_venv/lib/python3.11/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}")
workspace/outputs/audit_venv/lib/python3.11/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
workspace/outputs/audit_venv/lib/python3.11/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