mpl3d-vtk 0.5.0__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.
- mpl3d_vtk/__init__.py +12 -0
- mpl3d_vtk/_axes.py +494 -0
- mpl3d_vtk/_geometry.py +230 -0
- mpl3d_vtk/_my_mpl_style_license.txt +21 -0
- mpl3d_vtk/_projected_ticks.py +232 -0
- mpl3d_vtk/charts.py +180 -0
- mpl3d_vtk/graphs.py +76 -0
- mpl3d_vtk/planes.py +90 -0
- mpl3d_vtk/scene.py +315 -0
- mpl3d_vtk/spatial.py +181 -0
- mpl3d_vtk/surfaces.py +47 -0
- mpl3d_vtk/vectors.py +211 -0
- mpl3d_vtk/volumes.py +168 -0
- mpl3d_vtk-0.5.0.dist-info/METADATA +66 -0
- mpl3d_vtk-0.5.0.dist-info/RECORD +17 -0
- mpl3d_vtk-0.5.0.dist-info/WHEEL +5 -0
- mpl3d_vtk-0.5.0.dist-info/top_level.txt +1 -0
mpl3d_vtk/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
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 .scene import Graphic
|
|
8
|
+
from .vectors import trace_streamlines
|
|
9
|
+
from .volumes import extract_isosurface
|
|
10
|
+
|
|
11
|
+
__all__ = ["Graphic", "VtkAxes", "extract_isosurface", "trace_streamlines"]
|
|
12
|
+
__version__ = "0.5.0"
|
mpl3d_vtk/_axes.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
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.colors import to_rgb
|
|
11
|
+
from matplotlib.projections import register_projection
|
|
12
|
+
from matplotlib.tri import Triangulation
|
|
13
|
+
from matplotlib.transforms import Bbox
|
|
14
|
+
from mpl_toolkits.mplot3d import Axes3D
|
|
15
|
+
|
|
16
|
+
from . import charts, graphs, planes, spatial, surfaces, vectors, volumes
|
|
17
|
+
from ._geometry import surface_arrays
|
|
18
|
+
from ._projected_ticks import apply_axes_style
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _sampling_factor(value):
|
|
22
|
+
try:
|
|
23
|
+
factor = index(value)
|
|
24
|
+
except TypeError as exc:
|
|
25
|
+
raise ValueError("antialiasing must be an integer from 1 to 4") from exc
|
|
26
|
+
if not 1 <= factor <= 4:
|
|
27
|
+
raise ValueError("antialiasing must be an integer from 1 to 4")
|
|
28
|
+
return factor
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _Viewport(Artist):
|
|
32
|
+
def __init__(self, ax):
|
|
33
|
+
super().__init__()
|
|
34
|
+
self.scene = ax
|
|
35
|
+
self.set_zorder(1)
|
|
36
|
+
self.set_in_layout(False)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def _nearest(start, stop, low, high, size):
|
|
40
|
+
centers = np.arange(start, stop) + .5
|
|
41
|
+
idx = np.floor((centers - low) * (size / (high - low))).astype(np.intp)
|
|
42
|
+
np.clip(idx, 0, size-1, out=idx)
|
|
43
|
+
return idx
|
|
44
|
+
|
|
45
|
+
@allow_rasterization
|
|
46
|
+
def draw(self, renderer):
|
|
47
|
+
if self.get_visible() and any(h.get_visible() for h in self.scene.handles):
|
|
48
|
+
self._draw_frame(renderer)
|
|
49
|
+
self.stale = False
|
|
50
|
+
|
|
51
|
+
def _draw_frame(self, renderer):
|
|
52
|
+
box = self.scene.bbox
|
|
53
|
+
clipped = Bbox.intersection(box, Bbox.from_bounds(0, 0, *renderer.get_canvas_width_height()))
|
|
54
|
+
if clipped is None or box.width <= 0 or box.height <= 0:
|
|
55
|
+
return
|
|
56
|
+
mag = renderer.get_image_magnification()
|
|
57
|
+
# Snap the visible extent to the same pixel convention as BboxImage.
|
|
58
|
+
left, bottom, right, top = clipped.extents * mag
|
|
59
|
+
x0 = int(np.floor(left+.5))
|
|
60
|
+
y0 = int(np.ceil(bottom-.5-1e-8))
|
|
61
|
+
x1 = int(np.floor(right+.5+1e-8))
|
|
62
|
+
y1 = int(np.ceil(top-.5))
|
|
63
|
+
if x0 >= x1 or y0 >= y1:
|
|
64
|
+
return
|
|
65
|
+
|
|
66
|
+
width, height = (max(1, round(v*mag)) for v in box.size)
|
|
67
|
+
rgba = self.scene.pixels(width, height)
|
|
68
|
+
# VTK has already downsampled its framebuffer to the output scale.
|
|
69
|
+
# Only account for subpixel placement and clipping on the final canvas.
|
|
70
|
+
columns = self._nearest(x0, x1, box.x0*mag, box.x1*mag, width)
|
|
71
|
+
rows = self._nearest(y0, y1, box.y0*mag, box.y1*mag, height)
|
|
72
|
+
extent = getattr(self.scene, "_viewport_extent", None)
|
|
73
|
+
if extent is not None:
|
|
74
|
+
left, bottom, right, top = extent
|
|
75
|
+
first_col, last_col = np.searchsorted(columns, (left, right))
|
|
76
|
+
first_row, last_row = np.searchsorted(rows, (bottom, top))
|
|
77
|
+
if first_col >= last_col or first_row >= last_row:
|
|
78
|
+
return
|
|
79
|
+
columns = columns[first_col:last_col]
|
|
80
|
+
rows = rows[first_row:last_row]
|
|
81
|
+
x0 += first_col
|
|
82
|
+
y0 += first_row
|
|
83
|
+
if np.all(np.diff(columns) == 1) and np.all(np.diff(rows) == 1):
|
|
84
|
+
rgba = rgba[rows[0]:rows[-1]+1, columns[0]:columns[-1]+1]
|
|
85
|
+
else:
|
|
86
|
+
rgba = rgba[rows[:, None], columns]
|
|
87
|
+
gc = renderer.new_gc()
|
|
88
|
+
try:
|
|
89
|
+
self._set_gc_clip(gc)
|
|
90
|
+
gc.set_alpha(1.)
|
|
91
|
+
renderer.draw_image(gc, x0/mag, y0/mag, np.ascontiguousarray(rgba))
|
|
92
|
+
finally:
|
|
93
|
+
gc.restore()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class VtkAxes(Axes3D):
|
|
97
|
+
"""Matplotlib owns the axes. Only the three-dimensional data pass goes to VTK."""
|
|
98
|
+
name = "vtk3d"
|
|
99
|
+
|
|
100
|
+
def __init__(self, *args, antialiasing=2, **kwargs):
|
|
101
|
+
# Axes3D starts in auto mode. Reapplying it during initialization can
|
|
102
|
+
# reset an explicitly supplied box_aspect.
|
|
103
|
+
if kwargs.get("aspect") == "auto":
|
|
104
|
+
kwargs.pop("aspect")
|
|
105
|
+
kwargs.setdefault("elev", 30)
|
|
106
|
+
kwargs.setdefault("azim", -127.5)
|
|
107
|
+
focal_length = kwargs.get("focal_length")
|
|
108
|
+
kwargs.setdefault("proj_type", "persp" if focal_length is not None
|
|
109
|
+
and np.isfinite(focal_length) else "ortho")
|
|
110
|
+
self._antialiasing = _sampling_factor(antialiasing)
|
|
111
|
+
super().__init__(*args, **kwargs)
|
|
112
|
+
apply_axes_style(self)
|
|
113
|
+
self.renderer = vtk.vtkRenderer()
|
|
114
|
+
self.window = vtk.vtkRenderWindow()
|
|
115
|
+
self.window.SetOffScreenRendering(True)
|
|
116
|
+
self.window.SwapBuffersOff()
|
|
117
|
+
self.window.SetMultiSamples(0)
|
|
118
|
+
self.window.SetAlphaBitPlanes(1)
|
|
119
|
+
self.window.AddRenderer(self.renderer)
|
|
120
|
+
self.renderer.SetBackground(0,0,0)
|
|
121
|
+
self.renderer.SetBackgroundAlpha(0)
|
|
122
|
+
self.renderer.UseDepthPeelingOn()
|
|
123
|
+
self.renderer.SetMaximumNumberOfPeels(32)
|
|
124
|
+
self.renderer.SetOcclusionRatio(0)
|
|
125
|
+
self.capture = vtk.vtkWindowToImageFilter()
|
|
126
|
+
self.capture.SetInput(self.window)
|
|
127
|
+
self.capture.SetInputBufferTypeToRGBA()
|
|
128
|
+
self.capture.ReadFrontBufferOff()
|
|
129
|
+
self.capture.ShouldRerenderOff()
|
|
130
|
+
self._pixel_buffer = vtk.vtkUnsignedCharArray()
|
|
131
|
+
self.camera = self.renderer.GetActiveCamera()
|
|
132
|
+
self.handles = []
|
|
133
|
+
self._limits_dirty = False
|
|
134
|
+
self._viewport = _Viewport(self)
|
|
135
|
+
self.add_artist(self._viewport)
|
|
136
|
+
self._close_id = self.figure.canvas.mpl_connect("close_event", self._close)
|
|
137
|
+
self._viewport_key = None
|
|
138
|
+
self._viewport_frame = None
|
|
139
|
+
self._viewport_extent = None
|
|
140
|
+
|
|
141
|
+
def get_antialiasing(self):
|
|
142
|
+
"""Return the VTK render scale per output pixel dimension."""
|
|
143
|
+
return self._antialiasing
|
|
144
|
+
|
|
145
|
+
def set_antialiasing(self, factor):
|
|
146
|
+
"""Select 1× native rendering or 2× to 4× supersampling."""
|
|
147
|
+
self._antialiasing = _sampling_factor(factor)
|
|
148
|
+
self.stale = True
|
|
149
|
+
|
|
150
|
+
def clear_scene(self):
|
|
151
|
+
"""Remove VTK plots while keeping axes settings and Matplotlib artists."""
|
|
152
|
+
for handle in self.handles.copy():
|
|
153
|
+
handle.remove()
|
|
154
|
+
|
|
155
|
+
def clear(self):
|
|
156
|
+
if hasattr(self, "handles"):
|
|
157
|
+
self.clear_scene()
|
|
158
|
+
super().clear()
|
|
159
|
+
if hasattr(self, "_viewport"):
|
|
160
|
+
self.renderer.RemoveAllLights()
|
|
161
|
+
self.add_artist(self._viewport)
|
|
162
|
+
apply_axes_style(self)
|
|
163
|
+
|
|
164
|
+
def fit(self):
|
|
165
|
+
if self.handles:
|
|
166
|
+
records = [h._raw_bounds() for h in self.handles]
|
|
167
|
+
records = [r for r in records if r[0] <= r[1] and np.isfinite(r).all()]
|
|
168
|
+
if records:
|
|
169
|
+
data = np.asarray(records).reshape(-1,3,2)
|
|
170
|
+
bounds = np.stack((data[:,:,0].min(axis=0),data[:,:,1].max(axis=0)),axis=1)
|
|
171
|
+
self.auto_scale_xyz(*bounds, had_data=False)
|
|
172
|
+
self._limits_dirty = False
|
|
173
|
+
|
|
174
|
+
def draw(self, renderer):
|
|
175
|
+
for handle in self.handles:
|
|
176
|
+
if isinstance(handle, charts._StreamingLine):
|
|
177
|
+
handle._flush()
|
|
178
|
+
if self._limits_dirty:
|
|
179
|
+
self.fit()
|
|
180
|
+
super().draw(renderer)
|
|
181
|
+
|
|
182
|
+
def _sync_camera(self, projection, affine):
|
|
183
|
+
# Matplotlib first projects data with get_proj(), then maps xy with
|
|
184
|
+
# transData. OpenGL instead takes clip coordinates in [-w,w].
|
|
185
|
+
limits = np.array(self.get_w_lims()).reshape(3,2)
|
|
186
|
+
scales = [axis.get_transform() for axis in (self.xaxis,self.yaxis,self.zaxis)]
|
|
187
|
+
nonlinear = tuple(axis.get_scale() != "linear" for axis in (self.xaxis,self.yaxis,self.zaxis))
|
|
188
|
+
for i in range(3):
|
|
189
|
+
if nonlinear[i]:
|
|
190
|
+
limits[i] = scales[i].transform(limits[i])
|
|
191
|
+
for h in self.handles:
|
|
192
|
+
h._sync_geometry(scales,nonlinear)
|
|
193
|
+
box = self.bbox
|
|
194
|
+
ndc = np.array([[2/box.width,0,-1-2*box.x0/box.width],
|
|
195
|
+
[0,2/box.height,-1-2*box.y0/box.height], [0,0,1]])
|
|
196
|
+
plane = ndc @ affine
|
|
197
|
+
m = projection
|
|
198
|
+
combined = m.copy()
|
|
199
|
+
combined[:2] = plane[:2] @ m[[0,1,3]]
|
|
200
|
+
bounds = limits.copy()
|
|
201
|
+
for h in self.handles:
|
|
202
|
+
b = np.asarray(h._render_bounds()).reshape(3,2)
|
|
203
|
+
if b[0,0] <= b[0,1]:
|
|
204
|
+
bounds[:,0] = np.minimum(bounds.min(axis=1), b[:,0])
|
|
205
|
+
bounds[:,1] = np.maximum(bounds.max(axis=1), b[:,1])
|
|
206
|
+
# Include the visible axis box so extreme zoom still has a valid
|
|
207
|
+
# depth interval when data behind the eye is clipped by OpenGL.
|
|
208
|
+
corners = np.array(list(product(*limits)) + list(product(*bounds)))
|
|
209
|
+
clip = np.column_stack((corners,np.ones(len(corners)))) @ m.T
|
|
210
|
+
front = clip[:,3] > 1e-9
|
|
211
|
+
depth = clip[front,2]/clip[front,3]
|
|
212
|
+
lo, hi = depth.min(), depth.max()
|
|
213
|
+
scale = 1.8/max(hi-lo,1e-8)
|
|
214
|
+
combined[2] = scale*(m[2] - .5*(lo+hi)*m[3])
|
|
215
|
+
# A conventional physical camera gives lights a meaningful view frame.
|
|
216
|
+
# Its view matrix is factored out of the explicit projection below.
|
|
217
|
+
center = limits.mean(axis=1)
|
|
218
|
+
right, up = m[0,:3], m[1,:3]
|
|
219
|
+
back = np.cross(right,up)
|
|
220
|
+
back /= max(np.linalg.norm(back),1e-30)
|
|
221
|
+
up = up/max(np.linalg.norm(up),1e-30)
|
|
222
|
+
billboard_right = np.cross(up,back)
|
|
223
|
+
marker_matrix = np.eye(4)
|
|
224
|
+
marker_matrix[:3,:3] = np.column_stack((billboard_right,up,back))
|
|
225
|
+
for handle in self.handles:
|
|
226
|
+
if hasattr(handle,"_marker_transform"):
|
|
227
|
+
handle._marker_transform.SetMatrix(marker_matrix.ravel())
|
|
228
|
+
distance = max(np.linalg.norm(np.ptp(limits,axis=1)), 1)
|
|
229
|
+
self.camera.SetPosition(*(center+back*distance*2))
|
|
230
|
+
self.camera.SetFocalPoint(*center)
|
|
231
|
+
self.camera.SetViewUp(*up)
|
|
232
|
+
modelview = self.camera.GetModelViewTransformMatrix()
|
|
233
|
+
vm = np.array([[modelview.GetElement(i,j) for j in range(4)] for i in range(4)])
|
|
234
|
+
explicit = vtk.vtkMatrix4x4()
|
|
235
|
+
explicit.DeepCopy((combined @ np.linalg.inv(vm)).ravel())
|
|
236
|
+
self.camera.SetExplicitProjectionTransformMatrix(explicit)
|
|
237
|
+
self.camera.UseExplicitProjectionTransformMatrixOn()
|
|
238
|
+
|
|
239
|
+
def _frame_key(self, width, height, projection, affine):
|
|
240
|
+
lights = tuple(light.GetMTime() for light in self.renderer.GetLights())
|
|
241
|
+
return (width, height, self._antialiasing, projection.tobytes(), affine.tobytes(),
|
|
242
|
+
lights, self.renderer.GetMTime(),
|
|
243
|
+
tuple((h.get_visible(), h.actor.GetMTime(), h.mapper.GetMTime(), h.data.GetMTime())
|
|
244
|
+
for h in self.handles))
|
|
245
|
+
|
|
246
|
+
def _render_frame(self, width, height, factor, projection, affine):
|
|
247
|
+
render_size = (width*factor, height*factor)
|
|
248
|
+
self.window.SetSize(*render_size)
|
|
249
|
+
self._sync_camera(projection, affine)
|
|
250
|
+
|
|
251
|
+
# Lines and point sprites use framebuffer pixels. Scale them for the
|
|
252
|
+
# high-resolution pass and restore their VTK properties afterwards.
|
|
253
|
+
strokes = []
|
|
254
|
+
if factor > 1:
|
|
255
|
+
for handle in self.handles:
|
|
256
|
+
actor = handle.actor
|
|
257
|
+
if not handle.get_visible() or not actor.IsA("vtkActor"):
|
|
258
|
+
continue
|
|
259
|
+
prop = actor.GetProperty()
|
|
260
|
+
lines = (handle.data.GetNumberOfLines() or prop.GetEdgeVisibility()
|
|
261
|
+
or prop.GetRepresentation() == vtk.VTK_WIREFRAME
|
|
262
|
+
or hasattr(handle, "_marker_transform"))
|
|
263
|
+
points = (handle.data.GetNumberOfVerts() or prop.GetRepresentation() == vtk.VTK_POINTS)
|
|
264
|
+
width_px = prop.GetLineWidth() if lines else None
|
|
265
|
+
size_px = prop.GetPointSize() if points else None
|
|
266
|
+
if width_px is not None or size_px is not None:
|
|
267
|
+
strokes.append((prop, width_px, size_px))
|
|
268
|
+
try:
|
|
269
|
+
for prop, width_px, size_px in strokes:
|
|
270
|
+
if width_px is not None:
|
|
271
|
+
prop.SetLineWidth(width_px*factor)
|
|
272
|
+
if size_px is not None:
|
|
273
|
+
prop.SetPointSize(size_px*factor)
|
|
274
|
+
self.window.Render()
|
|
275
|
+
render_width, render_height = render_size
|
|
276
|
+
if self.window.GetRGBACharPixelData(0, 0, render_width-1, render_height-1,
|
|
277
|
+
0, self._pixel_buffer):
|
|
278
|
+
buf = self._pixel_buffer
|
|
279
|
+
else:
|
|
280
|
+
self.capture.Modified()
|
|
281
|
+
self.capture.Update()
|
|
282
|
+
buf = self.capture.GetOutput().GetPointData().GetScalars()
|
|
283
|
+
rgba = vtk_to_numpy(buf)
|
|
284
|
+
# Filter VTK's premultiplied framebuffer before converting to the
|
|
285
|
+
# straight alpha that Matplotlib expects. This avoids dark fringes.
|
|
286
|
+
image = Image.frombuffer("RGBa", render_size, rgba, "raw", "RGBa", 0, 1)
|
|
287
|
+
if factor > 1:
|
|
288
|
+
image = image.reduce(factor)
|
|
289
|
+
self._viewport_extent = image.getbbox() or (0, 0, 0, 0)
|
|
290
|
+
# Matplotlib's Agg renderer requires a writable pixel buffer.
|
|
291
|
+
return np.array(image.convert("RGBA"))
|
|
292
|
+
finally:
|
|
293
|
+
for prop, width_px, size_px in strokes:
|
|
294
|
+
if width_px is not None:
|
|
295
|
+
prop.SetLineWidth(width_px)
|
|
296
|
+
if size_px is not None:
|
|
297
|
+
prop.SetPointSize(size_px)
|
|
298
|
+
|
|
299
|
+
def pixels(self, width, height):
|
|
300
|
+
if self._limits_dirty:
|
|
301
|
+
self.fit()
|
|
302
|
+
projection = self.get_proj()
|
|
303
|
+
affine = self.transData.get_affine().get_matrix()
|
|
304
|
+
key = self._frame_key(width, height, projection, affine)
|
|
305
|
+
if key == self._viewport_key:
|
|
306
|
+
return self._viewport_frame
|
|
307
|
+
self._viewport_frame = self._render_frame(width, height, self._antialiasing, projection, affine)
|
|
308
|
+
self._viewport_key = self._frame_key(width, height, projection, affine)
|
|
309
|
+
return self._viewport_frame
|
|
310
|
+
|
|
311
|
+
def _close(self, event=None):
|
|
312
|
+
self.window.Finalize()
|
|
313
|
+
self._pixel_buffer.Initialize()
|
|
314
|
+
self._viewport_key = None
|
|
315
|
+
self._viewport_frame = None
|
|
316
|
+
self._viewport_extent = None
|
|
317
|
+
|
|
318
|
+
def remove(self):
|
|
319
|
+
self.figure.canvas.mpl_disconnect(self._close_id)
|
|
320
|
+
self._close()
|
|
321
|
+
super().remove()
|
|
322
|
+
|
|
323
|
+
def get_legend_handles_labels(self, legend_handler_map=None):
|
|
324
|
+
from matplotlib.lines import Line2D
|
|
325
|
+
handles, labels = super().get_legend_handles_labels(legend_handler_map)
|
|
326
|
+
for h in self.handles:
|
|
327
|
+
label = h.get_label()
|
|
328
|
+
if not label or label.startswith("_"):
|
|
329
|
+
continue
|
|
330
|
+
color = getattr(h, "constant_color", None)
|
|
331
|
+
color = h.get_cmap()(.5) if color is None else color
|
|
332
|
+
prop = h.actor.GetProperty() if h.actor.IsA("vtkActor") else None
|
|
333
|
+
is_point = prop is not None and bool(h.data.GetNumberOfVerts())
|
|
334
|
+
handles.append(Line2D([],[],color=color,alpha=prop.GetOpacity() if prop else 1.,
|
|
335
|
+
linewidth=prop.GetLineWidth() if prop else 1.,label=label,
|
|
336
|
+
marker="o" if is_point else None,
|
|
337
|
+
linestyle="none" if is_point else "-"))
|
|
338
|
+
labels.append(label)
|
|
339
|
+
return handles,labels
|
|
340
|
+
|
|
341
|
+
def legend(self, *args, **kwargs):
|
|
342
|
+
if not args and "handles" not in kwargs and "labels" not in kwargs:
|
|
343
|
+
args = self.get_legend_handles_labels(kwargs.get("handler_map"))
|
|
344
|
+
return super().legend(*args, **kwargs)
|
|
345
|
+
|
|
346
|
+
def plot_surface(self, x, y, z, *, values=None, rcount=None, ccount=None,
|
|
347
|
+
rstride=None, cstride=None, facecolors=None, shade=None, **style):
|
|
348
|
+
"""Draw a surface from coordinate vectors or matching grids."""
|
|
349
|
+
xyz = surface_arrays(x, y, z)
|
|
350
|
+
if facecolors is not None:
|
|
351
|
+
if values is not None:
|
|
352
|
+
raise TypeError("supply either values or facecolors")
|
|
353
|
+
values = facecolors
|
|
354
|
+
if values is not None:
|
|
355
|
+
values = np.asanyarray(values)
|
|
356
|
+
if values.shape not in (xyz[2].shape, xyz[2].shape + (3,), xyz[2].shape + (4,)):
|
|
357
|
+
raise ValueError("values must match the surface grid with optional RGB(A) channels")
|
|
358
|
+
if any(option is not None for option in (rcount, ccount, rstride, cstride)):
|
|
359
|
+
sample = self._grid_indices(xyz[2].shape, (rcount, ccount), (rstride, cstride))
|
|
360
|
+
xyz = tuple(axis[sample] for axis in xyz)
|
|
361
|
+
if values is not None:
|
|
362
|
+
values = values[sample]
|
|
363
|
+
if values is None and all(style.get(k) is None for k in ("cmap", "norm", "color", "facecolor")):
|
|
364
|
+
style["color"] = self._get_lines.get_next_color()
|
|
365
|
+
style.setdefault("lighting", shade if shade is not None else style.get("cmap") is None and values is None)
|
|
366
|
+
return surfaces._surface(self, *xyz, values, style)
|
|
367
|
+
|
|
368
|
+
@staticmethod
|
|
369
|
+
def _grid_indices(shape, counts, strides):
|
|
370
|
+
cuts = []
|
|
371
|
+
for size, count, stride in zip(shape, counts, strides):
|
|
372
|
+
if count is not None and stride is not None:
|
|
373
|
+
raise ValueError("choose a count or stride per axis")
|
|
374
|
+
if count is not None:
|
|
375
|
+
count = index(count)
|
|
376
|
+
if count < 2:
|
|
377
|
+
raise ValueError("sample counts must be at least two")
|
|
378
|
+
indices = np.linspace(0, size - 1, min(count, size), dtype=np.intp)
|
|
379
|
+
else:
|
|
380
|
+
step = 1 if stride is None else index(stride)
|
|
381
|
+
if step < 1:
|
|
382
|
+
raise ValueError("sample strides must be positive")
|
|
383
|
+
indices = np.arange(0, size, step)
|
|
384
|
+
if indices[-1] != size - 1:
|
|
385
|
+
indices = np.r_[indices, size - 1]
|
|
386
|
+
cuts.append(indices)
|
|
387
|
+
return np.ix_(*cuts)
|
|
388
|
+
|
|
389
|
+
def plot_wireframe(self, x, y, z, *, rcount=None, ccount=None, rstride=None, cstride=None, **style):
|
|
390
|
+
"""Draw grid lines, optionally downsampling rows and columns."""
|
|
391
|
+
xyz = surface_arrays(x, y, z)
|
|
392
|
+
if any(option is not None for option in (rcount, ccount, rstride, cstride)):
|
|
393
|
+
sample = self._grid_indices(xyz[2].shape, (rcount, ccount), (rstride, cstride))
|
|
394
|
+
xyz = tuple(axis[sample] for axis in xyz)
|
|
395
|
+
if "color" not in style and "cmap" not in style:
|
|
396
|
+
style["color"] = self._get_lines.get_next_color()
|
|
397
|
+
style["wireframe"] = True
|
|
398
|
+
self.renderer.UseHiddenLineRemovalOn()
|
|
399
|
+
return surfaces._surface(self, *xyz, None, style)
|
|
400
|
+
|
|
401
|
+
def plot(self, x, y, z=0, *, zdir="z", color=None, linestyle="-", marker=None, markersize=6, **style):
|
|
402
|
+
"""Draw one or more lines from coordinate arrays."""
|
|
403
|
+
return charts._line(self, *self._oriented(x, y, z, zdir), color=color, linestyle=linestyle,
|
|
404
|
+
marker=marker, markersize=markersize, **style)
|
|
405
|
+
|
|
406
|
+
plot3D = plot
|
|
407
|
+
|
|
408
|
+
@staticmethod
|
|
409
|
+
def _oriented(x, y, z, direction):
|
|
410
|
+
return {"z": (x, y, z), "x": (z, x, y), "y": (x, z, y)}[direction]
|
|
411
|
+
|
|
412
|
+
def scatter(self, x, y, z=0, *, s=20, c=None, zdir="z", marker="o", filled=True, **style):
|
|
413
|
+
"""Draw 3-D markers with area s and an optional color or scalar array c."""
|
|
414
|
+
return charts._scatter(self, *self._oriented(x, y, z, zdir), s=s, c=c, marker=marker,
|
|
415
|
+
filled=filled, **style)
|
|
416
|
+
|
|
417
|
+
scatter3D = scatter
|
|
418
|
+
|
|
419
|
+
def plot_trisurf(self, x, y=None, z=None, *, triangles=None, values=None,
|
|
420
|
+
association="point", shade=None, **style):
|
|
421
|
+
"""Draw a triangulation of x and y at heights z, with optional scalar values."""
|
|
422
|
+
if isinstance(x, Triangulation):
|
|
423
|
+
if triangles is not None or (y is not None and z is not None):
|
|
424
|
+
raise TypeError("supply a Triangulation and one height array")
|
|
425
|
+
triangulation, z = x, z if y is None else y
|
|
426
|
+
else:
|
|
427
|
+
triangulation = Triangulation(x, y, triangles)
|
|
428
|
+
z = np.asarray(z)
|
|
429
|
+
if z.shape != triangulation.x.shape:
|
|
430
|
+
raise ValueError("z must have one height per triangulation vertex")
|
|
431
|
+
faces = triangulation.get_masked_triangles()
|
|
432
|
+
if values is None and style.get("cmap") is not None:
|
|
433
|
+
values = z[faces].mean(axis=1) if association == "cell" else z
|
|
434
|
+
style.setdefault("lighting", shade if shade is not None else style.get("cmap") is None)
|
|
435
|
+
return self.plot_mesh(np.column_stack((triangulation.x, triangulation.y, z)), faces,
|
|
436
|
+
values=values, association=association, **style)
|
|
437
|
+
|
|
438
|
+
def quiver(self, x, y, z, u, v, w, *, length=1., normalize=False, arrow_length_ratio=.2,
|
|
439
|
+
show_heads=True, **style):
|
|
440
|
+
"""Draw vectors with proportional or normalized lengths."""
|
|
441
|
+
return vectors._quiver(self, x, y, z, u, v, w, length=length, normalize=normalize,
|
|
442
|
+
arrow_length_ratio=arrow_length_ratio, show_heads=show_heads, **style)
|
|
443
|
+
|
|
444
|
+
quiver3D = quiver
|
|
445
|
+
|
|
446
|
+
def contour(self, x, y, z, *, levels=10, offset=None, **style):
|
|
447
|
+
"""Draw contours on a height grid or project them to offset along z."""
|
|
448
|
+
return surfaces._contour(self, *surface_arrays(x, y, z), levels=levels, offset=offset, **style)
|
|
449
|
+
|
|
450
|
+
contour3D = contour
|
|
451
|
+
|
|
452
|
+
def bar3d(self, x, y, z, dx, dy, dz, *, shade=True, **style):
|
|
453
|
+
"""Draw bars from base coordinates and their widths, depths and heights."""
|
|
454
|
+
x, y, z, dx, dy, dz = np.broadcast_arrays(x, y, z, dx, dy, dz)
|
|
455
|
+
style.setdefault("lighting", shade)
|
|
456
|
+
return charts._bars(self, x + dx/2, y + dy/2, z, z + dz, dx, dy, style)
|
|
457
|
+
|
|
458
|
+
def stem(self, x, y, z, *, bottom=0, marker="o", markersize=6, **style):
|
|
459
|
+
"""Draw stems between a constant baseline and the supplied points."""
|
|
460
|
+
return charts._stem(self, x, y, z, bottom=bottom, marker=marker, markersize=markersize, **style)
|
|
461
|
+
|
|
462
|
+
def add_light(self, position, *, focal_point=(0., 0., 0.), color="white", positional=False):
|
|
463
|
+
"""Add a directional or positional VTK light in world coordinates."""
|
|
464
|
+
source = vtk.vtkLight()
|
|
465
|
+
source.SetLightTypeToSceneLight()
|
|
466
|
+
source.SetPosition(*position)
|
|
467
|
+
source.SetFocalPoint(*focal_point)
|
|
468
|
+
source.SetColor(to_rgb(color))
|
|
469
|
+
source.SetPositional(positional)
|
|
470
|
+
self.renderer.AddLight(source)
|
|
471
|
+
self.stale = True
|
|
472
|
+
return source
|
|
473
|
+
|
|
474
|
+
plot_mesh = surfaces.plot_mesh
|
|
475
|
+
plot_isosurface = volumes.plot_isosurface
|
|
476
|
+
plot_volume_slices = volumes.plot_volume_slices
|
|
477
|
+
plot_slice_contours = volumes.plot_slice_contours
|
|
478
|
+
plot_volume = spatial.plot_volume
|
|
479
|
+
plot_point_cloud = spatial.plot_point_cloud
|
|
480
|
+
plot_coordinate_frames = spatial.plot_coordinate_frames
|
|
481
|
+
plot_alpha_shape = spatial.plot_alpha_shape
|
|
482
|
+
plot_vector_samples = vectors.plot_vector_samples
|
|
483
|
+
plot_streamlines = vectors.plot_streamlines
|
|
484
|
+
plot_streamtubes = vectors.plot_streamtubes
|
|
485
|
+
plot_streamribbons = vectors.plot_streamribbons
|
|
486
|
+
plot_graph = graphs.plot_graph
|
|
487
|
+
plot_image_plane = planes.plot_image_plane
|
|
488
|
+
add_streaming_line = charts.add_streaming_line
|
|
489
|
+
|
|
490
|
+
def add_collection3d(self, *args, **kwargs):
|
|
491
|
+
raise NotImplementedError("Use the VTK plotting methods to add three-dimensional geometry.")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
register_projection(VtkAxes)
|