ZTWHHH commited on
Commit
4c2555b
·
verified ·
1 Parent(s): b62dd12

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. llava_video/lib/python3.10/site-packages/matplotlib/backends/__pycache__/backend_gtk4agg.cpython-310.pyc +0 -0
  3. llava_video/lib/python3.10/site-packages/matplotlib/backends/__pycache__/backend_tkcairo.cpython-310.pyc +0 -0
  4. llava_video/lib/python3.10/site-packages/matplotlib/backends/_backend_gtk.py +331 -0
  5. llava_video/lib/python3.10/site-packages/matplotlib/backends/_backend_tk.py +1077 -0
  6. llava_video/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so +3 -0
  7. llava_video/lib/python3.10/site-packages/matplotlib/backends/_tkagg.pyi +15 -0
  8. llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_agg.py +528 -0
  9. llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_pgf.py +1010 -0
  10. llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_qtcairo.py +46 -0
  11. llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_tkagg.py +20 -0
  12. llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_wxcairo.py +23 -0
  13. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/all_figures.html +52 -0
  14. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/boilerplate.css +77 -0
  15. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/fbm.css +97 -0
  16. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/mpl.css +84 -0
  17. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html +34 -0
  18. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/js/mpl.js +705 -0
  19. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/js/mpl_tornado.js +8 -0
  20. llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/single_figure.html +39 -0
  21. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_conj.h +30 -0
  22. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_convert_indices_from_csr_to_coo_cpu_dispatch.h +25 -0
  23. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cummin_helper_ops.h +28 -0
  24. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_log_cuda_dispatch.h +24 -0
  25. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_pow_native.h +37 -0
  26. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_zero_compositeexplicitautograd_dispatch.h +26 -0
  27. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_ops.h +28 -0
  28. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_check_errors.h +30 -0
  29. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_pin_memory.h +39 -0
  30. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_native.h +21 -0
  31. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward.h +47 -0
  32. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_triton_multi_head_attention_native.h +22 -0
  33. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_triton_scaled_dot_attention.h +39 -0
  34. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_unique2_cpu_dispatch.h +23 -0
  35. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_ops.h +39 -0
  36. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_ops.h +50 -0
  37. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/align_as_ops.h +28 -0
  38. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/alpha_dropout_native.h +22 -0
  39. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/any_compositeexplicitautogradnonfunctional_dispatch.h +25 -0
  40. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_backward.h +39 -0
  41. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_left_shift_meta.h +27 -0
  42. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/copy_sparse_to_sparse_native.h +23 -0
  43. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cos_compositeexplicitautogradnonfunctional_dispatch.h +24 -0
  44. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_grid_sampler_backward_ops.h +39 -0
  45. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/detach_copy_compositeexplicitautograd_dispatch.h +24 -0
  46. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/elu_backward_meta_dispatch.h +25 -0
  47. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/expand_ops.h +28 -0
  48. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fbgemm_pack_quantized_matrix_compositeimplicitautograd_dispatch.h +24 -0
  49. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fill_native.h +33 -0
  50. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_reduce_ops.h +50 -0
.gitattributes CHANGED
@@ -670,3 +670,4 @@ llava_video/lib/python3.10/site-packages/matplotlib/_c_internal_utils.cpython-31
670
  llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
671
  llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
672
  llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
670
  llava_video/lib/python3.10/site-packages/matplotlib/_path.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
671
  llava_video/lib/python3.10/site-packages/matplotlib/_image.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
672
  llava_video/lib/python3.10/site-packages/matplotlib/_tri.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
673
+ llava_video/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
llava_video/lib/python3.10/site-packages/matplotlib/backends/__pycache__/backend_gtk4agg.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
llava_video/lib/python3.10/site-packages/matplotlib/backends/__pycache__/backend_tkcairo.cpython-310.pyc ADDED
Binary file (1.29 kB). View file
 
