Debian Codegraph @

pyvista/demos/demos.py

raw
1 """Demos to show off the functionality of PyVista."""
2
3 from __future__ import annotations
4
5 import time
6
7 import numpy as np
8
9 import pyvista as pv
10 from pyvista import examples
11 from pyvista._deprecate_positional_args import _deprecate_positional_args
12
13 from .logo import text_3d
14
15
16 def glyphs(grid_sz=3):
17 """Create several parametric supertoroids using VTK's glyph table functionality.
18
19 Parameters
20 ----------
21 grid_sz : int, default: 3
22 Create ``grid_sz x grid_sz`` supertoroids.
23
24 Returns
25 -------
26 pyvista.PolyData
27 Mesh of supertoroids.
28
29 See Also
30 --------
31 plot_glyphs
32
33 Examples
34 --------
35 >>> from pyvista import demos
36 >>> mesh = demos.glyphs()
37 >>> mesh.plot()
38
39 """
40 # Seed rng for reproducible plots
41 rng = np.random.default_rng(seed=0)
42
43 n = 10
44 values = np.arange(n) # values for scalars to look up glyphs by
45
46 # taken from:
47 params = rng.uniform(0.5, 2, size=(n, 2)) # (n1, n2) parameters for the toroids
48
49 geoms = [pv.ParametricSuperToroid(n1=n1, n2=n2) for n1, n2 in params]
50
51 # get dataset where to put glyphs
52 grid_sz = float(grid_sz)
53 x, y, z = np.mgrid[:grid_sz, :grid_sz, :grid_sz]
54 mesh = pv.StructuredGrid(x, y, z)
55
56 # add random scalars
57 rng_int = rng.integers(0, n, size=x.size)
58 mesh.point_data['scalars'] = rng_int
59
60 # construct the glyphs on top of the mesh; don't scale by scalars now
61 return mesh.glyph(
62 geom=geoms,
63 indices=values,
64 scale=False,
65 factor=0.3,
66 rng=(0, n - 1),
67 orient=False,
68 )
69
70
71 def plot_glyphs(grid_sz=3, **kwargs):
72 """Plot several parametric supertoroids using VTK's glyph table functionality.
73
74 Parameters
75 ----------
76 grid_sz : int, default: 3
77 Create ``grid_sz x grid_sz`` supertoroids.
78
79 **kwargs : dict, optional
80 All additional keyword arguments will be passed to
81 :func:`pyvista.Plotter.add_mesh`.
82
83 Returns
84 -------
85 output : list | np.ndarray | ipywidgets.Widget
86 See :func:`show <pyvista.Plotter.show>`.
87
88 Examples
89 --------
90 >>> from pyvista import demos
91 >>> demos.plot_glyphs()
92
93 """
94 # construct the glyphs on top of the mesh; don't scale by scalars now
95 mesh = glyphs(grid_sz)
96
97 kwargs.setdefault('specular', 1)
98 kwargs.setdefault('specular_power', 15)
99 kwargs.setdefault('smooth_shading', True)
100
101 # create plotter and add our glyphs with some nontrivial lighting
102 pl = pv.Plotter()
103 pl.add_mesh(mesh, show_scalar_bar=False, **kwargs)
104 return pl.show()
105
106
107 def orientation_cube():
108 """Return a dictionary containing the meshes composing an orientation cube.
109
110 Returns
111 -------
112 dict
113 Dictionary containing the meshes composing an orientation cube.
114
115 Examples
116 --------
117 Load the cube mesh and plot it
118
119 >>> import pyvista as pv
120 >>> from pyvista import demos
121 >>> ocube = demos.orientation_cube()
122 >>> pl = pv.Plotter()
123 >>> _ = pl.add_mesh(ocube['cube'], show_edges=True)
124 >>> _ = pl.add_mesh(ocube['x_p'], color='blue')
125 >>> _ = pl.add_mesh(ocube['x_n'], color='blue')
126 >>> _ = pl.add_mesh(ocube['y_p'], color='green')
127 >>> _ = pl.add_mesh(ocube['y_n'], color='green')
128 >>> _ = pl.add_mesh(ocube['z_p'], color='red')
129 >>> _ = pl.add_mesh(ocube['z_n'], color='red')
130 >>> pl.show_axes()
131 >>> pl.show()
132
133 """
134 cube = pv.Cube()
135
136 x_p = text_3d('X+', depth=0.2)
137 x_p.points *= 0.45
138 x_p.rotate_y(90, inplace=True)
139 x_p.rotate_x(90, inplace=True)
140 x_p.translate(-np.array(x_p.center), inplace=True)
141 x_p.translate([0.5, 0, 0], inplace=True)
142 # x_p.point_data['mesh'] = 1
143
144 x_n = text_3d('X-', depth=0.2)
145 x_n.points *= 0.45
146 x_n.rotate_y(90, inplace=True)
147 x_n.rotate_x(90, inplace=True)
148 x_n.rotate_z(180, inplace=True)
149 x_n.translate(-np.array(x_n.center), inplace=True)
150 x_n.translate([-0.5, 0, 0], inplace=True)
151 # x_n.point_data['mesh'] = 2
152
153 y_p = text_3d('Y+', depth=0.2)
154 y_p.points *= 0.45
155 y_p.rotate_x(90, inplace=True)
156 y_p.rotate_z(180, inplace=True)
157 y_p.translate(-np.array(y_p.center), inplace=True)
158 y_p.translate([0, 0.5, 0], inplace=True)
159 # y_p.point_data['mesh'] = 3
160
161 y_n = text_3d('Y-', depth=0.2)
162 y_n.points *= 0.45
163 y_n.rotate_x(90, inplace=True)
164 y_n.translate(-np.array(y_n.center), inplace=True)
165 y_n.translate([0, -0.5, 0], inplace=True)
166 # y_n.point_data['mesh'] = 4
167
168 z_p = text_3d('Z+', depth=0.2)
169 z_p.points *= 0.45
170 z_p.rotate_z(90, inplace=True)
171 z_p.translate(-np.array(z_p.center), inplace=True)
172 z_p.translate([0, 0, 0.5], inplace=True)
173 # z_p.point_data['mesh'] = 5
174
175 z_n = text_3d('Z-', depth=0.2)
176 z_n.points *= 0.45
177 z_n.rotate_x(180, inplace=True)
178 z_n.translate(-np.array(z_n.center), inplace=True)
179 z_n.translate([0, 0, -0.5], inplace=True)
180
181 return {
182 'cube': cube,
183 'x_p': x_p,
184 'x_n': x_n,
185 'y_p': y_p,
186 'y_n': y_n,
187 'z_p': z_p,
188 'z_n': z_n,
189 }
190
191
192 def orientation_plotter():
193 """Return a plotter containing the orientation cube.
194
195 Returns
196 -------
197 pyvista.Plotter
198 Orientation cube plotter.
199
200 Examples
201 --------
202 >>> from pyvista import demos
203 >>> pl = demos.orientation_plotter()
204 >>> pl.show()
205
206 """
207 ocube = orientation_cube()
208 pl = pv.Plotter()
209 pl.add_mesh(ocube['cube'], show_edges=True)
210 pl.add_mesh(ocube['x_p'], color='blue')
211 pl.add_mesh(ocube['x_n'], color='blue')
212 pl.add_mesh(ocube['y_p'], color='green')
213 pl.add_mesh(ocube['y_n'], color='green')
214 pl.add_mesh(ocube['z_p'], color='red')
215 pl.add_mesh(ocube['z_n'], color='red')
216 pl.show_axes() # type: ignore[call-arg]
217 return pl
218
219
220 @_deprecate_positional_args
221 def plot_wave(fps=30, frequency=1, wavetime=3, notebook=None): # noqa: PLR0917
222 """Plot a 3D moving wave in a render window.
223
224 Parameters
225 ----------
226 fps : int, default: 30
227 Maximum frames per second to display.
228
229 frequency : float, default: 1.0
230 Wave cycles per second (Hz).
231
232 wavetime : float, default: 3.0
233 The desired total display time in seconds.
234
235 notebook : bool, optional
236 When ``True``, the resulting plot is placed inline a jupyter
237 notebook. Assumes a jupyter console is active.
238
239 Returns
240 -------
241 numpy.ndarray
242 Position of points at last frame.
243
244 Examples
245 --------
246 >>> from pyvista import demos
247 >>> out = demos.plot_wave()
248
249 """
250 # camera position
251 cpos = pv.CameraPosition(
252 position=(6.879481857604187, -32.143727535933195, 23.05622921691103),
253 focal_point=(-0.2336056403734026, -0.6960083534590372, -0.7226721553894022),
254 viewup=(-0.008900669873416645, 0.6018246347860926, 0.7985786667826725),
255 )
256
257 # Make data
258 X = np.arange(-10, 10, 0.25)
259 Y = np.arange(-10, 10, 0.25)
260 X, Y = np.meshgrid(X, Y)
261 R = np.sqrt(X**2 + Y**2)
262 Z = np.sin(R)
263
264 # Create and plot structured grid
265 sgrid = pv.StructuredGrid(X, Y, Z)
266
267 mesh = sgrid.extract_surface(algorithm=None)
268 mesh['Height'] = Z.ravel()
269
270 # Start a plotter object and set the scalars to the Z height
271 pl = pv.Plotter(notebook=notebook)
272 pl.add_mesh(mesh, scalars='Height', show_scalar_bar=False, smooth_shading=True)
273 pl.camera_position = cpos
274 pl.show(
275 title='Wave Example',
276 window_size=[800, 600],
277 auto_close=False,
278 interactive_update=True,
279 )
280
281 # Update Z and display a frame for each updated position
282 tdelay = 1.0 / fps
283 tlast = time.time()
284 tstart = time.time()
285 while time.time() - tstart < wavetime:
286 # get phase from start
287 telap = time.time() - tstart
288 phase = telap * 2 * np.pi * frequency
289 Z = np.sin(R + phase)
290 mesh.points[:, -1] = Z.ravel() # type: ignore[index]
291 mesh['Height'] = Z.ravel()
292
293 mesh.compute_normals(inplace=True)
294
295 # Render and get time to render
296 pl.update()
297
298 # time delay
299 tpast = time.time() - tlast
300 if tpast < tdelay and tpast >= 0 and not pl.off_screen:
301 time.sleep(tdelay - tpast)
302
303 # store when rendering complete
304 tlast = time.time()
305
306 # Close movie and delete object
307 pl.close()
308 return mesh.points
309
310
311 def plot_ants_plane(notebook=None):
312 """Plot two ants and airplane.
313
314 Demonstrate how to create a plot class to plot multiple meshes while
315 adding scalars and text.
316
317 This example plots the following:
318
319 .. code-block:: python
320
321 >>> import pyvista as pv
322 >>> from pyvista import examples
323
324 Load and shrink airplane
325
326 >>> airplane = examples.load_airplane()
327 >>> airplane.points /= 10
328
329 Rotate and translate ant so it is on the plane.
330
331 >>> ant = examples.load_ant()
332 >>> _ = ant.rotate_x(90, inplace=True)
333 >>> _ = ant.translate([90, 60, 15], inplace=True)
334
335 Make a copy and add another ant.
336
337 >>> ant_copy = ant.translate([30, 0, -10], inplace=False)
338
339 Create plotting object.
340
341 >>> pl = pv.Plotter()
342 >>> _ = pl.add_mesh(ant, color='r')
343 >>> _ = pl.add_mesh(ant_copy, color='b')
344
345 Add airplane mesh and make the color equal to the Y position.
346
347 >>> plane_scalars = airplane.points[:, 1]
348 >>> _ = pl.add_mesh(
349 ... airplane,
350 ... scalars=plane_scalars,
351 ... scalar_bar_args={'title': 'Plane Y Location'},
352 ... )
353 >>> _ = pl.add_text('Ants and Plane Example')
354 >>> pl.show()
355
356 Parameters
357 ----------
358 notebook : bool, optional
359 When ``True``, the resulting plot is placed inline a jupyter
360 notebook. Assumes a jupyter console is active.
361
362 Examples
363 --------
364 >>> from pyvista import demos
365 >>> demos.plot_ants_plane()
366
367 """
368 # load and shrink airplane
369 airplane = examples.load_airplane()
370 airplane.points /= 10
371
372 # rotate and translate ant so it is on the plane
373 ant = examples.load_ant()
374 ant.rotate_x(90, inplace=True)
375 ant.translate([90, 60, 15], inplace=True)
376
377 # Make a copy and add another ant
378 ant_copy = ant.copy()
379 ant_copy.translate([30, 0, -10], inplace=True)
380
381 # Create plotting object
382 pl = pv.Plotter(notebook=notebook)
383 pl.add_mesh(ant, color='r')
384 pl.add_mesh(ant_copy, color='b')
385
386 # Add airplane mesh and make the color equal to the Y position
387 plane_scalars = airplane.points[:, 1]
388 pl.add_mesh(
389 airplane,
390 scalars=plane_scalars,
391 scalar_bar_args={'title': 'Plane Y\nLocation'},
392 )
393 pl.add_text('Ants and Plane Example')
394 pl.show()
395
396
397 def plot_beam(notebook=None):
398 """Plot a beam with displacement.
399
400 Parameters
401 ----------
402 notebook : bool, optional
403 When ``True``, the resulting plot is placed inline a jupyter
404 notebook. Assumes a jupyter console is active.
405
406 Examples
407 --------
408 >>> from pyvista import demos
409 >>> demos.plot_beam()
410
411 """
412 # Create fiticious displacements as a function of Z location
413 grid = examples.load_hexbeam()
414 d = grid.points[:, 2] ** 3 / 250
415 grid.points[:, 1] += d
416
417 # Camera position
418 cpos = pv.CameraPosition(
419 position=(11.915126303095157, 6.11392754955802, 3.6124956735471914),
420 focal_point=(0.0, 0.375, 2.0),
421 viewup=(-0.42546442225230097, 0.9024244135964158, -0.06789847673314177),
422 )
423
424 cmap = 'bwr'
425
426 # plot this displaced beam
427 pl = pv.Plotter(notebook=notebook)
428 pl.add_mesh(
429 grid,
430 scalars=d,
431 scalar_bar_args={'title': 'Y Displacement'},
432 rng=[-d.max(), d.max()],
433 cmap=cmap, # type: ignore[arg-type]
434 )
435 pl.camera_position = cpos
436 pl.add_text('Static Beam Example')
437 pl.show()
438
439
440 def plot_datasets(dataset_type=None):
441 """Plot the pyvista dataset types.
442
443 This demo plots the following PyVista dataset types:
444
445 * :class:`pyvista.PolyData`
446 * :class:`pyvista.UnstructuredGrid`
447 * :class:`pyvista.ImageData`
448 * :class:`pyvista.RectilinearGrid`
449 * :class:`pyvista.StructuredGrid`
450
451 Parameters
452 ----------
453 dataset_type : str, optional
454 If set, plot just that dataset. Must be one of the following:
455
456 * ``'PolyData'``
457 * ``'UnstructuredGrid'``
458 * ``'ImageData'``
459 * ``'RectilinearGrid'``
460 * ``'StructuredGrid'``
461
462 Examples
463 --------
464 >>> from pyvista import demos
465 >>> demos.plot_datasets()
466
467 """
468 allowable_types = [
469 'PolyData',
470 'UnstructuredGrid',
471 'ImageData',
472 'RectilinearGrid',
473 'StructuredGrid',
474 ]
475 if dataset_type is not None and dataset_type not in allowable_types:
476 msg = (
477 f'Invalid dataset_type {dataset_type}. '
478 f'Must be one of the following: {allowable_types}'
479 )
480 raise ValueError(msg)
481
482 ###########################################################################
483 # uniform grid
484 image = pv.ImageData(dimensions=(6, 6, 1))
485 image.spacing = (3, 2, 1)
486
487 ###########################################################################
488 # RectilinearGrid
489 xrng = np.array([0, 0.3, 1, 4, 5, 6, 6.2, 6.6])
490 yrng = np.linspace(-2, 2, 5)
491 zrng = [1]
492 rec_grid = pv.RectilinearGrid(xrng, yrng, zrng)
493
494 ###########################################################################
495 # structured grid
496 ang = np.linspace(0, np.pi / 2, 10)
497 r = np.linspace(6, 10, 8)
498 z = [0]
499 ang, r, z = np.meshgrid(ang, r, z) # type: ignore[assignment]
500
501 x = r * np.sin(ang)
502 y = r * np.cos(ang)
503
504 struct_grid = pv.StructuredGrid(x[::-1], y[::-1], z[::-1])
505
506 ###########################################################################
507 # polydata
508 points = pv.PolyData([[1.0, 2.0, 2.0], [2.0, 2.0, 2.0]])
509
510 line = pv.Line()
511 line.points += np.array((2, 0, 0))
512 line.clear_data()
513
514 tri = pv.Triangle()
515 tri.points += np.array([0, 1, 0])
516 circ = pv.Circle()
517 circ.points += np.array([1.5, 1.5, 0])
518
519 poly = tri + circ
520
521 ###########################################################################
522 # unstructuredgrid
523 pyr = pv.Pyramid()
524 pyr.points *= 0.7
525 cube = pv.Cube(center=(2, 0, 0))
526 ugrid = circ + pyr + cube + tri
527
528 pl = pv.Plotter() if dataset_type is not None else pv.Plotter(shape='3/2')
529
530 # polydata
531 if dataset_type is None:
532 pl.subplot(0)
533 pl.add_text('4. PolyData')
534 if dataset_type in [None, 'PolyData']:
535 pl.add_points(points, point_size=20)
536 pl.add_mesh(line, line_width=5)
537 pl.add_mesh(poly)
538 pl.add_mesh(poly.extract_all_edges(), line_width=2, color='k')
539
540 # unstructuredgrid
541 if dataset_type is None:
542 pl.subplot(1)
543 pl.add_text('5. UnstructuredGrid')
544 if dataset_type in [None, 'UnstructuredGrid']:
545 pl.add_mesh(ugrid)
546 pl.add_mesh(ugrid.extract_all_edges(), line_width=2, color='k')
547
548 # ImageData
549 if dataset_type is None:
550 pl.subplot(2)
551 pl.add_text('1. ImageData')
552 if dataset_type in [None, 'ImageData']:
553 pl.add_mesh(image)
554 pl.add_mesh(image.extract_all_edges(), color='k', style='wireframe', line_width=2)
555 pl.camera_position = 'xy'
556
557 # RectilinearGrid
558 if dataset_type is None:
559 pl.subplot(3)
560 pl.add_text('2. RectilinearGrid')
561 if dataset_type in [None, 'RectilinearGrid']:
562 pl.add_mesh(rec_grid)
563 pl.add_mesh(rec_grid.extract_all_edges(), color='k', style='wireframe', line_width=2)
564 pl.camera_position = 'xy'
565
566 # StructuredGrid
567 if dataset_type is None:
568 pl.subplot(4)
569 pl.add_text('3. StructuredGrid')
570 if dataset_type in [None, 'StructuredGrid']:
571 pl.add_mesh(struct_grid)
572 pl.add_mesh(struct_grid.extract_all_edges(), color='k', style='wireframe', line_width=2)
573 pl.camera_position = 'xy'
574
575 pl.show()