mpl-depth-style 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mpl_depth_style/__init__.py +10 -0
- mpl_depth_style/_axes.py +521 -0
- mpl_depth_style/_axes_style.py +229 -0
- mpl_depth_style/_geometry.py +191 -0
- mpl_depth_style/charts.py +108 -0
- mpl_depth_style/scene.py +314 -0
- mpl_depth_style/surfaces.py +50 -0
- mpl_depth_style/volumes.py +44 -0
- mpl_depth_style-0.6.1.dist-info/METADATA +77 -0
- mpl_depth_style-0.6.1.dist-info/RECORD +12 -0
- mpl_depth_style-0.6.1.dist-info/WHEEL +5 -0
- mpl_depth_style-0.6.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Scientific 3D graphics powered by VTK and Matplotlib.
|
|
2
|
+
|
|
3
|
+
Importing this package registers the Matplotlib projection ``vtk3d``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ._axes import VtkAxes
|
|
7
|
+
from ._axes_style import ax3D_setting, plot_rc
|
|
8
|
+
from .scene import Graphic
|
|
9
|
+
|
|
10
|
+
__all__ = ["Graphic", "VtkAxes", "ax3D_setting", "plot_rc"]
|
mpl_depth_style/_axes.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
"""Native Matplotlib 3D axes with a transparent VTK geometry layer."""
|
|
2
|
+
from itertools import product
|
|
3
|
+
from operator import index
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from PIL import Image
|
|
7
|
+
import vtk
|
|
8
|
+
from vtk.util.numpy_support import vtk_to_numpy
|
|
9
|
+
from matplotlib.artist import Artist, allow_rasterization
|
|
10
|
+
from matplotlib.projections import register_projection
|
|
11
|
+
from matplotlib.tri import Triangulation
|
|
12
|
+
from matplotlib.transforms import Bbox
|
|
13
|
+
from mpl_toolkits.mplot3d import Axes3D
|
|
14
|
+
|
|
15
|
+
from . import charts, surfaces, volumes
|
|
16
|
+
from ._geometry import surface_arrays, vertices
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _sampling_factor(value):
|
|
20
|
+
try:
|
|
21
|
+
factor = index(value)
|
|
22
|
+
except TypeError as exc:
|
|
23
|
+
raise ValueError("antialiasing must be an integer from 1 to 4") from exc
|
|
24
|
+
if not 1 <= factor <= 4:
|
|
25
|
+
raise ValueError("antialiasing must be an integer from 1 to 4")
|
|
26
|
+
return factor
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _valid_bounds(bounds):
|
|
30
|
+
return np.isfinite(bounds).all(axis=(1, 2)) & (bounds[..., 0] <= bounds[..., 1]).all(axis=1)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _bounds_union(bounds):
|
|
34
|
+
return np.column_stack((bounds[..., 0].min(axis=0), bounds[..., 1].max(axis=0)))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Viewport(Artist):
|
|
38
|
+
def __init__(self, ax):
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.scene = ax
|
|
41
|
+
self.set_zorder(1)
|
|
42
|
+
self.set_in_layout(False)
|
|
43
|
+
|
|
44
|
+
@staticmethod
|
|
45
|
+
def _nearest(start, stop, low, high, size):
|
|
46
|
+
centers = np.arange(start, stop) + .5
|
|
47
|
+
idx = np.floor((centers - low) * (size / (high - low))).astype(np.intp)
|
|
48
|
+
np.clip(idx, 0, size-1, out=idx)
|
|
49
|
+
return idx
|
|
50
|
+
|
|
51
|
+
@allow_rasterization
|
|
52
|
+
def draw(self, renderer):
|
|
53
|
+
if self.get_visible() and any(h.get_visible() for h in self.scene.handles):
|
|
54
|
+
self._draw_frame(renderer)
|
|
55
|
+
self.stale = False
|
|
56
|
+
|
|
57
|
+
def _draw_frame(self, renderer):
|
|
58
|
+
box = self.scene.bbox
|
|
59
|
+
clipped = Bbox.intersection(box, Bbox.from_bounds(0, 0, *renderer.get_canvas_width_height()))
|
|
60
|
+
if clipped is None or box.width <= 0 or box.height <= 0:
|
|
61
|
+
return
|
|
62
|
+
mag = renderer.get_image_magnification()
|
|
63
|
+
# Snap the visible extent to the same pixel convention as BboxImage.
|
|
64
|
+
left, bottom, right, top = clipped.extents * mag
|
|
65
|
+
x0 = int(np.floor(left+.5))
|
|
66
|
+
y0 = int(np.ceil(bottom-.5-1e-8))
|
|
67
|
+
x1 = int(np.floor(right+.5+1e-8))
|
|
68
|
+
y1 = int(np.ceil(top-.5))
|
|
69
|
+
if x0 >= x1 or y0 >= y1:
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
width, height = (max(1, round(v*mag)) for v in box.size)
|
|
73
|
+
rgba = self.scene.pixels(width, height)
|
|
74
|
+
# VTK has already downsampled its framebuffer to the output scale.
|
|
75
|
+
# Only account for subpixel placement and clipping on the final canvas.
|
|
76
|
+
columns = self._nearest(x0, x1, box.x0*mag, box.x1*mag, width)
|
|
77
|
+
rows = self._nearest(y0, y1, box.y0*mag, box.y1*mag, height)
|
|
78
|
+
extent = getattr(self.scene, "_viewport_extent", None)
|
|
79
|
+
if extent is not None:
|
|
80
|
+
left, bottom, right, top = extent
|
|
81
|
+
first_col, last_col = np.searchsorted(columns, (left, right))
|
|
82
|
+
first_row, last_row = np.searchsorted(rows, (bottom, top))
|
|
83
|
+
if first_col >= last_col or first_row >= last_row:
|
|
84
|
+
return
|
|
85
|
+
columns = columns[first_col:last_col]
|
|
86
|
+
rows = rows[first_row:last_row]
|
|
87
|
+
x0 += first_col
|
|
88
|
+
y0 += first_row
|
|
89
|
+
if np.all(np.diff(columns) == 1) and np.all(np.diff(rows) == 1):
|
|
90
|
+
rgba = rgba[rows[0]:rows[-1]+1, columns[0]:columns[-1]+1]
|
|
91
|
+
else:
|
|
92
|
+
rgba = rgba[rows[:, None], columns]
|
|
93
|
+
gc = renderer.new_gc()
|
|
94
|
+
try:
|
|
95
|
+
self._set_gc_clip(gc)
|
|
96
|
+
gc.set_alpha(1.)
|
|
97
|
+
renderer.draw_image(gc, x0/mag, y0/mag, np.ascontiguousarray(rgba))
|
|
98
|
+
finally:
|
|
99
|
+
gc.restore()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class VtkAxes(Axes3D):
|
|
103
|
+
"""Matplotlib owns the axes. Only the three-dimensional data pass goes to VTK."""
|
|
104
|
+
name = "vtk3d"
|
|
105
|
+
|
|
106
|
+
def __init__(self, *args, antialiasing=2, **kwargs):
|
|
107
|
+
self._antialiasing = _sampling_factor(antialiasing)
|
|
108
|
+
self._fit_aspect = False
|
|
109
|
+
self._box_aspect_dirty = False
|
|
110
|
+
self._limits_dirty = False
|
|
111
|
+
super().__init__(*args, **kwargs)
|
|
112
|
+
self.renderer = vtk.vtkRenderer()
|
|
113
|
+
self.window = vtk.vtkRenderWindow()
|
|
114
|
+
self.window.SetOffScreenRendering(True)
|
|
115
|
+
self.window.SwapBuffersOff()
|
|
116
|
+
self.window.SetMultiSamples(0)
|
|
117
|
+
self.window.SetAlphaBitPlanes(1)
|
|
118
|
+
self.window.AddRenderer(self.renderer)
|
|
119
|
+
self.renderer.SetBackground(0,0,0)
|
|
120
|
+
self.renderer.SetBackgroundAlpha(0)
|
|
121
|
+
self.renderer.UseDepthPeelingOn()
|
|
122
|
+
self.renderer.SetMaximumNumberOfPeels(32)
|
|
123
|
+
self.renderer.SetOcclusionRatio(0)
|
|
124
|
+
self.capture = vtk.vtkWindowToImageFilter()
|
|
125
|
+
self.capture.SetInput(self.window)
|
|
126
|
+
self.capture.SetInputBufferTypeToRGBA()
|
|
127
|
+
self.capture.ReadFrontBufferOff()
|
|
128
|
+
self.capture.ShouldRerenderOff()
|
|
129
|
+
self._pixel_buffer = vtk.vtkUnsignedCharArray()
|
|
130
|
+
self.camera = self.renderer.GetActiveCamera()
|
|
131
|
+
self.handles = []
|
|
132
|
+
self._viewport = _Viewport(self)
|
|
133
|
+
self.add_artist(self._viewport)
|
|
134
|
+
self._close_id = self.figure.canvas.mpl_connect("close_event", self._close)
|
|
135
|
+
self._viewport_key = None
|
|
136
|
+
self._viewport_frame = None
|
|
137
|
+
self._viewport_extent = None
|
|
138
|
+
|
|
139
|
+
def get_antialiasing(self):
|
|
140
|
+
"""Return the VTK render scale per output pixel dimension."""
|
|
141
|
+
return self._antialiasing
|
|
142
|
+
|
|
143
|
+
def set_antialiasing(self, factor):
|
|
144
|
+
"""Select 1× native rendering or 2× to 4× supersampling."""
|
|
145
|
+
self._antialiasing = _sampling_factor(factor)
|
|
146
|
+
self.stale = True
|
|
147
|
+
|
|
148
|
+
def set_aspect(self, aspect, adjustable=None, *args, **kwargs):
|
|
149
|
+
"""Set the data aspect and preserve equal scaling when fitting the scene."""
|
|
150
|
+
super().set_aspect(aspect, adjustable, *args, **kwargs)
|
|
151
|
+
self._fit_aspect = aspect != "auto"
|
|
152
|
+
self._box_aspect_dirty = False
|
|
153
|
+
|
|
154
|
+
def set_box_aspect(self, aspect, *, zoom=1):
|
|
155
|
+
"""Set the display-box proportions and zoom explicitly."""
|
|
156
|
+
super().set_box_aspect(aspect, zoom=zoom)
|
|
157
|
+
self._fit_aspect = False
|
|
158
|
+
|
|
159
|
+
def get_box_aspect(self):
|
|
160
|
+
self._fit_if_needed()
|
|
161
|
+
if self._box_aspect_dirty and self._fit_aspect and self.get_adjustable() == "box":
|
|
162
|
+
self.set_aspect(self.get_aspect(), "box")
|
|
163
|
+
return super().get_box_aspect()
|
|
164
|
+
|
|
165
|
+
def get_proj(self):
|
|
166
|
+
# Axes3D projects with the cached box proportions.
|
|
167
|
+
self.get_box_aspect()
|
|
168
|
+
return super().get_proj()
|
|
169
|
+
|
|
170
|
+
def clear_scene(self):
|
|
171
|
+
"""Remove VTK plots while keeping axes settings and Matplotlib artists."""
|
|
172
|
+
for handle in self.handles.copy():
|
|
173
|
+
handle.remove()
|
|
174
|
+
|
|
175
|
+
def clear(self):
|
|
176
|
+
if hasattr(self, "handles"):
|
|
177
|
+
self.clear_scene()
|
|
178
|
+
super().clear()
|
|
179
|
+
if hasattr(self, "_viewport"):
|
|
180
|
+
self.renderer.RemoveAllLights()
|
|
181
|
+
self.add_artist(self._viewport)
|
|
182
|
+
|
|
183
|
+
def fit(self):
|
|
184
|
+
"""Autoscale from the current visible VTK geometry."""
|
|
185
|
+
if self._update_data_limits():
|
|
186
|
+
super().autoscale_view()
|
|
187
|
+
if self._fit_aspect:
|
|
188
|
+
self.set_aspect(self.get_aspect(), self.get_adjustable())
|
|
189
|
+
|
|
190
|
+
def _update_data_limits(self):
|
|
191
|
+
visible = [handle for handle in self.handles if handle.get_visible()]
|
|
192
|
+
bounds = np.asarray([handle._raw_bounds() for handle in visible]).reshape(-1, 3, 2)
|
|
193
|
+
valid = _valid_bounds(bounds)
|
|
194
|
+
bounds = bounds[valid]
|
|
195
|
+
# Matplotlib reads the current limits while applying the new bounds.
|
|
196
|
+
self._limits_dirty = False
|
|
197
|
+
if not len(bounds):
|
|
198
|
+
return False
|
|
199
|
+
axes = (self.xaxis, self.yaxis, self.zaxis)
|
|
200
|
+
if all(axis.get_scale() == "linear" for axis in axes):
|
|
201
|
+
# Two corners encode the full union without allocating a path for each artist.
|
|
202
|
+
limits = _bounds_union(bounds)
|
|
203
|
+
self.xy_dataLim.update_from_data_xy(limits[:2, :].T, ignore=True)
|
|
204
|
+
self.zz_dataLim.update_from_data_x(limits[2], ignore=True)
|
|
205
|
+
return True
|
|
206
|
+
|
|
207
|
+
handles = [handle for handle, usable in zip(visible, valid) if usable]
|
|
208
|
+
updates = (self.xy_dataLim.update_from_data_x, self.xy_dataLim.update_from_data_y,
|
|
209
|
+
self.zz_dataLim.update_from_data_x)
|
|
210
|
+
for dim, (axis, update) in enumerate(zip(axes, updates)):
|
|
211
|
+
ends = bounds[:, dim, :]
|
|
212
|
+
if axis.get_scale() != "linear":
|
|
213
|
+
ends = axis._nan_out_of_scale_range(ends)
|
|
214
|
+
# An out-of-scale bound can hide valid extrema inside the data.
|
|
215
|
+
missing = ~np.isfinite(ends).all(axis=1)
|
|
216
|
+
samples = [axis._nan_out_of_scale_range(vertices(handle.data)[:, dim])
|
|
217
|
+
for handle, needs_samples in zip(handles, missing)
|
|
218
|
+
if needs_samples and handle.data.IsA("vtkPolyData")]
|
|
219
|
+
if samples:
|
|
220
|
+
ends = np.concatenate([ends.ravel(), *samples])
|
|
221
|
+
ends = ends[np.isfinite(ends)]
|
|
222
|
+
if ends.size:
|
|
223
|
+
update(ends, ignore=True)
|
|
224
|
+
return True
|
|
225
|
+
|
|
226
|
+
def autoscale_view(self, tight=None, scalex=True, scaley=True, scalez=True):
|
|
227
|
+
"""Apply native autoscaling to up-to-date VTK data bounds."""
|
|
228
|
+
if self._limits_dirty:
|
|
229
|
+
self._update_data_limits()
|
|
230
|
+
super().autoscale_view(tight=tight, scalex=scalex, scaley=scaley, scalez=scalez)
|
|
231
|
+
|
|
232
|
+
def autoscale(self, enable=True, axis="both", tight=None):
|
|
233
|
+
"""Set the autoscaling mode and refresh the selected limits."""
|
|
234
|
+
super().autoscale(enable=enable, axis=axis, tight=tight)
|
|
235
|
+
self._unstale_viewLim()
|
|
236
|
+
|
|
237
|
+
def _fit_if_needed(self):
|
|
238
|
+
if self._limits_dirty:
|
|
239
|
+
self.fit()
|
|
240
|
+
|
|
241
|
+
def get_xlim(self):
|
|
242
|
+
self._fit_if_needed()
|
|
243
|
+
return super().get_xlim()
|
|
244
|
+
|
|
245
|
+
get_xlim3d = get_xlim
|
|
246
|
+
|
|
247
|
+
def get_ylim(self):
|
|
248
|
+
self._fit_if_needed()
|
|
249
|
+
return super().get_ylim()
|
|
250
|
+
|
|
251
|
+
get_ylim3d = get_ylim
|
|
252
|
+
|
|
253
|
+
def get_zlim(self):
|
|
254
|
+
self._fit_if_needed()
|
|
255
|
+
return super().get_zlim()
|
|
256
|
+
|
|
257
|
+
get_zlim3d = get_zlim
|
|
258
|
+
|
|
259
|
+
def _set_lim3d(self, axis, *args, **kwargs):
|
|
260
|
+
self._fit_if_needed()
|
|
261
|
+
limits = super()._set_lim3d(axis, *args, **kwargs)
|
|
262
|
+
self._box_aspect_dirty = True
|
|
263
|
+
return limits
|
|
264
|
+
|
|
265
|
+
def _set_axis_scale(self, axis, value, **kwargs):
|
|
266
|
+
super()._set_axis_scale(axis, value, **kwargs)
|
|
267
|
+
if getattr(self, "handles", ()):
|
|
268
|
+
self._limits_dirty = True
|
|
269
|
+
|
|
270
|
+
def draw(self, renderer):
|
|
271
|
+
self._fit_if_needed()
|
|
272
|
+
super().draw(renderer)
|
|
273
|
+
|
|
274
|
+
def _sync_camera(self, projection, affine):
|
|
275
|
+
# Matplotlib first projects data with get_proj(), then maps xy with
|
|
276
|
+
# transData. OpenGL instead takes clip coordinates in [-w,w].
|
|
277
|
+
limits = np.array(self.get_w_lims()).reshape(3,2)
|
|
278
|
+
visible = [handle for handle in self.handles if handle.get_visible()]
|
|
279
|
+
scales = [axis.get_transform() for axis in (self.xaxis,self.yaxis,self.zaxis)]
|
|
280
|
+
nonlinear = tuple(axis.get_scale() != "linear" for axis in (self.xaxis,self.yaxis,self.zaxis))
|
|
281
|
+
for i in range(3):
|
|
282
|
+
if nonlinear[i]:
|
|
283
|
+
limits[i] = scales[i].transform(limits[i])
|
|
284
|
+
for h in visible:
|
|
285
|
+
h._sync_geometry(scales,nonlinear)
|
|
286
|
+
box = self.bbox
|
|
287
|
+
ndc = np.array([[2/box.width,0,-1-2*box.x0/box.width],
|
|
288
|
+
[0,2/box.height,-1-2*box.y0/box.height], [0,0,1]])
|
|
289
|
+
plane = ndc @ affine
|
|
290
|
+
m = projection
|
|
291
|
+
combined = m.copy()
|
|
292
|
+
combined[:2] = plane[:2] @ m[[0,1,3]]
|
|
293
|
+
render_bounds = np.asarray([handle._render_bounds() for handle in visible]).reshape(-1, 3, 2)
|
|
294
|
+
valid = _valid_bounds(render_bounds)
|
|
295
|
+
bounds = _bounds_union(np.concatenate((np.sort(limits, axis=1)[None], render_bounds[valid])))
|
|
296
|
+
# Include the visible axis box so extreme zoom still has a valid
|
|
297
|
+
# depth interval when data behind the eye is clipped by OpenGL.
|
|
298
|
+
corners = np.array(list(product(*limits)) + list(product(*bounds)))
|
|
299
|
+
clip = np.column_stack((corners,np.ones(len(corners)))) @ m.T
|
|
300
|
+
front = clip[:,3] > 1e-9
|
|
301
|
+
depth = clip[front,2]/clip[front,3]
|
|
302
|
+
lo, hi = depth.min(), depth.max()
|
|
303
|
+
scale = 1.8/max(hi-lo,1e-8)
|
|
304
|
+
combined[2] = scale*(m[2] - .5*(lo+hi)*m[3])
|
|
305
|
+
# A conventional physical camera gives lights a meaningful view frame.
|
|
306
|
+
# Its view matrix is factored out of the explicit projection below.
|
|
307
|
+
center = limits.mean(axis=1)
|
|
308
|
+
right, up = m[0,:3], m[1,:3]
|
|
309
|
+
back = np.cross(right,up)
|
|
310
|
+
back /= max(np.linalg.norm(back),1e-30)
|
|
311
|
+
up = up/max(np.linalg.norm(up),1e-30)
|
|
312
|
+
billboard_right = np.cross(up,back)
|
|
313
|
+
marker_matrix = np.eye(4)
|
|
314
|
+
marker_matrix[:3,:3] = np.column_stack((billboard_right,up,back))
|
|
315
|
+
for handle in visible:
|
|
316
|
+
if hasattr(handle,"_marker_transform"):
|
|
317
|
+
handle._marker_transform.SetMatrix(marker_matrix.ravel())
|
|
318
|
+
distance = max(np.linalg.norm(np.ptp(limits,axis=1)), 1)
|
|
319
|
+
self.camera.SetPosition(*(center+back*distance*2))
|
|
320
|
+
self.camera.SetFocalPoint(*center)
|
|
321
|
+
self.camera.SetViewUp(*up)
|
|
322
|
+
modelview = self.camera.GetModelViewTransformMatrix()
|
|
323
|
+
vm = np.array([[modelview.GetElement(i,j) for j in range(4)] for i in range(4)])
|
|
324
|
+
explicit = vtk.vtkMatrix4x4()
|
|
325
|
+
explicit.DeepCopy((combined @ np.linalg.inv(vm)).ravel())
|
|
326
|
+
self.camera.SetExplicitProjectionTransformMatrix(explicit)
|
|
327
|
+
self.camera.UseExplicitProjectionTransformMatrixOn()
|
|
328
|
+
|
|
329
|
+
def _frame_key(self, width, height, projection, affine):
|
|
330
|
+
lights = tuple(light.GetMTime() for light in self.renderer.GetLights())
|
|
331
|
+
return (width, height, self._antialiasing, projection.tobytes(), affine.tobytes(),
|
|
332
|
+
lights, self.renderer.GetMTime(),
|
|
333
|
+
tuple((h.get_visible(), h.actor.GetMTime(), h.mapper.GetMTime(), h.data.GetMTime())
|
|
334
|
+
for h in self.handles))
|
|
335
|
+
|
|
336
|
+
def _render_frame(self, width, height, factor, projection, affine):
|
|
337
|
+
render_size = (width*factor, height*factor)
|
|
338
|
+
self.window.SetSize(*render_size)
|
|
339
|
+
self._sync_camera(projection, affine)
|
|
340
|
+
|
|
341
|
+
# Lines and point sprites use framebuffer pixels. Scale them for the
|
|
342
|
+
# high-resolution pass and restore their VTK properties afterwards.
|
|
343
|
+
strokes = []
|
|
344
|
+
if factor > 1:
|
|
345
|
+
for handle in self.handles:
|
|
346
|
+
actor = handle.actor
|
|
347
|
+
if not handle.get_visible() or not actor.IsA("vtkActor"):
|
|
348
|
+
continue
|
|
349
|
+
prop = actor.GetProperty()
|
|
350
|
+
lines = (handle.data.GetNumberOfLines() or prop.GetEdgeVisibility()
|
|
351
|
+
or prop.GetRepresentation() == vtk.VTK_WIREFRAME
|
|
352
|
+
or hasattr(handle, "_marker_transform"))
|
|
353
|
+
points = (handle.data.GetNumberOfVerts() or prop.GetRepresentation() == vtk.VTK_POINTS)
|
|
354
|
+
width_px = prop.GetLineWidth() if lines else None
|
|
355
|
+
size_px = prop.GetPointSize() if points else None
|
|
356
|
+
if width_px is not None or size_px is not None:
|
|
357
|
+
strokes.append((prop, width_px, size_px))
|
|
358
|
+
try:
|
|
359
|
+
for prop, width_px, size_px in strokes:
|
|
360
|
+
if width_px is not None:
|
|
361
|
+
prop.SetLineWidth(width_px*factor)
|
|
362
|
+
if size_px is not None:
|
|
363
|
+
prop.SetPointSize(size_px*factor)
|
|
364
|
+
self.window.Render()
|
|
365
|
+
render_width, render_height = render_size
|
|
366
|
+
if self.window.GetRGBACharPixelData(0, 0, render_width-1, render_height-1,
|
|
367
|
+
0, self._pixel_buffer):
|
|
368
|
+
buf = self._pixel_buffer
|
|
369
|
+
else:
|
|
370
|
+
self.capture.Modified()
|
|
371
|
+
self.capture.Update()
|
|
372
|
+
buf = self.capture.GetOutput().GetPointData().GetScalars()
|
|
373
|
+
rgba = vtk_to_numpy(buf)
|
|
374
|
+
# Filter VTK's premultiplied framebuffer before converting to the
|
|
375
|
+
# straight alpha that Matplotlib expects. This avoids dark fringes.
|
|
376
|
+
image = Image.frombuffer("RGBa", render_size, rgba, "raw", "RGBa", 0, 1)
|
|
377
|
+
if factor > 1:
|
|
378
|
+
image = image.reduce(factor)
|
|
379
|
+
self._viewport_extent = image.getbbox() or (0, 0, 0, 0)
|
|
380
|
+
# Matplotlib's Agg renderer requires a writable pixel buffer.
|
|
381
|
+
return np.array(image.convert("RGBA"))
|
|
382
|
+
finally:
|
|
383
|
+
for prop, width_px, size_px in strokes:
|
|
384
|
+
if width_px is not None:
|
|
385
|
+
prop.SetLineWidth(width_px)
|
|
386
|
+
if size_px is not None:
|
|
387
|
+
prop.SetPointSize(size_px)
|
|
388
|
+
|
|
389
|
+
def pixels(self, width, height):
|
|
390
|
+
self._fit_if_needed()
|
|
391
|
+
projection = self.get_proj()
|
|
392
|
+
affine = self.transData.get_affine().get_matrix()
|
|
393
|
+
key = self._frame_key(width, height, projection, affine)
|
|
394
|
+
if key == self._viewport_key:
|
|
395
|
+
return self._viewport_frame
|
|
396
|
+
self._viewport_frame = self._render_frame(width, height, self._antialiasing, projection, affine)
|
|
397
|
+
self._viewport_key = self._frame_key(width, height, projection, affine)
|
|
398
|
+
return self._viewport_frame
|
|
399
|
+
|
|
400
|
+
def _close(self, event=None):
|
|
401
|
+
self.window.Finalize()
|
|
402
|
+
self._pixel_buffer.Initialize()
|
|
403
|
+
self._viewport_key = None
|
|
404
|
+
self._viewport_frame = None
|
|
405
|
+
self._viewport_extent = None
|
|
406
|
+
|
|
407
|
+
def remove(self):
|
|
408
|
+
self.figure.canvas.mpl_disconnect(self._close_id)
|
|
409
|
+
self._close()
|
|
410
|
+
super().remove()
|
|
411
|
+
|
|
412
|
+
def get_legend_handles_labels(self, legend_handler_map=None):
|
|
413
|
+
from matplotlib.lines import Line2D
|
|
414
|
+
handles, labels = super().get_legend_handles_labels(legend_handler_map)
|
|
415
|
+
for h in self.handles:
|
|
416
|
+
label = h.get_label()
|
|
417
|
+
if not label or label.startswith("_"):
|
|
418
|
+
continue
|
|
419
|
+
color = getattr(h, "constant_color", None)
|
|
420
|
+
color = h.get_cmap()(.5) if color is None else color
|
|
421
|
+
prop = h.actor.GetProperty() if h.actor.IsA("vtkActor") else None
|
|
422
|
+
is_point = prop is not None and bool(h.data.GetNumberOfVerts())
|
|
423
|
+
handles.append(Line2D([],[],color=color,alpha=prop.GetOpacity() if prop else 1.,
|
|
424
|
+
linewidth=prop.GetLineWidth() if prop else 1.,label=label,
|
|
425
|
+
marker="o" if is_point else None,
|
|
426
|
+
linestyle="none" if is_point else "-"))
|
|
427
|
+
labels.append(label)
|
|
428
|
+
return handles,labels
|
|
429
|
+
|
|
430
|
+
def legend(self, *args, **kwargs):
|
|
431
|
+
if not args and "handles" not in kwargs and "labels" not in kwargs:
|
|
432
|
+
args = self.get_legend_handles_labels(kwargs.get("handler_map"))
|
|
433
|
+
return super().legend(*args, **kwargs)
|
|
434
|
+
|
|
435
|
+
def plot_surface(self, x, y, z, *, values=None, rcount=None, ccount=None,
|
|
436
|
+
rstride=None, cstride=None, facecolors=None, shade=None, **style):
|
|
437
|
+
"""Draw a surface from coordinate vectors or matching grids."""
|
|
438
|
+
xyz = surface_arrays(x, y, z)
|
|
439
|
+
if facecolors is not None:
|
|
440
|
+
if values is not None:
|
|
441
|
+
raise TypeError("supply either values or facecolors")
|
|
442
|
+
values = facecolors
|
|
443
|
+
if values is not None:
|
|
444
|
+
values = np.asanyarray(values)
|
|
445
|
+
if values.shape not in (xyz[2].shape, xyz[2].shape + (3,), xyz[2].shape + (4,)):
|
|
446
|
+
raise ValueError("values must match the surface grid with optional RGB(A) channels")
|
|
447
|
+
if any(option is not None for option in (rcount, ccount, rstride, cstride)):
|
|
448
|
+
sample = self._grid_indices(xyz[2].shape, (rcount, ccount), (rstride, cstride))
|
|
449
|
+
xyz = tuple(axis[sample] for axis in xyz)
|
|
450
|
+
if values is not None:
|
|
451
|
+
values = values[sample]
|
|
452
|
+
if values is None and all(style.get(k) is None for k in ("cmap", "norm", "color", "facecolor")):
|
|
453
|
+
style["color"] = self._get_lines.get_next_color()
|
|
454
|
+
style.setdefault("lighting", shade if shade is not None else style.get("cmap") is None and values is None)
|
|
455
|
+
return surfaces._surface(self, *xyz, values, style)
|
|
456
|
+
|
|
457
|
+
@staticmethod
|
|
458
|
+
def _grid_indices(shape, counts, strides):
|
|
459
|
+
cuts = []
|
|
460
|
+
for size, count, stride in zip(shape, counts, strides):
|
|
461
|
+
if count is not None and stride is not None:
|
|
462
|
+
raise ValueError("choose a count or stride per axis")
|
|
463
|
+
if count is not None:
|
|
464
|
+
count = index(count)
|
|
465
|
+
if count < 2:
|
|
466
|
+
raise ValueError("sample counts must be at least two")
|
|
467
|
+
indices = np.linspace(0, size - 1, min(count, size), dtype=np.intp)
|
|
468
|
+
else:
|
|
469
|
+
step = 1 if stride is None else index(stride)
|
|
470
|
+
if step < 1:
|
|
471
|
+
raise ValueError("sample strides must be positive")
|
|
472
|
+
indices = np.arange(0, size, step)
|
|
473
|
+
if indices[-1] != size - 1:
|
|
474
|
+
indices = np.r_[indices, size - 1]
|
|
475
|
+
cuts.append(indices)
|
|
476
|
+
return np.ix_(*cuts)
|
|
477
|
+
|
|
478
|
+
def plot(self, x, y, z=0, *, zdir="z", color=None, linestyle="-", marker=None, markersize=6, **style):
|
|
479
|
+
"""Draw one or more lines from coordinate arrays."""
|
|
480
|
+
return charts._line(self, *self._oriented(x, y, z, zdir), color=color, linestyle=linestyle,
|
|
481
|
+
marker=marker, markersize=markersize, **style)
|
|
482
|
+
|
|
483
|
+
@staticmethod
|
|
484
|
+
def _oriented(x, y, z, direction):
|
|
485
|
+
return {"z": (x, y, z), "x": (z, x, y), "y": (x, z, y)}[direction]
|
|
486
|
+
|
|
487
|
+
def scatter(self, x, y, z=0, *, s=20, c=None, zdir="z", marker="o", filled=True, **style):
|
|
488
|
+
"""Draw 3-D markers with area s and an optional color or scalar array c."""
|
|
489
|
+
return charts._scatter(self, *self._oriented(x, y, z, zdir), s=s, c=c, marker=marker,
|
|
490
|
+
filled=filled, **style)
|
|
491
|
+
|
|
492
|
+
def plot_trisurf(self, x, y=None, z=None, *, triangles=None, values=None,
|
|
493
|
+
association="point", shade=None, **style):
|
|
494
|
+
"""Draw a triangulation of x and y at heights z, with optional scalar values."""
|
|
495
|
+
if isinstance(x, Triangulation):
|
|
496
|
+
if triangles is not None or (y is not None and z is not None):
|
|
497
|
+
raise TypeError("supply a Triangulation and one height array")
|
|
498
|
+
triangulation, z = x, z if y is None else y
|
|
499
|
+
elif triangles is None:
|
|
500
|
+
triangulation = Triangulation(x, y)
|
|
501
|
+
else:
|
|
502
|
+
x, y, faces = surfaces._triangle_arrays(x, y, triangles)
|
|
503
|
+
triangulation = None
|
|
504
|
+
if triangulation is not None:
|
|
505
|
+
x, y = triangulation.x, triangulation.y
|
|
506
|
+
faces = triangulation.get_masked_triangles()
|
|
507
|
+
z = np.asarray(z)
|
|
508
|
+
if z.shape != x.shape:
|
|
509
|
+
raise ValueError("z must have one height per triangulation vertex")
|
|
510
|
+
if values is None and style.get("cmap") is not None:
|
|
511
|
+
values = z[faces].mean(axis=1) if association == "cell" else z
|
|
512
|
+
style.setdefault("lighting", shade if shade is not None else style.get("cmap") is None)
|
|
513
|
+
return surfaces._triangles(self, x, y, z, faces, values, association, style)
|
|
514
|
+
|
|
515
|
+
plot_isosurface = volumes.plot_isosurface
|
|
516
|
+
|
|
517
|
+
def add_collection3d(self, *args, **kwargs):
|
|
518
|
+
raise NotImplementedError("Use the VTK plotting methods to add three-dimensional geometry.")
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
register_projection(VtkAxes)
|