llava_video/lib/python3.10/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
llava_video/lib/python3.10/site-packages/matplotlib/backends/_backend_tk.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from . import _tkagg
26
+ from ._tkagg import TK_PHOTO_COMPOSITE_OVERLAY, TK_PHOTO_COMPOSITE_SET
27
+
28
+
29
+ _log = logging.getLogger(__name__)
30
+ cursord = {
31
+ cursors.MOVE: "fleur",
32
+ cursors.HAND: "hand2",
33
+ cursors.POINTER: "arrow",
34
+ cursors.SELECT_REGION: "crosshair",
35
+ cursors.WAIT: "watch",
36
+ cursors.RESIZE_HORIZONTAL: "sb_h_double_arrow",
37
+ cursors.RESIZE_VERTICAL: "sb_v_double_arrow",
38
+ }
39
+
40
+
41
+ @contextmanager
42
+ def _restore_foreground_window_at_end():
43
+ foreground = _c_internal_utils.Win32_GetForegroundWindow()
44
+ try:
45
+ yield
46
+ finally:
47
+ if foreground and mpl.rcParams['tk.window_focus']:
48
+ _c_internal_utils.Win32_SetForegroundWindow(foreground)
49
+
50
+
51
+ _blit_args = {}
52
+ # Initialize to a non-empty string that is not a Tcl command
53
+ _blit_tcl_name = "mpl_blit_" + uuid.uuid4().hex
54
+
55
+
56
+ def _blit(argsid):
57
+ """
58
+ Thin wrapper to blit called via tkapp.call.
59
+
60
+ *argsid* is a unique string identifier to fetch the correct arguments from
61
+ the ``_blit_args`` dict, since arguments cannot be passed directly.
62
+ """
63
+ photoimage, data, offsets, bbox, comp_rule = _blit_args.pop(argsid)
64
+ if not photoimage.tk.call("info", "commands", photoimage):
65
+ return
66
+ _tkagg.blit(photoimage.tk.interpaddr(), str(photoimage), data, comp_rule, offsets,
67
+ bbox)
68
+
69
+
70
+ def blit(photoimage, aggimage, offsets, bbox=None):
71
+ """
72
+ Blit *aggimage* to *photoimage*.
73
+
74
+ *offsets* is a tuple describing how to fill the ``offset`` field of the
75
+ ``Tk_PhotoImageBlock`` struct: it should be (0, 1, 2, 3) for RGBA8888 data,
76
+ (2, 1, 0, 3) for little-endian ARBG32 (i.e. GBRA8888) data and (1, 2, 3, 0)
77
+ for big-endian ARGB32 (i.e. ARGB8888) data.
78
+
79
+ If *bbox* is passed, it defines the region that gets blitted. That region
80
+ will be composed with the previous data according to the alpha channel.
81
+ Blitting will be clipped to pixels inside the canvas, including silently
82
+ doing nothing if the *bbox* region is entirely outside the canvas.
83
+
84
+ Tcl events must be dispatched to trigger a blit from a non-Tcl thread.
85
+ """
86
+ data = np.asarray(aggimage)
87
+ height, width = data.shape[:2]
88
+ if bbox is not None:
89
+ (x1, y1), (x2, y2) = bbox.__array__()
90
+ x1 = max(math.floor(x1), 0)
91
+ x2 = min(math.ceil(x2), width)
92
+ y1 = max(math.floor(y1), 0)
93
+ y2 = min(math.ceil(y2), height)
94
+ if (x1 > x2) or (y1 > y2):
95
+ return
96
+ bboxptr = (x1, x2, y1, y2)
97
+ comp_rule = TK_PHOTO_COMPOSITE_OVERLAY
98
+ else:
99
+ bboxptr = (0, width, 0, height)
100
+ comp_rule = TK_PHOTO_COMPOSITE_SET
101
+
102
+ # NOTE: _tkagg.blit is thread unsafe and will crash the process if called
103
+ # from a thread (GH#13293). Instead of blanking and blitting here,
104
+ # use tkapp.call to post a cross-thread event if this function is called
105
+ # from a non-Tcl thread.
106
+
107
+ # tkapp.call coerces all arguments to strings, so to avoid string parsing
108
+ # within _blit, pack up the arguments into a global data structure.
109
+ args = photoimage, data, offsets, bboxptr, comp_rule
110
+ # Need a unique key to avoid thread races.
111
+ # Again, make the key a string to avoid string parsing in _blit.
112
+ argsid = str(id(args))
113
+ _blit_args[argsid] = args
114
+
115
+ try:
116
+ photoimage.tk.call(_blit_tcl_name, argsid)
117
+ except tk.TclError as e:
118
+ if "invalid command name" not in str(e):
119
+ raise
120
+ photoimage.tk.createcommand(_blit_tcl_name, _blit)
121
+ photoimage.tk.call(_blit_tcl_name, argsid)
122
+
123
+
124
+ class TimerTk(TimerBase):
125
+ """Subclass of `backend_bases.TimerBase` using Tk timer events."""
126
+
127
+ def __init__(self, parent, *args, **kwargs):
128
+ self._timer = None
129
+ super().__init__(*args, **kwargs)
130
+ self.parent = parent
131
+
132
+ def _timer_start(self):
133
+ self._timer_stop()
134
+ self._timer = self.parent.after(self._interval, self._on_timer)
135
+
136
+ def _timer_stop(self):
137
+ if self._timer is not None:
138
+ self.parent.after_cancel(self._timer)
139
+ self._timer = None
140
+
141
+ def _on_timer(self):
142
+ super()._on_timer()
143
+ # Tk after() is only a single shot, so we need to add code here to
144
+ # reset the timer if we're not operating in single shot mode. However,
145
+ # if _timer is None, this means that _timer_stop has been called; so
146
+ # don't recreate the timer in that case.
147
+ if not self._single and self._timer:
148
+ if self._interval > 0:
149
+ self._timer = self.parent.after(self._interval, self._on_timer)
150
+ else:
151
+ # Edge case: Tcl after 0 *prepends* events to the queue
152
+ # so a 0 interval does not allow any other events to run.
153
+ # This incantation is cancellable and runs as fast as possible
154
+ # while also allowing events and drawing every frame. GH#18236
155
+ self._timer = self.parent.after_idle(
156
+ lambda: self.parent.after(self._interval, self._on_timer)
157
+ )
158
+ else:
159
+ self._timer = None
160
+
161
+
162
+ class FigureCanvasTk(FigureCanvasBase):
163
+ required_interactive_framework = "tk"
164
+ manager_class = _api.classproperty(lambda cls: FigureManagerTk)
165
+
166
+ def __init__(self, figure=None, master=None):
167
+ super().__init__(figure)
168
+ self._idle_draw_id = None
169
+ self._event_loop_id = None
170
+ w, h = self.get_width_height(physical=True)
171
+ self._tkcanvas = tk.Canvas(
172
+ master=master, background="white",
173
+ width=w, height=h, borderwidth=0, highlightthickness=0)
174
+ self._tkphoto = tk.PhotoImage(
175
+ master=self._tkcanvas, width=w, height=h)
176
+ self._tkcanvas_image_region = self._tkcanvas.create_image(
177
+ w//2, h//2, image=self._tkphoto)
178
+ self._tkcanvas.bind("<Configure>", self.resize)
179
+ self._tkcanvas.bind("<Map>", self._update_device_pixel_ratio)
180
+ self._tkcanvas.bind("<Key>", self.key_press)
181
+ self._tkcanvas.bind("<Motion>", self.motion_notify_event)
182
+ self._tkcanvas.bind("<Enter>", self.enter_notify_event)
183
+ self._tkcanvas.bind("<Leave>", self.leave_notify_event)
184
+ self._tkcanvas.bind("<KeyRelease>", self.key_release)
185
+ for name in ["<Button-1>", "<Button-2>", "<Button-3>"]:
186
+ self._tkcanvas.bind(name, self.button_press_event)
187
+ for name in [
188
+ "<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>"]:
189
+ self._tkcanvas.bind(name, self.button_dblclick_event)
190
+ for name in [
191
+ "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>"]:
192
+ self._tkcanvas.bind(name, self.button_release_event)
193
+
194
+ # Mouse wheel on Linux generates button 4/5 events
195
+ for name in "<Button-4>", "<Button-5>":
196
+ self._tkcanvas.bind(name, self.scroll_event)
197
+ # Mouse wheel for windows goes to the window with the focus.
198
+ # Since the canvas won't usually have the focus, bind the
199
+ # event to the window containing the canvas instead.
200
+ # See https://wiki.tcl-lang.org/3893 (mousewheel) for details
201
+ root = self._tkcanvas.winfo_toplevel()
202
+
203
+ # Prevent long-lived references via tkinter callback structure GH-24820
204
+ weakself = weakref.ref(self)
205
+ weakroot = weakref.ref(root)
206
+
207
+ def scroll_event_windows(event):
208
+ self = weakself()
209
+ if self is None:
210
+ root = weakroot()
211
+ if root is not None:
212
+ root.unbind("<MouseWheel>", scroll_event_windows_id)
213
+ return
214
+ return self.scroll_event_windows(event)
215
+ scroll_event_windows_id = root.bind("<MouseWheel>", scroll_event_windows, "+")
216
+
217
+ # Can't get destroy events by binding to _tkcanvas. Therefore, bind
218
+ # to the window and filter.
219
+ def filter_destroy(event):
220
+ self = weakself()
221
+ if self is None:
222
+ root = weakroot()
223
+ if root is not None:
224
+ root.unbind("<Destroy>", filter_destroy_id)
225
+ return
226
+ if event.widget is self._tkcanvas:
227
+ CloseEvent("close_event", self)._process()
228
+ filter_destroy_id = root.bind("<Destroy>", filter_destroy, "+")
229
+
230
+ self._tkcanvas.focus_set()
231
+
232
+ self._rubberband_rect_black = None
233
+ self._rubberband_rect_white = None
234
+
235
+ def _update_device_pixel_ratio(self, event=None):
236
+ ratio = None
237
+ if sys.platform == 'win32':
238
+ # Tk gives scaling with respect to 72 DPI, but Windows screens are
239
+ # scaled vs 96 dpi, and pixel ratio settings are given in whole
240
+ # percentages, so round to 2 digits.
241
+ ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2)
242
+ elif sys.platform == "linux":
243
+ ratio = self._tkcanvas.winfo_fpixels('1i') / 96
244
+ if ratio is not None and self._set_device_pixel_ratio(ratio):
245
+ # The easiest way to resize the canvas is to resize the canvas
246
+ # widget itself, since we implement all the logic for resizing the
247
+ # canvas backing store on that event.
248
+ w, h = self.get_width_height(physical=True)
249
+ self._tkcanvas.configure(width=w, height=h)
250
+
251
+ def resize(self, event):
252
+ width, height = event.width, event.height
253
+
254
+ # compute desired figure size in inches
255
+ dpival = self.figure.dpi
256
+ winch = width / dpival
257
+ hinch = height / dpival
258
+ self.figure.set_size_inches(winch, hinch, forward=False)
259
+
260
+ self._tkcanvas.delete(self._tkcanvas_image_region)
261
+ self._tkphoto.configure(width=int(width), height=int(height))
262
+ self._tkcanvas_image_region = self._tkcanvas.create_image(
263
+ int(width / 2), int(height / 2), image=self._tkphoto)
264
+ ResizeEvent("resize_event", self)._process()
265
+ self.draw_idle()
266
+
267
+ def draw_idle(self):
268
+ # docstring inherited
269
+ if self._idle_draw_id:
270
+ return
271
+
272
+ def idle_draw(*args):
273
+ try:
274
+ self.draw()
275
+ finally:
276
+ self._idle_draw_id = None
277
+
278
+ self._idle_draw_id = self._tkcanvas.after_idle(idle_draw)
279
+
280
+ def get_tk_widget(self):
281
+ """
282
+ Return the Tk widget used to implement FigureCanvasTkAgg.
283
+
284
+ Although the initial implementation uses a Tk canvas, this routine
285
+ is intended to hide that fact.
286
+ """
287
+ return self._tkcanvas
288
+
289
+ def _event_mpl_coords(self, event):
290
+ # calling canvasx/canvasy allows taking scrollbars into account (i.e.
291
+ # the top of the widget may have been scrolled out of view).
292
+ return (self._tkcanvas.canvasx(event.x),
293
+ # flipy so y=0 is bottom of canvas
294
+ self.figure.bbox.height - self._tkcanvas.canvasy(event.y))
295
+
296
+ def motion_notify_event(self, event):
297
+ MouseEvent("motion_notify_event", self,
298
+ *self._event_mpl_coords(event),
299
+ buttons=self._mpl_buttons(event),
300
+ modifiers=self._mpl_modifiers(event),
301
+ guiEvent=event)._process()
302
+
303
+ def enter_notify_event(self, event):
304
+ LocationEvent("figure_enter_event", self,
305
+ *self._event_mpl_coords(event),
306
+ modifiers=self._mpl_modifiers(event),
307
+ guiEvent=event)._process()
308
+
309
+ def leave_notify_event(self, event):
310
+ LocationEvent("figure_leave_event", self,
311
+ *self._event_mpl_coords(event),
312
+ modifiers=self._mpl_modifiers(event),
313
+ guiEvent=event)._process()
314
+
315
+ def button_press_event(self, event, dblclick=False):
316
+ # set focus to the canvas so that it can receive keyboard events
317
+ self._tkcanvas.focus_set()
318
+
319
+ num = getattr(event, 'num', None)
320
+ if sys.platform == 'darwin': # 2 and 3 are reversed.
321
+ num = {2: 3, 3: 2}.get(num, num)
322
+ MouseEvent("button_press_event", self,
323
+ *self._event_mpl_coords(event), num, dblclick=dblclick,
324
+ modifiers=self._mpl_modifiers(event),
325
+ guiEvent=event)._process()
326
+
327
+ def button_dblclick_event(self, event):
328
+ self.button_press_event(event, dblclick=True)
329
+
330
+ def button_release_event(self, event):
331
+ num = getattr(event, 'num', None)
332
+ if sys.platform == 'darwin': # 2 and 3 are reversed.
333
+ num = {2: 3, 3: 2}.get(num, num)
334
+ MouseEvent("button_release_event", self,
335
+ *self._event_mpl_coords(event), num,
336
+ modifiers=self._mpl_modifiers(event),
337
+ guiEvent=event)._process()
338
+
339
+ def scroll_event(self, event):
340
+ num = getattr(event, 'num', None)
341
+ step = 1 if num == 4 else -1 if num == 5 else 0
342
+ MouseEvent("scroll_event", self,
343
+ *self._event_mpl_coords(event), step=step,
344
+ modifiers=self._mpl_modifiers(event),
345
+ guiEvent=event)._process()
346
+
347
+ def scroll_event_windows(self, event):
348
+ """MouseWheel event processor"""
349
+ # need to find the window that contains the mouse
350
+ w = event.widget.winfo_containing(event.x_root, event.y_root)
351
+ if w != self._tkcanvas:
352
+ return
353
+ x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx())
354
+ y = (self.figure.bbox.height
355
+ - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty()))
356
+ step = event.delta / 120
357
+ MouseEvent("scroll_event", self,
358
+ x, y, step=step, modifiers=self._mpl_modifiers(event),
359
+ guiEvent=event)._process()
360
+
361
+ @staticmethod
362
+ def _mpl_buttons(event): # See _mpl_modifiers.
363
+ # NOTE: This fails to report multiclicks on macOS; only one button is
364
+ # reported (multiclicks work correctly on Linux & Windows).
365
+ modifiers = [
366
+ # macOS appears to swap right and middle (look for "Swap buttons
367
+ # 2/3" in tk/macosx/tkMacOSXMouseEvent.c).
368
+ (MouseButton.LEFT, 1 << 8),
369
+ (MouseButton.RIGHT, 1 << 9),
370
+ (MouseButton.MIDDLE, 1 << 10),
371
+ (MouseButton.BACK, 1 << 11),
372
+ (MouseButton.FORWARD, 1 << 12),
373
+ ] if sys.platform == "darwin" else [
374
+ (MouseButton.LEFT, 1 << 8),
375
+ (MouseButton.MIDDLE, 1 << 9),
376
+ (MouseButton.RIGHT, 1 << 10),
377
+ (MouseButton.BACK, 1 << 11),
378
+ (MouseButton.FORWARD, 1 << 12),
379
+ ]
380
+ # State *before* press/release.
381
+ return [name for name, mask in modifiers if event.state & mask]
382
+
383
+ @staticmethod
384
+ def _mpl_modifiers(event, *, exclude=None):
385
+ # Add modifier keys to the key string. Bit values are inferred from
386
+ # the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... =
387
+ # Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5)
388
+ # In general, the modifier key is excluded from the modifier flag,
389
+ # however this is not the case on "darwin", so double check that
390
+ # we aren't adding repeat modifier flags to a modifier key.
391
+ modifiers = [
392
+ ("ctrl", 1 << 2, "control"),
393
+ ("alt", 1 << 17, "alt"),
394
+ ("shift", 1 << 0, "shift"),
395
+ ] if sys.platform == "win32" else [
396
+ ("ctrl", 1 << 2, "control"),
397
+ ("alt", 1 << 4, "alt"),
398
+ ("shift", 1 << 0, "shift"),
399
+ ("cmd", 1 << 3, "cmd"),
400
+ ] if sys.platform == "darwin" else [
401
+ ("ctrl", 1 << 2, "control"),
402
+ ("alt", 1 << 3, "alt"),
403
+ ("shift", 1 << 0, "shift"),
404
+ ("super", 1 << 6, "super"),
405
+ ]
406
+ return [name for name, mask, key in modifiers
407
+ if event.state & mask and exclude != key]
408
+
409
+ def _get_key(self, event):
410
+ unikey = event.char
411
+ key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym)
412
+ if key is not None:
413
+ mods = self._mpl_modifiers(event, exclude=key)
414
+ # shift is not added to the keys as this is already accounted for.
415
+ if "shift" in mods and unikey:
416
+ mods.remove("shift")
417
+ return "+".join([*mods, key])
418
+
419
+ def key_press(self, event):
420
+ KeyEvent("key_press_event", self,
421
+ self._get_key(event), *self._event_mpl_coords(event),
422
+ guiEvent=event)._process()
423
+
424
+ def key_release(self, event):
425
+ KeyEvent("key_release_event", self,
426
+ self._get_key(event), *self._event_mpl_coords(event),
427
+ guiEvent=event)._process()
428
+
429
+ def new_timer(self, *args, **kwargs):
430
+ # docstring inherited
431
+ return TimerTk(self._tkcanvas, *args, **kwargs)
432
+
433
+ def flush_events(self):
434
+ # docstring inherited
435
+ self._tkcanvas.update()
436
+
437
+ def start_event_loop(self, timeout=0):
438
+ # docstring inherited
439
+ if timeout > 0:
440
+ milliseconds = int(1000 * timeout)
441
+ if milliseconds > 0:
442
+ self._event_loop_id = self._tkcanvas.after(
443
+ milliseconds, self.stop_event_loop)
444
+ else:
445
+ self._event_loop_id = self._tkcanvas.after_idle(
446
+ self.stop_event_loop)
447
+ self._tkcanvas.mainloop()
448
+
449
+ def stop_event_loop(self):
450
+ # docstring inherited
451
+ if self._event_loop_id:
452
+ self._tkcanvas.after_cancel(self._event_loop_id)
453
+ self._event_loop_id = None
454
+ self._tkcanvas.quit()
455
+
456
+ def set_cursor(self, cursor):
457
+ try:
458
+ self._tkcanvas.configure(cursor=cursord[cursor])
459
+ except tkinter.TclError:
460
+ pass
461
+
462
+
463
+ class FigureManagerTk(FigureManagerBase):
464
+ """
465
+ Attributes
466
+ ----------
467
+ canvas : `FigureCanvas`
468
+ The FigureCanvas instance
469
+ num : int or str
470
+ The Figure number
471
+ toolbar : tk.Toolbar
472
+ The tk.Toolbar
473
+ window : tk.Window
474
+ The tk.Window
475
+ """
476
+
477
+ _owns_mainloop = False
478
+
479
+ def __init__(self, canvas, num, window):
480
+ self.window = window
481
+ super().__init__(canvas, num)
482
+ self.window.withdraw()
483
+ # packing toolbar first, because if space is getting low, last packed
484
+ # widget is getting shrunk first (-> the canvas)
485
+ self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
486
+
487
+ # If the window has per-monitor DPI awareness, then setup a Tk variable
488
+ # to store the DPI, which will be updated by the C code, and the trace
489
+ # will handle it on the Python side.
490
+ window_frame = int(window.wm_frame(), 16)
491
+ self._window_dpi = tk.IntVar(master=window, value=96,
492
+ name=f'window_dpi{window_frame}')
493
+ self._window_dpi_cbname = ''
494
+ if _tkagg.enable_dpi_awareness(window_frame, window.tk.interpaddr()):
495
+ self._window_dpi_cbname = self._window_dpi.trace_add(
496
+ 'write', self._update_window_dpi)
497
+
498
+ self._shown = False
499
+
500
+ @classmethod
501
+ def create_with_canvas(cls, canvas_class, figure, num):
502
+ # docstring inherited
503
+ with _restore_foreground_window_at_end():
504
+ if cbook._get_running_interactive_framework() is None:
505
+ cbook._setup_new_guiapp()
506
+ _c_internal_utils.Win32_SetProcessDpiAwareness_max()
507
+ window = tk.Tk(className="matplotlib")
508
+ window.withdraw()
509
+
510
+ # Put a Matplotlib icon on the window rather than the default tk
511
+ # icon. See https://www.tcl.tk/man/tcl/TkCmd/wm.html#M50
512
+ #
513
+ # `ImageTk` can be replaced with `tk` whenever the minimum
514
+ # supported Tk version is increased to 8.6, as Tk 8.6+ natively
515
+ # supports PNG images.
516
+ icon_fname = str(cbook._get_data_path(
517
+ 'images/matplotlib.png'))
518
+ icon_img = ImageTk.PhotoImage(file=icon_fname, master=window)
519
+
520
+ icon_fname_large = str(cbook._get_data_path(
521
+ 'images/matplotlib_large.png'))
522
+ icon_img_large = ImageTk.PhotoImage(
523
+ file=icon_fname_large, master=window)
524
+
525
+ window.iconphoto(False, icon_img_large, icon_img)
526
+
527
+ canvas = canvas_class(figure, master=window)
528
+ manager = cls(canvas, num, window)
529
+ if mpl.is_interactive():
530
+ manager.show()
531
+ canvas.draw_idle()
532
+ return manager
533
+
534
+ @classmethod
535
+ def start_main_loop(cls):
536
+ managers = Gcf.get_all_fig_managers()
537
+ if managers:
538
+ first_manager = managers[0]
539
+ manager_class = type(first_manager)
540
+ if manager_class._owns_mainloop:
541
+ return
542
+ manager_class._owns_mainloop = True
543
+ try:
544
+ first_manager.window.mainloop()
545
+ finally:
546
+ manager_class._owns_mainloop = False
547
+
548
+ def _update_window_dpi(self, *args):
549
+ newdpi = self._window_dpi.get()
550
+ self.window.call('tk', 'scaling', newdpi / 72)
551
+ if self.toolbar and hasattr(self.toolbar, '_rescale'):
552
+ self.toolbar._rescale()
553
+ self.canvas._update_device_pixel_ratio()
554
+
555
+ def resize(self, width, height):
556
+ max_size = 1_400_000 # the measured max on xorg 1.20.8 was 1_409_023
557
+
558
+ if (width > max_size or height > max_size) and sys.platform == 'linux':
559
+ raise ValueError(
560
+ 'You have requested to resize the '
561
+ f'Tk window to ({width}, {height}), one of which '
562
+ f'is bigger than {max_size}. At larger sizes xorg will '
563
+ 'either exit with an error on newer versions (~1.20) or '
564
+ 'cause corruption on older version (~1.19). We '
565
+ 'do not expect a window over a million pixel wide or tall '
566
+ 'to be intended behavior.')
567
+ self.canvas._tkcanvas.configure(width=width, height=height)
568
+
569
+ def show(self):
570
+ with _restore_foreground_window_at_end():
571
+ if not self._shown:
572
+ def destroy(*args):
573
+ Gcf.destroy(self)
574
+ self.window.protocol("WM_DELETE_WINDOW", destroy)
575
+ self.window.deiconify()
576
+ self.canvas._tkcanvas.focus_set()
577
+ else:
578
+ self.canvas.draw_idle()
579
+ if mpl.rcParams['figure.raise_window']:
580
+ self.canvas.manager.window.attributes('-topmost', 1)
581
+ self.canvas.manager.window.attributes('-topmost', 0)
582
+ self._shown = True
583
+
584
+ def destroy(self, *args):
585
+ if self.canvas._idle_draw_id:
586
+ self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)
587
+ if self.canvas._event_loop_id:
588
+ self.canvas._tkcanvas.after_cancel(self.canvas._event_loop_id)
589
+ if self._window_dpi_cbname:
590
+ self._window_dpi.trace_remove('write', self._window_dpi_cbname)
591
+
592
+ # NOTE: events need to be flushed before issuing destroy (GH #9956),
593
+ # however, self.window.update() can break user code. An async callback
594
+ # is the safest way to achieve a complete draining of the event queue,
595
+ # but it leaks if no tk event loop is running. Therefore we explicitly
596
+ # check for an event loop and choose our best guess.
597
+ def delayed_destroy():
598
+ self.window.destroy()
599
+
600
+ if self._owns_mainloop and not Gcf.get_num_fig_managers():
601
+ self.window.quit()
602
+
603
+ if cbook._get_running_interactive_framework() == "tk":
604
+ # "after idle after 0" avoids Tcl error/race (GH #19940)
605
+ self.window.after_idle(self.window.after, 0, delayed_destroy)
606
+ else:
607
+ self.window.update()
608
+ delayed_destroy()
609
+
610
+ def get_window_title(self):
611
+ return self.window.wm_title()
612
+
613
+ def set_window_title(self, title):
614
+ self.window.wm_title(title)
615
+
616
+ def full_screen_toggle(self):
617
+ is_fullscreen = bool(self.window.attributes('-fullscreen'))
618
+ self.window.attributes('-fullscreen', not is_fullscreen)
619
+
620
+
621
+ class NavigationToolbar2Tk(NavigationToolbar2, tk.Frame):
622
+ def __init__(self, canvas, window=None, *, pack_toolbar=True):
623
+ """
624
+ Parameters
625
+ ----------
626
+ canvas : `FigureCanvas`
627
+ The figure canvas on which to operate.
628
+ window : tk.Window
629
+ The tk.Window which owns this toolbar.
630
+ pack_toolbar : bool, default: True
631
+ If True, add the toolbar to the parent's pack manager's packing
632
+ list during initialization with ``side="bottom"`` and ``fill="x"``.
633
+ If you want to use the toolbar with a different layout manager, use
634
+ ``pack_toolbar=False``.
635
+ """
636
+
637
+ if window is None:
638
+ window = canvas.get_tk_widget().master
639
+ tk.Frame.__init__(self, master=window, borderwidth=2,
640
+ width=int(canvas.figure.bbox.width), height=50)
641
+
642
+ self._buttons = {}
643
+ for text, tooltip_text, image_file, callback in self.toolitems:
644
+ if text is None:
645
+ # Add a spacer; return value is unused.
646
+ self._Spacer()
647
+ else:
648
+ self._buttons[text] = button = self._Button(
649
+ text,
650
+ str(cbook._get_data_path(f"images/{image_file}.png")),
651
+ toggle=callback in ["zoom", "pan"],
652
+ command=getattr(self, callback),
653
+ )
654
+ if tooltip_text is not None:
655
+ add_tooltip(button, tooltip_text)
656
+
657
+ self._label_font = tkinter.font.Font(root=window, size=10)
658
+
659
+ # This filler item ensures the toolbar is always at least two text
660
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
661
+ # over images because those use two-line messages which resize the
662
+ # toolbar.
663
+ label = tk.Label(master=self, font=self._label_font,
664
+ text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
665
+ label.pack(side=tk.RIGHT)
666
+
667
+ self.message = tk.StringVar(master=self)
668
+ self._message_label = tk.Label(master=self, font=self._label_font,
669
+ textvariable=self.message,
670
+ justify=tk.RIGHT)
671
+ self._message_label.pack(side=tk.RIGHT)
672
+
673
+ NavigationToolbar2.__init__(self, canvas)
674
+ if pack_toolbar:
675
+ self.pack(side=tk.BOTTOM, fill=tk.X)
676
+
677
+ def _rescale(self):
678
+ """
679
+ Scale all children of the toolbar to current DPI setting.
680
+
681
+ Before this is called, the Tk scaling setting will have been updated to
682
+ match the new DPI. Tk widgets do not update for changes to scaling, but
683
+ all measurements made after the change will match the new scaling. Thus
684
+ this function re-applies all the same sizes in points, which Tk will
685
+ scale correctly to pixels.
686
+ """
687
+ for widget in self.winfo_children():
688
+ if isinstance(widget, (tk.Button, tk.Checkbutton)):
689
+ if hasattr(widget, '_image_file'):
690
+ # Explicit class because ToolbarTk calls _rescale.
691
+ NavigationToolbar2Tk._set_image_for_button(self, widget)
692
+ else:
693
+ # Text-only button is handled by the font setting instead.
694
+ pass
695
+ elif isinstance(widget, tk.Frame):
696
+ widget.configure(height='18p')
697
+ widget.pack_configure(padx='3p')
698
+ elif isinstance(widget, tk.Label):
699
+ pass # Text is handled by the font setting instead.
700
+ else:
701
+ _log.warning('Unknown child class %s', widget.winfo_class)
702
+ self._label_font.configure(size=10)
703
+
704
+ def _update_buttons_checked(self):
705
+ # sync button checkstates to match active mode
706
+ for text, mode in [('Zoom', _Mode.ZOOM), ('Pan', _Mode.PAN)]:
707
+ if text in self._buttons:
708
+ if self.mode == mode:
709
+ self._buttons[text].select() # NOT .invoke()
710
+ else:
711
+ self._buttons[text].deselect()
712
+
713
+ def pan(self, *args):
714
+ super().pan(*args)
715
+ self._update_buttons_checked()
716
+
717
+ def zoom(self, *args):
718
+ super().zoom(*args)
719
+ self._update_buttons_checked()
720
+
721
+ def set_message(self, s):
722
+ self.message.set(s)
723
+
724
+ def draw_rubberband(self, event, x0, y0, x1, y1):
725
+ # Block copied from remove_rubberband for backend_tools convenience.
726
+ if self.canvas._rubberband_rect_white:
727
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
728
+ if self.canvas._rubberband_rect_black:
729
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
730
+ height = self.canvas.figure.bbox.height
731
+ y0 = height - y0
732
+ y1 = height - y1
733
+ self.canvas._rubberband_rect_black = (
734
+ self.canvas._tkcanvas.create_rectangle(
735
+ x0, y0, x1, y1))
736
+ self.canvas._rubberband_rect_white = (
737
+ self.canvas._tkcanvas.create_rectangle(
738
+ x0, y0, x1, y1, outline='white', dash=(3, 3)))
739
+
740
+ def remove_rubberband(self):
741
+ if self.canvas._rubberband_rect_white:
742
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_white)
743
+ self.canvas._rubberband_rect_white = None
744
+ if self.canvas._rubberband_rect_black:
745
+ self.canvas._tkcanvas.delete(self.canvas._rubberband_rect_black)
746
+ self.canvas._rubberband_rect_black = None
747
+
748
+ def _set_image_for_button(self, button):
749
+ """
750
+ Set the image for a button based on its pixel size.
751
+
752
+ The pixel size is determined by the DPI scaling of the window.
753
+ """
754
+ if button._image_file is None:
755
+ return
756
+
757
+ # Allow _image_file to be relative to Matplotlib's "images" data
758
+ # directory.
759
+ path_regular = cbook._get_data_path('images', button._image_file)
760
+ path_large = path_regular.with_name(
761
+ path_regular.name.replace('.png', '_large.png'))
762
+ size = button.winfo_pixels('18p')
763
+
764
+ # Nested functions because ToolbarTk calls _Button.
765
+ def _get_color(color_name):
766
+ # `winfo_rgb` returns an (r, g, b) tuple in the range 0-65535
767
+ return button.winfo_rgb(button.cget(color_name))
768
+
769
+ def _is_dark(color):
770
+ if isinstance(color, str):
771
+ color = _get_color(color)
772
+ return max(color) < 65535 / 2
773
+
774
+ def _recolor_icon(image, color):
775
+ image_data = np.asarray(image).copy()
776
+ black_mask = (image_data[..., :3] == 0).all(axis=-1)
777
+ image_data[black_mask, :3] = color
778
+ return Image.fromarray(image_data, mode="RGBA")
779
+
780
+ # Use the high-resolution (48x48 px) icon if it exists and is needed
781
+ with Image.open(path_large if (size > 24 and path_large.exists())
782
+ else path_regular) as im:
783
+ # assure a RGBA image as foreground color is RGB
784
+ im = im.convert("RGBA")
785
+ image = ImageTk.PhotoImage(im.resize((size, size)), master=self)
786
+ button._ntimage = image
787
+
788
+ # create a version of the icon with the button's text color
789
+ foreground = (255 / 65535) * np.array(
790
+ button.winfo_rgb(button.cget("foreground")))
791
+ im_alt = _recolor_icon(im, foreground)
792
+ image_alt = ImageTk.PhotoImage(
793
+ im_alt.resize((size, size)), master=self)
794
+ button._ntimage_alt = image_alt
795
+
796
+ if _is_dark("background"):
797
+ # For Checkbuttons, we need to set `image` and `selectimage` at
798
+ # the same time. Otherwise, when updating the `image` option
799
+ # (such as when changing DPI), if the old `selectimage` has
800
+ # just been overwritten, Tk will throw an error.
801
+ image_kwargs = {"image": image_alt}
802
+ else:
803
+ image_kwargs = {"image": image}
804
+ # Checkbuttons may switch the background to `selectcolor` in the
805
+ # checked state, so check separately which image it needs to use in
806
+ # that state to still ensure enough contrast with the background.
807
+ if (
808
+ isinstance(button, tk.Checkbutton)
809
+ and button.cget("selectcolor") != ""
810
+ ):
811
+ if self._windowingsystem != "x11":
812
+ selectcolor = "selectcolor"
813
+ else:
814
+ # On X11, selectcolor isn't used directly for indicator-less
815
+ # buttons. See `::tk::CheckEnter` in the Tk button.tcl source
816
+ # code for details.
817
+ r1, g1, b1 = _get_color("selectcolor")
818
+ r2, g2, b2 = _get_color("activebackground")
819
+ selectcolor = ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2)
820
+ if _is_dark(selectcolor):
821
+ image_kwargs["selectimage"] = image_alt
822
+ else:
823
+ image_kwargs["selectimage"] = image
824
+
825
+ button.configure(**image_kwargs, height='18p', width='18p')
826
+
827
+ def _Button(self, text, image_file, toggle, command):
828
+ if not toggle:
829
+ b = tk.Button(
830
+ master=self, text=text, command=command,
831
+ relief="flat", overrelief="groove", borderwidth=1,
832
+ )
833
+ else:
834
+ # There is a bug in tkinter included in some python 3.6 versions
835
+ # that without this variable, produces a "visual" toggling of
836
+ # other near checkbuttons
837
+ # https://bugs.python.org/issue29402
838
+ # https://bugs.python.org/issue25684
839
+ var = tk.IntVar(master=self)
840
+ b = tk.Checkbutton(
841
+ master=self, text=text, command=command, indicatoron=False,
842
+ variable=var, offrelief="flat", overrelief="groove",
843
+ borderwidth=1
844
+ )
845
+ b.var = var
846
+ b._image_file = image_file
847
+ if image_file is not None:
848
+ # Explicit class because ToolbarTk calls _Button.
849
+ NavigationToolbar2Tk._set_image_for_button(self, b)
850
+ else:
851
+ b.configure(font=self._label_font)
852
+ b.pack(side=tk.LEFT)
853
+ return b
854
+
855
+ def _Spacer(self):
856
+ # Buttons are also 18pt high.
857
+ s = tk.Frame(master=self, height='18p', relief=tk.RIDGE, bg='DarkGray')
858
+ s.pack(side=tk.LEFT, padx='3p')
859
+ return s
860
+
861
+ def save_figure(self, *args):
862
+ filetypes = self.canvas.get_supported_filetypes_grouped()
863
+ tk_filetypes = [
864
+ (name, " ".join(f"*.{ext}" for ext in exts))
865
+ for name, exts in sorted(filetypes.items())
866
+ ]
867
+
868
+ default_extension = self.canvas.get_default_filetype()
869
+ default_filetype = self.canvas.get_supported_filetypes()[default_extension]
870
+ filetype_variable = tk.StringVar(self.canvas.get_tk_widget(), default_filetype)
871
+
872
+ # adding a default extension seems to break the
873
+ # asksaveasfilename dialog when you choose various save types
874
+ # from the dropdown. Passing in the empty string seems to
875
+ # work - JDH!
876
+ # defaultextension = self.canvas.get_default_filetype()
877
+ defaultextension = ''
878
+ initialdir = os.path.expanduser(mpl.rcParams['savefig.directory'])
879
+ # get_default_filename() contains the default extension. On some platforms,
880
+ # choosing a different extension from the dropdown does not overwrite it,
881
+ # so we need to remove it to make the dropdown functional.
882
+ initialfile = pathlib.Path(self.canvas.get_default_filename()).stem
883
+ fname = tkinter.filedialog.asksaveasfilename(
884
+ master=self.canvas.get_tk_widget().master,
885
+ title='Save the figure',
886
+ filetypes=tk_filetypes,
887
+ defaultextension=defaultextension,
888
+ initialdir=initialdir,
889
+ initialfile=initialfile,
890
+ typevariable=filetype_variable
891
+ )
892
+
893
+ if fname in ["", ()]:
894
+ return None
895
+ # Save dir for next time, unless empty str (i.e., use cwd).
896
+ if initialdir != "":
897
+ mpl.rcParams['savefig.directory'] = (
898
+ os.path.dirname(str(fname)))
899
+
900
+ # If the filename contains an extension, let savefig() infer the file
901
+ # format from that. If it does not, use the selected dropdown option.
902
+ if pathlib.Path(fname).suffix[1:] != "":
903
+ extension = None
904
+ else:
905
+ extension = filetypes[filetype_variable.get()][0]
906
+
907
+ try:
908
+ self.canvas.figure.savefig(fname, format=extension)
909
+ return fname
910
+ except Exception as e:
911
+ tkinter.messagebox.showerror("Error saving file", str(e))
912
+
913
+ def set_history_buttons(self):
914
+ state_map = {True: tk.NORMAL, False: tk.DISABLED}
915
+ can_back = self._nav_stack._pos > 0
916
+ can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
917
+ if "Back" in self._buttons:
918
+ self._buttons['Back']['state'] = state_map[can_back]
919
+ if "Forward" in self._buttons:
920
+ self._buttons['Forward']['state'] = state_map[can_forward]
921
+
922
+
923
+ def add_tooltip(widget, text):
924
+ tipwindow = None
925
+
926
+ def showtip(event):
927
+ """Display text in tooltip window."""
928
+ nonlocal tipwindow
929
+ if tipwindow or not text:
930
+ return
931
+ x, y, _, _ = widget.bbox("insert")
932
+ x = x + widget.winfo_rootx() + widget.winfo_width()
933
+ y = y + widget.winfo_rooty()
934
+ tipwindow = tk.Toplevel(widget)
935
+ tipwindow.overrideredirect(1)
936
+ tipwindow.geometry(f"+{x}+{y}")
937
+ try: # For Mac OS
938
+ tipwindow.tk.call("::tk::unsupported::MacWindowStyle",
939
+ "style", tipwindow._w,
940
+ "help", "noActivates")
941
+ except tk.TclError:
942
+ pass
943
+ label = tk.Label(tipwindow, text=text, justify=tk.LEFT,
944
+ relief=tk.SOLID, borderwidth=1)
945
+ label.pack(ipadx=1)
946
+
947
+ def hidetip(event):
948
+ nonlocal tipwindow
949
+ if tipwindow:
950
+ tipwindow.destroy()
951
+ tipwindow = None
952
+
953
+ widget.bind("<Enter>", showtip)
954
+ widget.bind("<Leave>", hidetip)
955
+
956
+
957
+ @backend_tools._register_tool_class(FigureCanvasTk)
958
+ class RubberbandTk(backend_tools.RubberbandBase):
959
+ def draw_rubberband(self, x0, y0, x1, y1):
960
+ NavigationToolbar2Tk.draw_rubberband(
961
+ self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
962
+
963
+ def remove_rubberband(self):
964
+ NavigationToolbar2Tk.remove_rubberband(
965
+ self._make_classic_style_pseudo_toolbar())
966
+
967
+
968
+ class ToolbarTk(ToolContainerBase, tk.Frame):
969
+ def __init__(self, toolmanager, window=None):
970
+ ToolContainerBase.__init__(self, toolmanager)
971
+ if window is None:
972
+ window = self.toolmanager.canvas.get_tk_widget().master
973
+ xmin, xmax = self.toolmanager.canvas.figure.bbox.intervalx
974
+ height, width = 50, xmax - xmin
975
+ tk.Frame.__init__(self, master=window,
976
+ width=int(width), height=int(height),
977
+ borderwidth=2)
978
+ self._label_font = tkinter.font.Font(size=10)
979
+ # This filler item ensures the toolbar is always at least two text
980
+ # lines high. Otherwise the canvas gets redrawn as the mouse hovers
981
+ # over images because those use two-line messages which resize the
982
+ # toolbar.
983
+ label = tk.Label(master=self, font=self._label_font,
984
+ text='\N{NO-BREAK SPACE}\n\N{NO-BREAK SPACE}')
985
+ label.pack(side=tk.RIGHT)
986
+ self._message = tk.StringVar(master=self)
987
+ self._message_label = tk.Label(master=self, font=self._label_font,
988
+ textvariable=self._message)
989
+ self._message_label.pack(side=tk.RIGHT)
990
+ self._toolitems = {}
991
+ self.pack(side=tk.TOP, fill=tk.X)
992
+ self._groups = {}
993
+
994
+ def _rescale(self):
995
+ return NavigationToolbar2Tk._rescale(self)
996
+
997
+ def add_toolitem(
998
+ self, name, group, position, image_file, description, toggle):
999
+ frame = self._get_groupframe(group)
1000
+ buttons = frame.pack_slaves()
1001
+ if position >= len(buttons) or position < 0:
1002
+ before = None
1003
+ else:
1004
+ before = buttons[position]
1005
+ button = NavigationToolbar2Tk._Button(frame, name, image_file, toggle,
1006
+ lambda: self._button_click(name))
1007
+ button.pack_configure(before=before)
1008
+ if description is not None:
1009
+ add_tooltip(button, description)
1010
+ self._toolitems.setdefault(name, [])
1011
+ self._toolitems[name].append(button)
1012
+
1013
+ def _get_groupframe(self, group):
1014
+ if group not in self._groups:
1015
+ if self._groups:
1016
+ self._add_separator()
1017
+ frame = tk.Frame(master=self, borderwidth=0)
1018
+ frame.pack(side=tk.LEFT, fill=tk.Y)
1019
+ frame._label_font = self._label_font
1020
+ self._groups[group] = frame
1021
+ return self._groups[group]
1022
+
1023
+ def _add_separator(self):
1024
+ return NavigationToolbar2Tk._Spacer(self)
1025
+
1026
+ def _button_click(self, name):
1027
+ self.trigger_tool(name)
1028
+
1029
+ def toggle_toolitem(self, name, toggled):
1030
+ if name not in self._toolitems:
1031
+ return
1032
+ for toolitem in self._toolitems[name]:
1033
+ if toggled:
1034
+ toolitem.select()
1035
+ else:
1036
+ toolitem.deselect()
1037
+
1038
+ def remove_toolitem(self, name):
1039
+ for toolitem in self._toolitems.pop(name, []):
1040
+ toolitem.pack_forget()
1041
+
1042
+ def set_message(self, s):
1043
+ self._message.set(s)
1044
+
1045
+
1046
+ @backend_tools._register_tool_class(FigureCanvasTk)
1047
+ class SaveFigureTk(backend_tools.SaveFigureBase):
1048
+ def trigger(self, *args):
1049
+ NavigationToolbar2Tk.save_figure(
1050
+ self._make_classic_style_pseudo_toolbar())
1051
+
1052
+
1053
+ @backend_tools._register_tool_class(FigureCanvasTk)
1054
+ class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase):
1055
+ def trigger(self, *args):
1056
+ NavigationToolbar2Tk.configure_subplots(self)
1057
+
1058
+
1059
+ @backend_tools._register_tool_class(FigureCanvasTk)
1060
+ class HelpTk(backend_tools.ToolHelpBase):
1061
+ def trigger(self, *args):
1062
+ dialog = SimpleDialog(
1063
+ self.figure.canvas._tkcanvas, self._get_help_text(), ["OK"])
1064
+ dialog.done = lambda num: dialog.frame.master.withdraw()
1065
+
1066
+
1067
+ Toolbar = ToolbarTk
1068
+ FigureManagerTk._toolbar2_class = NavigationToolbar2Tk
1069
+ FigureManagerTk._toolmanager_toolbar_class = ToolbarTk
1070
+
1071
+
1072
+ @_Backend.export
1073
+ class _BackendTk(_Backend):
1074
+ backend_version = tk.TkVersion
1075
+ FigureCanvas = FigureCanvasTk
1076
+ FigureManager = FigureManagerTk
1077
+ mainloop = FigureManagerTk.start_main_loop
llava_video/lib/python3.10/site-packages/matplotlib/backends/_tkagg.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99882d0e2dcf8ad31d19c4669a3f8d0acf7f54719da08d38d071b10653aa93a7
3
+ size 279120
llava_video/lib/python3.10/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: ...
llava_video/lib/python3.10/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
llava_video/lib/python3.10/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
llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_qtcairo.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+
3
+ from .backend_cairo import cairo, FigureCanvasCairo
4
+ from .backend_qt import _BackendQT, FigureCanvasQT
5
+ from .qt_compat import QT_API, QtCore, QtGui
6
+
7
+
8
+ class FigureCanvasQTCairo(FigureCanvasCairo, FigureCanvasQT):
9
+ def draw(self):
10
+ if hasattr(self._renderer.gc, "ctx"):
11
+ self._renderer.dpi = self.figure.dpi
12
+ self.figure.draw(self._renderer)
13
+ super().draw()
14
+
15
+ def paintEvent(self, event):
16
+ width = int(self.device_pixel_ratio * self.width())
17
+ height = int(self.device_pixel_ratio * self.height())
18
+ if (width, height) != self._renderer.get_canvas_width_height():
19
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
20
+ self._renderer.set_context(cairo.Context(surface))
21
+ self._renderer.dpi = self.figure.dpi
22
+ self.figure.draw(self._renderer)
23
+ buf = self._renderer.gc.ctx.get_target().get_data()
24
+ if QT_API == "PyQt6":
25
+ from PyQt6 import sip
26
+ ptr = int(sip.voidptr(buf))
27
+ else:
28
+ ptr = buf
29
+ qimage = QtGui.QImage(
30
+ ptr, width, height,
31
+ QtGui.QImage.Format.Format_ARGB32_Premultiplied)
32
+ # Adjust the buf reference count to work around a memory leak bug in
33
+ # QImage under PySide.
34
+ if QT_API == "PySide2" and QtCore.__version_info__ < (5, 12):
35
+ ctypes.c_long.from_address(id(buf)).value = 1
36
+ qimage.setDevicePixelRatio(self.device_pixel_ratio)
37
+ painter = QtGui.QPainter(self)
38
+ painter.eraseRect(event.rect())
39
+ painter.drawImage(0, 0, qimage)
40
+ self._draw_rect_callback(painter)
41
+ painter.end()
42
+
43
+
44
+ @_BackendQT.export
45
+ class _BackendQTCairo(_BackendQT):
46
+ FigureCanvas = FigureCanvasQTCairo
llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_tkagg.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import _backend_tk
2
+ from .backend_agg import FigureCanvasAgg
3
+ from ._backend_tk import _BackendTk, FigureCanvasTk
4
+ from ._backend_tk import ( # noqa: F401 # pylint: disable=W0611
5
+ FigureManagerTk, NavigationToolbar2Tk)
6
+
7
+
8
+ class FigureCanvasTkAgg(FigureCanvasAgg, FigureCanvasTk):
9
+ def draw(self):
10
+ super().draw()
11
+ self.blit()
12
+
13
+ def blit(self, bbox=None):
14
+ _backend_tk.blit(self._tkphoto, self.renderer.buffer_rgba(),
15
+ (0, 1, 2, 3), bbox=bbox)
16
+
17
+
18
+ @_BackendTk.export
19
+ class _BackendTkAgg(_BackendTk):
20
+ FigureCanvas = FigureCanvasTkAgg
llava_video/lib/python3.10/site-packages/matplotlib/backends/backend_wxcairo.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wx.lib.wxcairo as wxcairo
2
+
3
+ from .backend_cairo import cairo, FigureCanvasCairo
4
+ from .backend_wx import _BackendWx, _FigureCanvasWxBase
5
+ from .backend_wx import ( # noqa: F401 # pylint: disable=W0611
6
+ NavigationToolbar2Wx as NavigationToolbar2WxCairo)
7
+
8
+
9
+ class FigureCanvasWxCairo(FigureCanvasCairo, _FigureCanvasWxBase):
10
+ def draw(self, drawDC=None):
11
+ size = self.figure.bbox.size.astype(int)
12
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)
13
+ self._renderer.set_context(cairo.Context(surface))
14
+ self._renderer.dpi = self.figure.dpi
15
+ self.figure.draw(self._renderer)
16
+ self.bitmap = wxcairo.BitmapFromImageSurface(surface)
17
+ self._isDrawn = True
18
+ self.gui_repaint(drawDC=drawDC)
19
+
20
+
21
+ @_BackendWx.export
22
+ class _BackendWxCairo(_BackendWx):
23
+ FigureCanvas = FigureCanvasWxCairo
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/all_figures.html ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css">
5
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css">
6
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css">
7
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/mpl.css" type="text/css">
8
+ <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script>
9
+ <script src="{{ prefix }}/js/mpl.js"></script>
10
+
11
+ <script>
12
+ function ready(fn) {
13
+ if (document.readyState != "loading") {
14
+ fn();
15
+ } else {
16
+ document.addEventListener("DOMContentLoaded", fn);
17
+ }
18
+ }
19
+
20
+ function figure_ready(fig_id) {
21
+ return function () {
22
+ var main_div = document.querySelector("div#figures");
23
+ var figure_div = document.createElement("div");
24
+ figure_div.id = "figure-div";
25
+ main_div.appendChild(figure_div);
26
+ var websocket_type = mpl.get_websocket_type();
27
+ var uri = "{{ ws_uri }}" + fig_id + "/ws";
28
+ if (window.location.protocol === "https:") uri = uri.replace('ws:', 'wss:')
29
+ var websocket = new websocket_type(uri);
30
+ var fig = new mpl.figure(fig_id, websocket, mpl_ondownload, figure_div);
31
+
32
+ fig.focus_on_mouseover = true;
33
+
34
+ fig.canvas.setAttribute("tabindex", fig_id);
35
+ }
36
+ };
37
+
38
+ {% for (fig_id, fig_manager) in figures %}
39
+ ready(figure_ready({{ str(fig_id) }}));
40
+ {% end %}
41
+ </script>
42
+
43
+ <title>MPL | WebAgg current figures</title>
44
+
45
+ </head>
46
+ <body>
47
+ <div id="mpl-warnings" class="mpl-warnings"></div>
48
+
49
+ <div id="figures" style="margin: 10px 10px;"></div>
50
+
51
+ </body>
52
+ </html>
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/boilerplate.css ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * HTML5 ✰ Boilerplate
3
+ *
4
+ * style.css contains a reset, font normalization and some base styles.
5
+ *
6
+ * Credit is left where credit is due.
7
+ * Much inspiration was taken from these projects:
8
+ * - yui.yahooapis.com/2.8.1/build/base/base.css
9
+ * - camendesign.com/design/
10
+ * - praegnanz.de/weblog/htmlcssjs-kickstart
11
+ */
12
+
13
+
14
+ /**
15
+ * html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline)
16
+ * v1.6.1 2010-09-17 | Authors: Eric Meyer & Richard Clark
17
+ * html5doctor.com/html-5-reset-stylesheet/
18
+ */
19
+
20
+ html, body, div, span, object, iframe,
21
+ h1, h2, h3, h4, h5, h6, p, blockquote, pre,
22
+ abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
23
+ small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
24
+ fieldset, form, label, legend,
25
+ table, caption, tbody, tfoot, thead, tr, th, td,
26
+ article, aside, canvas, details, figcaption, figure,
27
+ footer, header, hgroup, menu, nav, section, summary,
28
+ time, mark, audio, video {
29
+ margin: 0;
30
+ padding: 0;
31
+ border: 0;
32
+ font-size: 100%;
33
+ font: inherit;
34
+ vertical-align: baseline;
35
+ }
36
+
37
+ sup { vertical-align: super; }
38
+ sub { vertical-align: sub; }
39
+
40
+ article, aside, details, figcaption, figure,
41
+ footer, header, hgroup, menu, nav, section {
42
+ display: block;
43
+ }
44
+
45
+ blockquote, q { quotes: none; }
46
+
47
+ blockquote:before, blockquote:after,
48
+ q:before, q:after { content: ""; content: none; }
49
+
50
+ ins { background-color: #ff9; color: #000; text-decoration: none; }
51
+
52
+ mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; }
53
+
54
+ del { text-decoration: line-through; }
55
+
56
+ abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; }
57
+
58
+ table { border-collapse: collapse; border-spacing: 0; }
59
+
60
+ hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }
61
+
62
+ input, select { vertical-align: middle; }
63
+
64
+
65
+ /**
66
+ * Font normalization inspired by YUI Library's fonts.css: developer.yahoo.com/yui/
67
+ */
68
+
69
+ body { font:13px/1.231 sans-serif; *font-size:small; } /* Hack retained to preserve specificity */
70
+ select, input, textarea, button { font:99% sans-serif; }
71
+
72
+ /* Normalize monospace sizing:
73
+ en.wikipedia.org/wiki/MediaWiki_talk:Common.css/Archive_11#Teletype_style_fix_for_Chrome */
74
+ pre, code, kbd, samp { font-family: monospace, sans-serif; }
75
+
76
+ em,i { font-style: italic; }
77
+ b,strong { font-weight: bold; }
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/fbm.css ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ /* Flexible box model classes */
3
+ /* Taken from Alex Russell https://infrequently.org/2009/08/css-3-progress/ */
4
+
5
+ .hbox {
6
+ display: -webkit-box;
7
+ -webkit-box-orient: horizontal;
8
+ -webkit-box-align: stretch;
9
+
10
+ display: -moz-box;
11
+ -moz-box-orient: horizontal;
12
+ -moz-box-align: stretch;
13
+
14
+ display: box;
15
+ box-orient: horizontal;
16
+ box-align: stretch;
17
+ }
18
+
19
+ .hbox > * {
20
+ -webkit-box-flex: 0;
21
+ -moz-box-flex: 0;
22
+ box-flex: 0;
23
+ }
24
+
25
+ .vbox {
26
+ display: -webkit-box;
27
+ -webkit-box-orient: vertical;
28
+ -webkit-box-align: stretch;
29
+
30
+ display: -moz-box;
31
+ -moz-box-orient: vertical;
32
+ -moz-box-align: stretch;
33
+
34
+ display: box;
35
+ box-orient: vertical;
36
+ box-align: stretch;
37
+ }
38
+
39
+ .vbox > * {
40
+ -webkit-box-flex: 0;
41
+ -moz-box-flex: 0;
42
+ box-flex: 0;
43
+ }
44
+
45
+ .reverse {
46
+ -webkit-box-direction: reverse;
47
+ -moz-box-direction: reverse;
48
+ box-direction: reverse;
49
+ }
50
+
51
+ .box-flex0 {
52
+ -webkit-box-flex: 0;
53
+ -moz-box-flex: 0;
54
+ box-flex: 0;
55
+ }
56
+
57
+ .box-flex1, .box-flex {
58
+ -webkit-box-flex: 1;
59
+ -moz-box-flex: 1;
60
+ box-flex: 1;
61
+ }
62
+
63
+ .box-flex2 {
64
+ -webkit-box-flex: 2;
65
+ -moz-box-flex: 2;
66
+ box-flex: 2;
67
+ }
68
+
69
+ .box-group1 {
70
+ -webkit-box-flex-group: 1;
71
+ -moz-box-flex-group: 1;
72
+ box-flex-group: 1;
73
+ }
74
+
75
+ .box-group2 {
76
+ -webkit-box-flex-group: 2;
77
+ -moz-box-flex-group: 2;
78
+ box-flex-group: 2;
79
+ }
80
+
81
+ .start {
82
+ -webkit-box-pack: start;
83
+ -moz-box-pack: start;
84
+ box-pack: start;
85
+ }
86
+
87
+ .end {
88
+ -webkit-box-pack: end;
89
+ -moz-box-pack: end;
90
+ box-pack: end;
91
+ }
92
+
93
+ .center {
94
+ -webkit-box-pack: center;
95
+ -moz-box-pack: center;
96
+ box-pack: center;
97
+ }
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/css/mpl.css ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* General styling */
2
+ .ui-helper-clearfix:before,
3
+ .ui-helper-clearfix:after {
4
+ content: "";
5
+ display: table;
6
+ border-collapse: collapse;
7
+ }
8
+ .ui-helper-clearfix:after {
9
+ clear: both;
10
+ }
11
+
12
+ /* Header */
13
+ .ui-widget-header {
14
+ border: 1px solid #dddddd;
15
+ border-top-left-radius: 6px;
16
+ border-top-right-radius: 6px;
17
+ background: #e9e9e9;
18
+ color: #333333;
19
+ font-weight: bold;
20
+ }
21
+
22
+ /* Toolbar and items */
23
+ .mpl-toolbar {
24
+ width: 100%;
25
+ }
26
+
27
+ .mpl-toolbar div.mpl-button-group {
28
+ display: inline-block;
29
+ }
30
+
31
+ .mpl-button-group + .mpl-button-group {
32
+ margin-left: 0.5em;
33
+ }
34
+
35
+ .mpl-widget {
36
+ background-color: #fff;
37
+ border: 1px solid #ccc;
38
+ display: inline-block;
39
+ cursor: pointer;
40
+ color: #333;
41
+ padding: 6px;
42
+ vertical-align: middle;
43
+ }
44
+
45
+ .mpl-widget:disabled,
46
+ .mpl-widget[disabled] {
47
+ background-color: #ddd;
48
+ border-color: #ddd !important;
49
+ cursor: not-allowed;
50
+ }
51
+
52
+ .mpl-widget:disabled img,
53
+ .mpl-widget[disabled] img {
54
+ /* Convert black to grey */
55
+ filter: contrast(0%);
56
+ }
57
+
58
+ .mpl-widget.active img {
59
+ /* Convert black to tab:blue, approximately */
60
+ filter: invert(34%) sepia(97%) saturate(468%) hue-rotate(162deg) brightness(96%) contrast(91%);
61
+ }
62
+
63
+ button.mpl-widget:focus,
64
+ button.mpl-widget:hover {
65
+ background-color: #ddd;
66
+ border-color: #aaa;
67
+ }
68
+
69
+ .mpl-button-group button.mpl-widget {
70
+ margin-left: -1px;
71
+ }
72
+ .mpl-button-group button.mpl-widget:first-child {
73
+ border-top-left-radius: 6px;
74
+ border-bottom-left-radius: 6px;
75
+ margin-left: 0px;
76
+ }
77
+ .mpl-button-group button.mpl-widget:last-child {
78
+ border-top-right-radius: 6px;
79
+ border-bottom-right-radius: 6px;
80
+ }
81
+
82
+ select.mpl-widget {
83
+ cursor: default;
84
+ }
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/ipython_inline_figure.html ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- Within the kernel, we don't know the address of the matplotlib
2
+ websocket server, so we have to get in client-side and fetch our
3
+ resources that way. -->
4
+ <script>
5
+ // We can't proceed until these JavaScript files are fetched, so
6
+ // we fetch them synchronously
7
+ $.ajaxSetup({async: false});
8
+ $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/_static/js/mpl_tornado.js");
9
+ $.getScript("http://" + window.location.hostname + ":{{ port }}{{prefix}}/js/mpl.js");
10
+ $.ajaxSetup({async: true});
11
+
12
+ function init_figure{{ fig_id }}(e) {
13
+ $('div.output').off('resize');
14
+
15
+ var output_div = e.target.querySelector('div.output_subarea');
16
+ var websocket_type = mpl.get_websocket_type();
17
+ var websocket = new websocket_type(
18
+ "ws://" + window.location.hostname + ":{{ port }}{{ prefix}}/" +
19
+ {{ repr(str(fig_id)) }} + "/ws");
20
+
21
+ var fig = new mpl.figure(
22
+ {{repr(str(fig_id))}}, websocket, mpl_ondownload, output_div);
23
+
24
+ // Fetch the first image
25
+ fig.context.drawImage(fig.imageObj, 0, 0);
26
+
27
+ fig.focus_on_mouseover = true;
28
+ }
29
+
30
+ // We can't initialize the figure contents until our content
31
+ // has been added to the DOM. This is a bit of hack to get an
32
+ // event for that.
33
+ $('div.output').resize(init_figure{{ fig_id }});
34
+ </script>
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/js/mpl.js ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Put everything inside the global mpl namespace */
2
+ /* global mpl */
3
+ window.mpl = {};
4
+
5
+ mpl.get_websocket_type = function () {
6
+ if (typeof WebSocket !== 'undefined') {
7
+ return WebSocket;
8
+ } else if (typeof MozWebSocket !== 'undefined') {
9
+ return MozWebSocket;
10
+ } else {
11
+ alert(
12
+ 'Your browser does not have WebSocket support. ' +
13
+ 'Please try Chrome, Safari or Firefox ≥ 6. ' +
14
+ 'Firefox 4 and 5 are also supported but you ' +
15
+ 'have to enable WebSockets in about:config.'
16
+ );
17
+ }
18
+ };
19
+
20
+ mpl.figure = function (figure_id, websocket, ondownload, parent_element) {
21
+ this.id = figure_id;
22
+
23
+ this.ws = websocket;
24
+
25
+ this.supports_binary = this.ws.binaryType !== undefined;
26
+
27
+ if (!this.supports_binary) {
28
+ var warnings = document.getElementById('mpl-warnings');
29
+ if (warnings) {
30
+ warnings.style.display = 'block';
31
+ warnings.textContent =
32
+ 'This browser does not support binary websocket messages. ' +
33
+ 'Performance may be slow.';
34
+ }
35
+ }
36
+
37
+ this.imageObj = new Image();
38
+
39
+ this.context = undefined;
40
+ this.message = undefined;
41
+ this.canvas = undefined;
42
+ this.rubberband_canvas = undefined;
43
+ this.rubberband_context = undefined;
44
+ this.format_dropdown = undefined;
45
+
46
+ this.image_mode = 'full';
47
+
48
+ this.root = document.createElement('div');
49
+ this.root.setAttribute('style', 'display: inline-block');
50
+ this._root_extra_style(this.root);
51
+
52
+ parent_element.appendChild(this.root);
53
+
54
+ this._init_header(this);
55
+ this._init_canvas(this);
56
+ this._init_toolbar(this);
57
+
58
+ var fig = this;
59
+
60
+ this.waiting = false;
61
+
62
+ this.ws.onopen = function () {
63
+ fig.send_message('supports_binary', { value: fig.supports_binary });
64
+ fig.send_message('send_image_mode', {});
65
+ if (fig.ratio !== 1) {
66
+ fig.send_message('set_device_pixel_ratio', {
67
+ device_pixel_ratio: fig.ratio,
68
+ });
69
+ }
70
+ fig.send_message('refresh', {});
71
+ };
72
+
73
+ this.imageObj.onload = function () {
74
+ if (fig.image_mode === 'full') {
75
+ // Full images could contain transparency (where diff images
76
+ // almost always do), so we need to clear the canvas so that
77
+ // there is no ghosting.
78
+ fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);
79
+ }
80
+ fig.context.drawImage(fig.imageObj, 0, 0);
81
+ };
82
+
83
+ this.imageObj.onunload = function () {
84
+ fig.ws.close();
85
+ };
86
+
87
+ this.ws.onmessage = this._make_on_message_function(this);
88
+
89
+ this.ondownload = ondownload;
90
+ };
91
+
92
+ mpl.figure.prototype._init_header = function () {
93
+ var titlebar = document.createElement('div');
94
+ titlebar.classList =
95
+ 'ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix';
96
+ var titletext = document.createElement('div');
97
+ titletext.classList = 'ui-dialog-title';
98
+ titletext.setAttribute(
99
+ 'style',
100
+ 'width: 100%; text-align: center; padding: 3px;'
101
+ );
102
+ titlebar.appendChild(titletext);
103
+ this.root.appendChild(titlebar);
104
+ this.header = titletext;
105
+ };
106
+
107
+ mpl.figure.prototype._canvas_extra_style = function (_canvas_div) {};
108
+
109
+ mpl.figure.prototype._root_extra_style = function (_canvas_div) {};
110
+
111
+ mpl.figure.prototype._init_canvas = function () {
112
+ var fig = this;
113
+
114
+ var canvas_div = (this.canvas_div = document.createElement('div'));
115
+ canvas_div.setAttribute('tabindex', '0');
116
+ canvas_div.setAttribute(
117
+ 'style',
118
+ 'border: 1px solid #ddd;' +
119
+ 'box-sizing: content-box;' +
120
+ 'clear: both;' +
121
+ 'min-height: 1px;' +
122
+ 'min-width: 1px;' +
123
+ 'outline: 0;' +
124
+ 'overflow: hidden;' +
125
+ 'position: relative;' +
126
+ 'resize: both;' +
127
+ 'z-index: 2;'
128
+ );
129
+
130
+ function on_keyboard_event_closure(name) {
131
+ return function (event) {
132
+ return fig.key_event(event, name);
133
+ };
134
+ }
135
+
136
+ canvas_div.addEventListener(
137
+ 'keydown',
138
+ on_keyboard_event_closure('key_press')
139
+ );
140
+ canvas_div.addEventListener(
141
+ 'keyup',
142
+ on_keyboard_event_closure('key_release')
143
+ );
144
+
145
+ this._canvas_extra_style(canvas_div);
146
+ this.root.appendChild(canvas_div);
147
+
148
+ var canvas = (this.canvas = document.createElement('canvas'));
149
+ canvas.classList.add('mpl-canvas');
150
+ canvas.setAttribute(
151
+ 'style',
152
+ 'box-sizing: content-box;' +
153
+ 'pointer-events: none;' +
154
+ 'position: relative;' +
155
+ 'z-index: 0;'
156
+ );
157
+
158
+ this.context = canvas.getContext('2d');
159
+
160
+ var backingStore =
161
+ this.context.backingStorePixelRatio ||
162
+ this.context.webkitBackingStorePixelRatio ||
163
+ this.context.mozBackingStorePixelRatio ||
164
+ this.context.msBackingStorePixelRatio ||
165
+ this.context.oBackingStorePixelRatio ||
166
+ this.context.backingStorePixelRatio ||
167
+ 1;
168
+
169
+ this.ratio = (window.devicePixelRatio || 1) / backingStore;
170
+
171
+ var rubberband_canvas = (this.rubberband_canvas = document.createElement(
172
+ 'canvas'
173
+ ));
174
+ rubberband_canvas.setAttribute(
175
+ 'style',
176
+ 'box-sizing: content-box;' +
177
+ 'left: 0;' +
178
+ 'pointer-events: none;' +
179
+ 'position: absolute;' +
180
+ 'top: 0;' +
181
+ 'z-index: 1;'
182
+ );
183
+
184
+ // Apply a ponyfill if ResizeObserver is not implemented by browser.
185
+ if (this.ResizeObserver === undefined) {
186
+ if (window.ResizeObserver !== undefined) {
187
+ this.ResizeObserver = window.ResizeObserver;
188
+ } else {
189
+ var obs = _JSXTOOLS_RESIZE_OBSERVER({});
190
+ this.ResizeObserver = obs.ResizeObserver;
191
+ }
192
+ }
193
+
194
+ this.resizeObserverInstance = new this.ResizeObserver(function (entries) {
195
+ // There's no need to resize if the WebSocket is not connected:
196
+ // - If it is still connecting, then we will get an initial resize from
197
+ // Python once it connects.
198
+ // - If it has disconnected, then resizing will clear the canvas and
199
+ // never get anything back to refill it, so better to not resize and
200
+ // keep something visible.
201
+ if (fig.ws.readyState != 1) {
202
+ return;
203
+ }
204
+ var nentries = entries.length;
205
+ for (var i = 0; i < nentries; i++) {
206
+ var entry = entries[i];
207
+ var width, height;
208
+ if (entry.contentBoxSize) {
209
+ if (entry.contentBoxSize instanceof Array) {
210
+ // Chrome 84 implements new version of spec.
211
+ width = entry.contentBoxSize[0].inlineSize;
212
+ height = entry.contentBoxSize[0].blockSize;
213
+ } else {
214
+ // Firefox implements old version of spec.
215
+ width = entry.contentBoxSize.inlineSize;
216
+ height = entry.contentBoxSize.blockSize;
217
+ }
218
+ } else {
219
+ // Chrome <84 implements even older version of spec.
220
+ width = entry.contentRect.width;
221
+ height = entry.contentRect.height;
222
+ }
223
+
224
+ // Keep the size of the canvas and rubber band canvas in sync with
225
+ // the canvas container.
226
+ if (entry.devicePixelContentBoxSize) {
227
+ // Chrome 84 implements new version of spec.
228
+ canvas.setAttribute(
229
+ 'width',
230
+ entry.devicePixelContentBoxSize[0].inlineSize
231
+ );
232
+ canvas.setAttribute(
233
+ 'height',
234
+ entry.devicePixelContentBoxSize[0].blockSize
235
+ );
236
+ } else {
237
+ canvas.setAttribute('width', width * fig.ratio);
238
+ canvas.setAttribute('height', height * fig.ratio);
239
+ }
240
+ /* This rescales the canvas back to display pixels, so that it
241
+ * appears correct on HiDPI screens. */
242
+ canvas.style.width = width + 'px';
243
+ canvas.style.height = height + 'px';
244
+
245
+ rubberband_canvas.setAttribute('width', width);
246
+ rubberband_canvas.setAttribute('height', height);
247
+
248
+ // And update the size in Python. We ignore the initial 0/0 size
249
+ // that occurs as the element is placed into the DOM, which should
250
+ // otherwise not happen due to the minimum size styling.
251
+ if (width != 0 && height != 0) {
252
+ fig.request_resize(width, height);
253
+ }
254
+ }
255
+ });
256
+ this.resizeObserverInstance.observe(canvas_div);
257
+
258
+ function on_mouse_event_closure(name) {
259
+ /* User Agent sniffing is bad, but WebKit is busted:
260
+ * https://bugs.webkit.org/show_bug.cgi?id=144526
261
+ * https://bugs.webkit.org/show_bug.cgi?id=181818
262
+ * The worst that happens here is that they get an extra browser
263
+ * selection when dragging, if this check fails to catch them.
264
+ */
265
+ var UA = navigator.userAgent;
266
+ var isWebKit = /AppleWebKit/.test(UA) && !/Chrome/.test(UA);
267
+ if(isWebKit) {
268
+ return function (event) {
269
+ /* This prevents the web browser from automatically changing to
270
+ * the text insertion cursor when the button is pressed. We
271
+ * want to control all of the cursor setting manually through
272
+ * the 'cursor' event from matplotlib */
273
+ event.preventDefault()
274
+ return fig.mouse_event(event, name);
275
+ };
276
+ } else {
277
+ return function (event) {
278
+ return fig.mouse_event(event, name);
279
+ };
280
+ }
281
+ }
282
+
283
+ canvas_div.addEventListener(
284
+ 'mousedown',
285
+ on_mouse_event_closure('button_press')
286
+ );
287
+ canvas_div.addEventListener(
288
+ 'mouseup',
289
+ on_mouse_event_closure('button_release')
290
+ );
291
+ canvas_div.addEventListener(
292
+ 'dblclick',
293
+ on_mouse_event_closure('dblclick')
294
+ );
295
+ // Throttle sequential mouse events to 1 every 20ms.
296
+ canvas_div.addEventListener(
297
+ 'mousemove',
298
+ on_mouse_event_closure('motion_notify')
299
+ );
300
+
301
+ canvas_div.addEventListener(
302
+ 'mouseenter',
303
+ on_mouse_event_closure('figure_enter')
304
+ );
305
+ canvas_div.addEventListener(
306
+ 'mouseleave',
307
+ on_mouse_event_closure('figure_leave')
308
+ );
309
+
310
+ canvas_div.addEventListener('wheel', function (event) {
311
+ if (event.deltaY < 0) {
312
+ event.step = 1;
313
+ } else {
314
+ event.step = -1;
315
+ }
316
+ on_mouse_event_closure('scroll')(event);
317
+ });
318
+
319
+ canvas_div.appendChild(canvas);
320
+ canvas_div.appendChild(rubberband_canvas);
321
+
322
+ this.rubberband_context = rubberband_canvas.getContext('2d');
323
+ this.rubberband_context.strokeStyle = '#000000';
324
+
325
+ this._resize_canvas = function (width, height, forward) {
326
+ if (forward) {
327
+ canvas_div.style.width = width + 'px';
328
+ canvas_div.style.height = height + 'px';
329
+ }
330
+ };
331
+
332
+ // Disable right mouse context menu.
333
+ canvas_div.addEventListener('contextmenu', function (_e) {
334
+ event.preventDefault();
335
+ return false;
336
+ });
337
+
338
+ function set_focus() {
339
+ canvas.focus();
340
+ canvas_div.focus();
341
+ }
342
+
343
+ window.setTimeout(set_focus, 100);
344
+ };
345
+
346
+ mpl.figure.prototype._init_toolbar = function () {
347
+ var fig = this;
348
+
349
+ var toolbar = document.createElement('div');
350
+ toolbar.classList = 'mpl-toolbar';
351
+ this.root.appendChild(toolbar);
352
+
353
+ function on_click_closure(name) {
354
+ return function (_event) {
355
+ return fig.toolbar_button_onclick(name);
356
+ };
357
+ }
358
+
359
+ function on_mouseover_closure(tooltip) {
360
+ return function (event) {
361
+ if (!event.currentTarget.disabled) {
362
+ return fig.toolbar_button_onmouseover(tooltip);
363
+ }
364
+ };
365
+ }
366
+
367
+ fig.buttons = {};
368
+ var buttonGroup = document.createElement('div');
369
+ buttonGroup.classList = 'mpl-button-group';
370
+ for (var toolbar_ind in mpl.toolbar_items) {
371
+ var name = mpl.toolbar_items[toolbar_ind][0];
372
+ var tooltip = mpl.toolbar_items[toolbar_ind][1];
373
+ var image = mpl.toolbar_items[toolbar_ind][2];
374
+ var method_name = mpl.toolbar_items[toolbar_ind][3];
375
+
376
+ if (!name) {
377
+ /* Instead of a spacer, we start a new button group. */
378
+ if (buttonGroup.hasChildNodes()) {
379
+ toolbar.appendChild(buttonGroup);
380
+ }
381
+ buttonGroup = document.createElement('div');
382
+ buttonGroup.classList = 'mpl-button-group';
383
+ continue;
384
+ }
385
+
386
+ var button = (fig.buttons[name] = document.createElement('button'));
387
+ button.classList = 'mpl-widget';
388
+ button.setAttribute('role', 'button');
389
+ button.setAttribute('aria-disabled', 'false');
390
+ button.addEventListener('click', on_click_closure(method_name));
391
+ button.addEventListener('mouseover', on_mouseover_closure(tooltip));
392
+
393
+ var icon_img = document.createElement('img');
394
+ icon_img.src = '_images/' + image + '.png';
395
+ icon_img.srcset = '_images/' + image + '_large.png 2x';
396
+ icon_img.alt = tooltip;
397
+ button.appendChild(icon_img);
398
+
399
+ buttonGroup.appendChild(button);
400
+ }
401
+
402
+ if (buttonGroup.hasChildNodes()) {
403
+ toolbar.appendChild(buttonGroup);
404
+ }
405
+
406
+ var fmt_picker = document.createElement('select');
407
+ fmt_picker.classList = 'mpl-widget';
408
+ toolbar.appendChild(fmt_picker);
409
+ this.format_dropdown = fmt_picker;
410
+
411
+ for (var ind in mpl.extensions) {
412
+ var fmt = mpl.extensions[ind];
413
+ var option = document.createElement('option');
414
+ option.selected = fmt === mpl.default_extension;
415
+ option.innerHTML = fmt;
416
+ fmt_picker.appendChild(option);
417
+ }
418
+
419
+ var status_bar = document.createElement('span');
420
+ status_bar.classList = 'mpl-message';
421
+ toolbar.appendChild(status_bar);
422
+ this.message = status_bar;
423
+ };
424
+
425
+ mpl.figure.prototype.request_resize = function (x_pixels, y_pixels) {
426
+ // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,
427
+ // which will in turn request a refresh of the image.
428
+ this.send_message('resize', { width: x_pixels, height: y_pixels });
429
+ };
430
+
431
+ mpl.figure.prototype.send_message = function (type, properties) {
432
+ properties['type'] = type;
433
+ properties['figure_id'] = this.id;
434
+ this.ws.send(JSON.stringify(properties));
435
+ };
436
+
437
+ mpl.figure.prototype.send_draw_message = function () {
438
+ if (!this.waiting) {
439
+ this.waiting = true;
440
+ this.ws.send(JSON.stringify({ type: 'draw', figure_id: this.id }));
441
+ }
442
+ };
443
+
444
+ mpl.figure.prototype.handle_save = function (fig, _msg) {
445
+ var format_dropdown = fig.format_dropdown;
446
+ var format = format_dropdown.options[format_dropdown.selectedIndex].value;
447
+ fig.ondownload(fig, format);
448
+ };
449
+
450
+ mpl.figure.prototype.handle_resize = function (fig, msg) {
451
+ var size = msg['size'];
452
+ if (size[0] !== fig.canvas.width || size[1] !== fig.canvas.height) {
453
+ fig._resize_canvas(size[0], size[1], msg['forward']);
454
+ fig.send_message('refresh', {});
455
+ }
456
+ };
457
+
458
+ mpl.figure.prototype.handle_rubberband = function (fig, msg) {
459
+ var x0 = msg['x0'] / fig.ratio;
460
+ var y0 = (fig.canvas.height - msg['y0']) / fig.ratio;
461
+ var x1 = msg['x1'] / fig.ratio;
462
+ var y1 = (fig.canvas.height - msg['y1']) / fig.ratio;
463
+ x0 = Math.floor(x0) + 0.5;
464
+ y0 = Math.floor(y0) + 0.5;
465
+ x1 = Math.floor(x1) + 0.5;
466
+ y1 = Math.floor(y1) + 0.5;
467
+ var min_x = Math.min(x0, x1);
468
+ var min_y = Math.min(y0, y1);
469
+ var width = Math.abs(x1 - x0);
470
+ var height = Math.abs(y1 - y0);
471
+
472
+ fig.rubberband_context.clearRect(
473
+ 0,
474
+ 0,
475
+ fig.canvas.width / fig.ratio,
476
+ fig.canvas.height / fig.ratio
477
+ );
478
+
479
+ fig.rubberband_context.strokeRect(min_x, min_y, width, height);
480
+ };
481
+
482
+ mpl.figure.prototype.handle_figure_label = function (fig, msg) {
483
+ // Updates the figure title.
484
+ fig.header.textContent = msg['label'];
485
+ };
486
+
487
+ mpl.figure.prototype.handle_cursor = function (fig, msg) {
488
+ fig.canvas_div.style.cursor = msg['cursor'];
489
+ };
490
+
491
+ mpl.figure.prototype.handle_message = function (fig, msg) {
492
+ fig.message.textContent = msg['message'];
493
+ };
494
+
495
+ mpl.figure.prototype.handle_draw = function (fig, _msg) {
496
+ // Request the server to send over a new figure.
497
+ fig.send_draw_message();
498
+ };
499
+
500
+ mpl.figure.prototype.handle_image_mode = function (fig, msg) {
501
+ fig.image_mode = msg['mode'];
502
+ };
503
+
504
+ mpl.figure.prototype.handle_history_buttons = function (fig, msg) {
505
+ for (var key in msg) {
506
+ if (!(key in fig.buttons)) {
507
+ continue;
508
+ }
509
+ fig.buttons[key].disabled = !msg[key];
510
+ fig.buttons[key].setAttribute('aria-disabled', !msg[key]);
511
+ }
512
+ };
513
+
514
+ mpl.figure.prototype.handle_navigate_mode = function (fig, msg) {
515
+ if (msg['mode'] === 'PAN') {
516
+ fig.buttons['Pan'].classList.add('active');
517
+ fig.buttons['Zoom'].classList.remove('active');
518
+ } else if (msg['mode'] === 'ZOOM') {
519
+ fig.buttons['Pan'].classList.remove('active');
520
+ fig.buttons['Zoom'].classList.add('active');
521
+ } else {
522
+ fig.buttons['Pan'].classList.remove('active');
523
+ fig.buttons['Zoom'].classList.remove('active');
524
+ }
525
+ };
526
+
527
+ mpl.figure.prototype.updated_canvas_event = function () {
528
+ // Called whenever the canvas gets updated.
529
+ this.send_message('ack', {});
530
+ };
531
+
532
+ // A function to construct a web socket function for onmessage handling.
533
+ // Called in the figure constructor.
534
+ mpl.figure.prototype._make_on_message_function = function (fig) {
535
+ return function socket_on_message(evt) {
536
+ if (evt.data instanceof Blob) {
537
+ var img = evt.data;
538
+ if (img.type !== 'image/png') {
539
+ /* FIXME: We get "Resource interpreted as Image but
540
+ * transferred with MIME type text/plain:" errors on
541
+ * Chrome. But how to set the MIME type? It doesn't seem
542
+ * to be part of the websocket stream */
543
+ img.type = 'image/png';
544
+ }
545
+
546
+ /* Free the memory for the previous frames */
547
+ if (fig.imageObj.src) {
548
+ (window.URL || window.webkitURL).revokeObjectURL(
549
+ fig.imageObj.src
550
+ );
551
+ }
552
+
553
+ fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(
554
+ img
555
+ );
556
+ fig.updated_canvas_event();
557
+ fig.waiting = false;
558
+ return;
559
+ } else if (
560
+ typeof evt.data === 'string' &&
561
+ evt.data.slice(0, 21) === 'data:image/png;base64'
562
+ ) {
563
+ fig.imageObj.src = evt.data;
564
+ fig.updated_canvas_event();
565
+ fig.waiting = false;
566
+ return;
567
+ }
568
+
569
+ var msg = JSON.parse(evt.data);
570
+ var msg_type = msg['type'];
571
+
572
+ // Call the "handle_{type}" callback, which takes
573
+ // the figure and JSON message as its only arguments.
574
+ try {
575
+ var callback = fig['handle_' + msg_type];
576
+ } catch (e) {
577
+ console.log(
578
+ "No handler for the '" + msg_type + "' message type: ",
579
+ msg
580
+ );
581
+ return;
582
+ }
583
+
584
+ if (callback) {
585
+ try {
586
+ // console.log("Handling '" + msg_type + "' message: ", msg);
587
+ callback(fig, msg);
588
+ } catch (e) {
589
+ console.log(
590
+ "Exception inside the 'handler_" + msg_type + "' callback:",
591
+ e,
592
+ e.stack,
593
+ msg
594
+ );
595
+ }
596
+ }
597
+ };
598
+ };
599
+
600
+ function getModifiers(event) {
601
+ var mods = [];
602
+ if (event.ctrlKey) {
603
+ mods.push('ctrl');
604
+ }
605
+ if (event.altKey) {
606
+ mods.push('alt');
607
+ }
608
+ if (event.shiftKey) {
609
+ mods.push('shift');
610
+ }
611
+ if (event.metaKey) {
612
+ mods.push('meta');
613
+ }
614
+ return mods;
615
+ }
616
+
617
+ /*
618
+ * return a copy of an object with only non-object keys
619
+ * we need this to avoid circular references
620
+ * https://stackoverflow.com/a/24161582/3208463
621
+ */
622
+ function simpleKeys(original) {
623
+ return Object.keys(original).reduce(function (obj, key) {
624
+ if (typeof original[key] !== 'object') {
625
+ obj[key] = original[key];
626
+ }
627
+ return obj;
628
+ }, {});
629
+ }
630
+
631
+ mpl.figure.prototype.mouse_event = function (event, name) {
632
+ if (name === 'button_press') {
633
+ this.canvas.focus();
634
+ this.canvas_div.focus();
635
+ }
636
+
637
+ // from https://stackoverflow.com/q/1114465
638
+ var boundingRect = this.canvas.getBoundingClientRect();
639
+ var x = (event.clientX - boundingRect.left) * this.ratio;
640
+ var y = (event.clientY - boundingRect.top) * this.ratio;
641
+
642
+ this.send_message(name, {
643
+ x: x,
644
+ y: y,
645
+ button: event.button,
646
+ step: event.step,
647
+ buttons: event.buttons,
648
+ modifiers: getModifiers(event),
649
+ guiEvent: simpleKeys(event),
650
+ });
651
+
652
+ return false;
653
+ };
654
+
655
+ mpl.figure.prototype._key_event_extra = function (_event, _name) {
656
+ // Handle any extra behaviour associated with a key event
657
+ };
658
+
659
+ mpl.figure.prototype.key_event = function (event, name) {
660
+ // Prevent repeat events
661
+ if (name === 'key_press') {
662
+ if (event.key === this._key) {
663
+ return;
664
+ } else {
665
+ this._key = event.key;
666
+ }
667
+ }
668
+ if (name === 'key_release') {
669
+ this._key = null;
670
+ }
671
+
672
+ var value = '';
673
+ if (event.ctrlKey && event.key !== 'Control') {
674
+ value += 'ctrl+';
675
+ }
676
+ else if (event.altKey && event.key !== 'Alt') {
677
+ value += 'alt+';
678
+ }
679
+ else if (event.shiftKey && event.key !== 'Shift') {
680
+ value += 'shift+';
681
+ }
682
+
683
+ value += 'k' + event.key;
684
+
685
+ this._key_event_extra(event, name);
686
+
687
+ this.send_message(name, { key: value, guiEvent: simpleKeys(event) });
688
+ return false;
689
+ };
690
+
691
+ mpl.figure.prototype.toolbar_button_onclick = function (name) {
692
+ if (name === 'download') {
693
+ this.handle_save(this, null);
694
+ } else {
695
+ this.send_message('toolbar_button', { name: name });
696
+ }
697
+ };
698
+
699
+ mpl.figure.prototype.toolbar_button_onmouseover = function (tooltip) {
700
+ this.message.textContent = tooltip;
701
+ };
702
+
703
+ ///////////////// REMAINING CONTENT GENERATED BY embed_js.py /////////////////
704
+ // prettier-ignore
705
+ var _JSXTOOLS_RESIZE_OBSERVER=function(A){var t,i=new WeakMap,n=new WeakMap,a=new WeakMap,r=new WeakMap,o=new Set;function s(e){if(!(this instanceof s))throw new TypeError("Constructor requires 'new' operator");i.set(this,e)}function h(){throw new TypeError("Function is not a constructor")}function c(e,t,i,n){e=0 in arguments?Number(arguments[0]):0,t=1 in arguments?Number(arguments[1]):0,i=2 in arguments?Number(arguments[2]):0,n=3 in arguments?Number(arguments[3]):0,this.right=(this.x=this.left=e)+(this.width=i),this.bottom=(this.y=this.top=t)+(this.height=n),Object.freeze(this)}function d(){t=requestAnimationFrame(d);var s=new WeakMap,p=new Set;o.forEach((function(t){r.get(t).forEach((function(i){var r=t instanceof window.SVGElement,o=a.get(t),d=r?0:parseFloat(o.paddingTop),f=r?0:parseFloat(o.paddingRight),l=r?0:parseFloat(o.paddingBottom),u=r?0:parseFloat(o.paddingLeft),g=r?0:parseFloat(o.borderTopWidth),m=r?0:parseFloat(o.borderRightWidth),w=r?0:parseFloat(o.borderBottomWidth),b=u+f,F=d+l,v=(r?0:parseFloat(o.borderLeftWidth))+m,W=g+w,y=r?0:t.offsetHeight-W-t.clientHeight,E=r?0:t.offsetWidth-v-t.clientWidth,R=b+v,z=F+W,M=r?t.width:parseFloat(o.width)-R-E,O=r?t.height:parseFloat(o.height)-z-y;if(n.has(t)){var k=n.get(t);if(k[0]===M&&k[1]===O)return}n.set(t,[M,O]);var S=Object.create(h.prototype);S.target=t,S.contentRect=new c(u,d,M,O),s.has(i)||(s.set(i,[]),p.add(i)),s.get(i).push(S)}))})),p.forEach((function(e){i.get(e).call(e,s.get(e),e)}))}return s.prototype.observe=function(i){if(i instanceof window.Element){r.has(i)||(r.set(i,new Set),o.add(i),a.set(i,window.getComputedStyle(i)));var n=r.get(i);n.has(this)||n.add(this),cancelAnimationFrame(t),t=requestAnimationFrame(d)}},s.prototype.unobserve=function(i){if(i instanceof window.Element&&r.has(i)){var n=r.get(i);n.has(this)&&(n.delete(this),n.size||(r.delete(i),o.delete(i))),n.size||r.delete(i),o.size||cancelAnimationFrame(t)}},A.DOMRectReadOnly=c,A.ResizeObserver=s,A.ResizeObserverEntry=h,A}; // eslint-disable-line
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/js/mpl_tornado.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ /* This .js file contains functions for matplotlib's built-in
2
+ tornado-based server, that are not relevant when embedding WebAgg
3
+ in another web application. */
4
+
5
+ /* exported mpl_ondownload */
6
+ function mpl_ondownload(figure, format) {
7
+ window.open(figure.id + '/download.' + format, '_blank');
8
+ }
llava_video/lib/python3.10/site-packages/matplotlib/backends/web_backend/single_figure.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/page.css" type="text/css">
5
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/boilerplate.css" type="text/css">
6
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/fbm.css" type="text/css">
7
+ <link rel="stylesheet" href="{{ prefix }}/_static/css/mpl.css" type="text/css">
8
+ <script src="{{ prefix }}/_static/js/mpl_tornado.js"></script>
9
+ <script src="{{ prefix }}/js/mpl.js"></script>
10
+ <script>
11
+ function ready(fn) {
12
+ if (document.readyState != "loading") {
13
+ fn();
14
+ } else {
15
+ document.addEventListener("DOMContentLoaded", fn);
16
+ }
17
+ }
18
+
19
+ ready(
20
+ function () {
21
+ var websocket_type = mpl.get_websocket_type();
22
+ var uri = "{{ ws_uri }}" + {{ str(fig_id) }} + "/ws";
23
+ if (window.location.protocol === 'https:') uri = uri.replace('ws:', 'wss:')
24
+ var websocket = new websocket_type(uri);
25
+ var fig = new mpl.figure(
26
+ {{ str(fig_id) }}, websocket, mpl_ondownload,
27
+ document.getElementById("figure"));
28
+ }
29
+ );
30
+ </script>
31
+
32
+ <title>matplotlib</title>
33
+ </head>
34
+
35
+ <body>
36
+ <div id="mpl-warnings" class="mpl-warnings"></div>
37
+ <div id="figure" style="margin: 10px 10px;"></div>
38
+ </body>
39
+ </html>
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_conj.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_conj_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_conj(Tensor(a) self) -> Tensor(a)
26
+ inline at::Tensor _conj(const at::Tensor & self) {
27
+ return at::_ops::_conj::call(self);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_convert_indices_from_csr_to_coo_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _convert_indices_from_csr_to_coo(const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32=false, bool transpose=false);
21
+ TORCH_API at::Tensor & _convert_indices_from_csr_to_coo_out(at::Tensor & out, const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32=false, bool transpose=false);
22
+ TORCH_API at::Tensor & _convert_indices_from_csr_to_coo_outf(const at::Tensor & crow_indices, const at::Tensor & col_indices, bool out_int32, bool transpose, at::Tensor & out);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cummin_helper_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _cummin_helper {
18
+ using schema = void (const at::Tensor &, at::Tensor &, at::Tensor &, int64_t);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_cummin_helper")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()")
24
+ static void call(const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim);
25
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_log_cuda_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_log(at::TensorList self);
21
+ TORCH_API void _foreach_log_(at::TensorList self);
22
+
23
+ } // namespace cuda
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_pow_native.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_list_kernel_slow(at::TensorList self, at::TensorList exponent);
20
+ TORCH_API void _foreach_pow_List_out(at::TensorList self, at::TensorList exponent, at::TensorList out);
21
+ TORCH_API void foreach_tensor_pow_list_kernel_slow_(at::TensorList self, at::TensorList exponent);
22
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_list_kernel_cuda(at::TensorList self, at::TensorList exponent);
23
+ TORCH_API void foreach_tensor_pow_list_kernel_cuda_(at::TensorList self, at::TensorList exponent);
24
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_scalar_kernel_slow(at::TensorList self, const at::Scalar & exponent);
25
+ TORCH_API void _foreach_pow_Scalar_out(at::TensorList self, const at::Scalar & exponent, at::TensorList out);
26
+ TORCH_API void foreach_tensor_pow_scalar_kernel_slow_(at::TensorList self, const at::Scalar & exponent);
27
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_scalar_kernel_cuda(at::TensorList self, const at::Scalar & exponent);
28
+ TORCH_API void foreach_tensor_pow_scalar_kernel_cuda_(at::TensorList self, const at::Scalar & exponent);
29
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_scalarlist_kernel_slow(at::TensorList self, at::ArrayRef<at::Scalar> exponent);
30
+ TORCH_API void _foreach_pow_ScalarList_out(at::TensorList self, at::ArrayRef<at::Scalar> exponent, at::TensorList out);
31
+ TORCH_API void foreach_tensor_pow_scalarlist_kernel_slow_(at::TensorList self, at::ArrayRef<at::Scalar> exponent);
32
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_pow_scalarlist_kernel_cuda(at::TensorList self, at::ArrayRef<at::Scalar> exponent);
33
+ TORCH_API void foreach_tensor_pow_scalarlist_kernel_cuda_(at::TensorList self, at::ArrayRef<at::Scalar> exponent);
34
+ TORCH_API ::std::vector<at::Tensor> foreach_scalar_pow_list_kernel_slow(const at::Scalar & self, at::TensorList exponent);
35
+ TORCH_API ::std::vector<at::Tensor> foreach_scalar_pow_list_kernel_cuda(const at::Scalar & self, at::TensorList exponent);
36
+ } // namespace native
37
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_zero_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_zero(at::TensorList self);
21
+ TORCH_API void _foreach_zero_out(at::TensorList out, at::TensorList self);
22
+ TORCH_API void _foreach_zero_outf(at::TensorList self, at::TensorList out);
23
+ TORCH_API void _foreach_zero_(at::TensorList self);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _gather_sparse_backward {
18
+ using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_gather_sparse_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & grad);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & grad);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_check_errors.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_linalg_check_errors_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_linalg_check_errors(Tensor info, str api_name, *, bool is_matrix) -> ()
26
+ inline void _linalg_check_errors(const at::Tensor & info, c10::string_view api_name, bool is_matrix) {
27
+ return at::_ops::_linalg_check_errors::call(info, api_name, is_matrix);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_pin_memory.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_pin_memory_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_pin_memory(Tensor self, Device? device=None) -> Tensor
26
+ inline at::Tensor _pin_memory(const at::Tensor & self, ::std::optional<at::Device> device=::std::nullopt) {
27
+ return at::_ops::_pin_memory::call(self, device);
28
+ }
29
+
30
+ // aten::_pin_memory.out(Tensor self, Device? device=None, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & _pin_memory_out(at::Tensor & out, const at::Tensor & self, ::std::optional<at::Device> device=::std::nullopt) {
32
+ return at::_ops::_pin_memory_out::call(self, device, out);
33
+ }
34
+ // aten::_pin_memory.out(Tensor self, Device? device=None, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & _pin_memory_outf(const at::Tensor & self, ::std::optional<at::Device> device, at::Tensor & out) {
36
+ return at::_ops::_pin_memory_out::call(self, device, out);
37
+ }
38
+
39
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor _reshape_alias(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride);
20
+ } // namespace native
21
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_scaled_dot_product_fused_attention_overrideable_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor attn_bias, bool[4] grad_input_mask, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value, Tensor grad_attn_bias)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_fused_attention_overrideable_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & attn_bias, ::std::array<bool,4> grad_input_mask, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
27
+ return at::_ops::_scaled_dot_product_fused_attention_overrideable_backward::call(grad_out, query, key, value, attn_bias, grad_input_mask, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_fused_attention_overrideable_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & attn_bias, ::std::array<bool,4> grad_input_mask, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
32
+ return at::_ops::_scaled_dot_product_fused_attention_overrideable_backward::call(grad_out, query, key, value, attn_bias, grad_input_mask, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
33
+ }
34
+ }
35
+
36
+ // aten::_scaled_dot_product_fused_attention_overrideable_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor attn_bias, bool[4] grad_input_mask, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value, Tensor grad_attn_bias)
37
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_fused_attention_overrideable_backward_symint(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & attn_bias, ::std::array<bool,4> grad_input_mask, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
38
+ return at::_ops::_scaled_dot_product_fused_attention_overrideable_backward::call(grad_out, query, key, value, attn_bias, grad_input_mask, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_fused_attention_overrideable_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & attn_bias, ::std::array<bool,4> grad_input_mask, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
43
+ return at::_ops::_scaled_dot_product_fused_attention_overrideable_backward::call(grad_out, query, key, value, attn_bias, grad_input_mask, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
44
+ }
45
+ }
46
+
47
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_triton_multi_head_attention_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _triton_multi_head_attention_out(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional<at::Tensor> & mask, at::Tensor & out);
20
+ TORCH_API at::Tensor triton_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional<at::Tensor> & mask={});
21
+ } // namespace native
22
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_triton_scaled_dot_attention.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_triton_scaled_dot_attention_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_triton_scaled_dot_attention(Tensor q, Tensor k, Tensor v, float dropout_p=0.0) -> Tensor
26
+ inline at::Tensor _triton_scaled_dot_attention(const at::Tensor & q, const at::Tensor & k, const at::Tensor & v, double dropout_p=0.0) {
27
+ return at::_ops::_triton_scaled_dot_attention::call(q, k, v, dropout_p);
28
+ }
29
+
30
+ // aten::_triton_scaled_dot_attention.out(Tensor q, Tensor k, Tensor v, float dropout_p=0.0, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & _triton_scaled_dot_attention_out(at::Tensor & out, const at::Tensor & q, const at::Tensor & k, const at::Tensor & v, double dropout_p=0.0) {
32
+ return at::_ops::_triton_scaled_dot_attention_out::call(q, k, v, dropout_p, out);
33
+ }
34
+ // aten::_triton_scaled_dot_attention.out(Tensor q, Tensor k, Tensor v, float dropout_p=0.0, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & _triton_scaled_dot_attention_outf(const at::Tensor & q, const at::Tensor & k, const at::Tensor & v, double dropout_p, at::Tensor & out) {
36
+ return at::_ops::_triton_scaled_dot_attention_out::call(q, k, v, dropout_p, out);
37
+ }
38
+
39
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_unique2_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _unique2(const at::Tensor & self, bool sorted=true, bool return_inverse=false, bool return_counts=false);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _upsample_bicubic2d_aa_backward_grad_input {
18
+ using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, ::std::optional<double>, ::std::optional<double>, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_bicubic2d_aa_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_bicubic2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input);
26
+ };
27
+
28
+ struct TORCH_API _upsample_bicubic2d_aa_backward {
29
+ using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, ::std::optional<double>, ::std::optional<double>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_upsample_bicubic2d_aa_backward")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w);
37
+ };
38
+
39
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API addcdiv_out {
18
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcdiv")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcdiv.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API addcdiv {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcdiv")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value);
37
+ };
38
+
39
+ struct TORCH_API addcdiv_ {
40
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addcdiv_")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)")
46
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value);
48
+ };
49
+
50
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/align_as_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API align_as {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::align_as")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "align_as(Tensor self, Tensor other) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/alpha_dropout_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor alpha_dropout(const at::Tensor & input, double p, bool train);
20
+ TORCH_API at::Tensor & alpha_dropout_(at::Tensor & self, double p, bool train);
21
+ } // namespace native
22
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/any_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor any(const at::Tensor & self, int64_t dim, bool keepdim=false);
21
+ TORCH_API at::Tensor any(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
22
+ TORCH_API at::Tensor any(const at::Tensor & self);
23
+
24
+ } // namespace compositeexplicitautogradnonfunctional
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_backward.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/binary_cross_entropy_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
26
+ inline at::Tensor binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
27
+ return at::_ops::binary_cross_entropy_backward::call(grad_output, self, target, weight, reduction);
28
+ }
29
+
30
+ // aten::binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
31
+ inline at::Tensor & binary_cross_entropy_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
32
+ return at::_ops::binary_cross_entropy_backward_grad_input::call(grad_output, self, target, weight, reduction, grad_input);
33
+ }
34
+ // aten::binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
35
+ inline at::Tensor & binary_cross_entropy_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & grad_input) {
36
+ return at::_ops::binary_cross_entropy_backward_grad_input::call(grad_output, self, target, weight, reduction, grad_input);
37
+ }
38
+
39
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_left_shift_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_bitwise_left_shift_Tensor : public TensorIteratorBase {
21
+
22
+
23
+ void meta(const at::Tensor & self, const at::Tensor & other);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/copy_sparse_to_sparse_native.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor copy_sparse_to_sparse(const at::Tensor & self, const at::Tensor & src, bool non_blocking=false);
20
+ TORCH_API at::Tensor & copy_sparse_to_sparse_out(const at::Tensor & self, const at::Tensor & src, bool non_blocking, at::Tensor & out);
21
+ TORCH_API at::Tensor & copy_sparse_(at::Tensor & self, const at::Tensor & src, bool non_blocking=false);
22
+ } // namespace native
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cos_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor cos(const at::Tensor & self);
21
+ TORCH_API at::Tensor & cos_(at::Tensor & self);
22
+
23
+ } // namespace compositeexplicitautogradnonfunctional
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_grid_sampler_backward_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API cudnn_grid_sampler_backward {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_grid_sampler_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output);
26
+ };
27
+
28
+ struct TORCH_API cudnn_grid_sampler_backward_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_grid_sampler_backward")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_grid_sampler_backward.out(Tensor self, Tensor grid, Tensor grad_output, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output, at::Tensor & out0, at::Tensor & out1);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output, at::Tensor & out0, at::Tensor & out1);
37
+ };
38
+
39
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/detach_copy_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & detach_copy_out(at::Tensor & out, const at::Tensor & self);
21
+ TORCH_API at::Tensor & detach_copy_outf(const at::Tensor & self, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/elu_backward_meta_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor elu_backward(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
21
+ TORCH_API at::Tensor & elu_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
22
+ TORCH_API at::Tensor & elu_backward_outf(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result, at::Tensor & grad_input);
23
+
24
+ } // namespace meta
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/expand_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API expand {
18
+ using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::expand")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a)")
24
+ static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, bool implicit);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fbgemm_pack_quantized_matrix_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input);
21
+ TORCH_API at::Tensor fbgemm_pack_quantized_matrix(const at::Tensor & input, int64_t K, int64_t N);
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fill_native.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor fill(const at::Tensor & self, const at::Scalar & value);
20
+ TORCH_API at::Tensor & fill_Scalar_out(const at::Tensor & self, const at::Scalar & value, at::Tensor & out);
21
+ TORCH_API at::Tensor & fill_(at::Tensor & self, const at::Scalar & value);
22
+ TORCH_API at::Tensor & fill_nested_(at::Tensor & self, const at::Scalar & value);
23
+ TORCH_API at::Tensor & fill_sparse_csr_(at::Tensor & self, const at::Scalar & value);
24
+ TORCH_API at::Tensor & fill_meta_(at::Tensor & self, const at::Scalar & value);
25
+ TORCH_API at::Tensor & fill_quantized_(at::Tensor & self, const at::Scalar & value);
26
+ TORCH_API at::Tensor fill(const at::Tensor & self, const at::Tensor & value);
27
+ TORCH_API at::Tensor & fill_Tensor_out(const at::Tensor & self, const at::Tensor & value, at::Tensor & out);
28
+ TORCH_API at::Tensor & fill_(at::Tensor & self, const at::Tensor & value);
29
+ TORCH_API at::Tensor & fill_nested_(at::Tensor & self, const at::Tensor & value);
30
+ TORCH_API at::Tensor & fill_meta_(at::Tensor & self, const at::Tensor & value);
31
+ TORCH_API at::Tensor & fill_quantized_(at::Tensor & self, const at::Tensor & value);
32
+ } // namespace native
33
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_reduce_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API index_reduce_out {
18
+ using schema = at::Tensor & (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_reduce")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_reduce.out(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API index_reduce_ {
29
+ using schema = at::Tensor & (at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_reduce_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_reduce_(Tensor(a!) self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self);
37
+ };
38
+
39
+ struct TORCH_API index_reduce {
40
+ using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::index_reduce")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor")
46
+ static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self);
47
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self);
48
+ };
49
+
50
+ }} // namespace at::_ops