Debian Codegraph @

pyvista/examples/examples.py

raw
1 """Built-in examples that ship with PyVista and do not need to be downloaded.
2
3 Examples
4 --------
5 >>> from pyvista import examples
6 >>> mesh = examples.load_ant()
7 >>> mesh.plot()
8
9 """
10
11 from __future__ import annotations
12
13 import math
14 import os
15 from pathlib import Path
16 from typing import TYPE_CHECKING
17
18 import numpy as np
19
20 import pyvista as pv
21 from pyvista.examples._dataset_loader import _DatasetLoader
22 from pyvista.examples._dataset_loader import _SingleFileDownloadableDatasetLoader
23
24 if TYPE_CHECKING:
25 from pyvista import PolyData
26
27 # get location of this folder and the example files
28 dir_path = str(Path(os.path.realpath(__file__)).parent)
29 antfile = str(Path(dir_path) / 'ant.ply')
30 planefile = str(Path(dir_path) / 'airplane.ply')
31 hexbeamfile = str(Path(dir_path) / 'hexbeam.vtk')
32 spherefile = str(Path(dir_path) / 'sphere.ply')
33 uniformfile = str(Path(dir_path) / 'uniform.vtk')
34 rectfile = str(Path(dir_path) / 'rectilinear.vtk')
35 globefile = str(Path(dir_path) / 'globe.vtk')
36 mapfile = str(Path(dir_path) / '2k_earth_daymap.jpg')
37 channelsfile = str(Path(dir_path) / 'channels.vti')
38 logofile = str(Path(dir_path) / 'pyvista_logo.png')
39 nutfile = str(Path(dir_path) / 'nut.ply')
40 frogtissuesfile = str(Path(dir_path) / 'frog_tissues.vti')
41
42
43 def load_ant():
44 """Load ply ant mesh.
45
46 Returns
47 -------
48 pyvista.PolyData
49 Dataset.
50
51 Examples
52 --------
53 >>> from pyvista import examples
54 >>> dataset = examples.load_ant()
55 >>> dataset.plot()
56
57 .. seealso::
58
59 :ref:`Ant Dataset <ant_dataset>`
60 See this dataset in the Dataset Gallery for more info.
61
62 """
63 return _dataset_ant.load()
64
65
66 _dataset_ant = _SingleFileDownloadableDatasetLoader(antfile, read_func=pv.PolyData)
67
68
69 def load_airplane():
70 """Load ply airplane mesh.
71
72 Returns
73 -------
74 pyvista.PolyData
75 Dataset.
76
77 Examples
78 --------
79 >>> from pyvista import examples
80 >>> dataset = examples.load_airplane()
81 >>> dataset.plot()
82
83 .. seealso::
84
85 :ref:`Airplane Dataset <airplane_dataset>`
86 See this dataset in the Dataset Gallery for more info.
87
88 """
89 return _dataset_airplane.load()
90
91
92 _dataset_airplane = _SingleFileDownloadableDatasetLoader(planefile, read_func=pv.PolyData)
93
94
95 def load_sphere():
96 """Load sphere ply mesh.
97
98 Returns
99 -------
100 pyvista.PolyData
101 Dataset.
102
103 Examples
104 --------
105 >>> from pyvista import examples
106 >>> dataset = examples.load_sphere()
107 >>> dataset.plot()
108
109 .. seealso::
110
111 :ref:`Sphere Dataset <sphere_dataset>`
112 See this dataset in the Dataset Gallery for more info.
113
114 """
115 return _dataset_sphere.load()
116
117
118 _dataset_sphere = _SingleFileDownloadableDatasetLoader(spherefile, read_func=pv.PolyData)
119
120
121 def load_uniform():
122 """Load a sample uniform grid.
123
124 Returns
125 -------
126 pyvista.ImageData
127 Dataset.
128
129 Examples
130 --------
131 >>> from pyvista import examples
132 >>> dataset = examples.load_uniform()
133 >>> dataset.plot()
134
135 .. seealso::
136
137 :ref:`Uniform Dataset <uniform_dataset>`
138 See this dataset in the Dataset Gallery for more info.
139
140 """
141 return _dataset_uniform.load()
142
143
144 _dataset_uniform = _SingleFileDownloadableDatasetLoader(uniformfile, read_func=pv.ImageData)
145
146
147 def load_rectilinear():
148 """Load a sample uniform grid.
149
150 Returns
151 -------
152 pyvista.RectilinearGrid
153 Dataset.
154
155 Examples
156 --------
157 >>> from pyvista import examples
158 >>> dataset = examples.load_rectilinear()
159 >>> dataset.plot()
160
161 .. seealso::
162
163 :ref:`Rectilinear Dataset <rectilinear_dataset>`
164 See this dataset in the Dataset Gallery for more info.
165
166 """
167 return _dataset_rectilinear.load()
168
169
170 _dataset_rectilinear = _SingleFileDownloadableDatasetLoader(
171 rectfile,
172 read_func=pv.RectilinearGrid,
173 )
174
175
176 def load_hexbeam():
177 """Load a sample UnstructuredGrid.
178
179 Returns
180 -------
181 pyvista.UnstructuredGrid
182 Dataset.
183
184 Examples
185 --------
186 >>> from pyvista import examples
187 >>> dataset = examples.load_hexbeam()
188 >>> dataset.plot()
189
190 .. seealso::
191
192 :ref:`Hexbeam Dataset <hexbeam_dataset>`
193 See this dataset in the Dataset Gallery for more info.
194
195 """
196 return _dataset_hexbeam.load()
197
198
199 _dataset_hexbeam = _SingleFileDownloadableDatasetLoader(
200 hexbeamfile,
201 read_func=pv.UnstructuredGrid,
202 )
203
204
205 def load_tetbeam():
206 """Load a sample UnstructuredGrid containing only tetrahedral cells.
207
208 Returns
209 -------
210 pyvista.UnstructuredGrid
211 Dataset.
212
213 Examples
214 --------
215 >>> from pyvista import examples
216 >>> dataset = examples.load_tetbeam()
217 >>> dataset.plot()
218
219 .. seealso::
220
221 :ref:`Tetbeam Dataset <tetbeam_dataset>`
222 See this dataset in the Dataset Gallery for more info.
223
224 """
225 return _dataset_tetbeam.load()
226
227
228 def _tetbeam_load_func():
229 # make the geometry identical to the hexbeam
230 xrng = np.linspace(0, 1, 3)
231 yrng = np.linspace(0, 1, 3)
232 zrng = np.linspace(0, 5, 11)
233 grid = pv.RectilinearGrid(xrng, yrng, zrng)
234 return grid.to_tetrahedra()
235
236
237 _dataset_tetbeam = _DatasetLoader(_tetbeam_load_func)
238
239
240 def load_structured():
241 """Load a simple StructuredGrid.
242
243 Returns
244 -------
245 pyvista.StructuredGrid
246 Dataset.
247
248 Examples
249 --------
250 >>> from pyvista import examples
251 >>> dataset = examples.load_structured()
252 >>> dataset.plot()
253
254 .. seealso::
255
256 :ref:`Structured Dataset <structured_dataset>`
257 See this dataset in the Dataset Gallery for more info.
258
259 """
260 return _dataset_structured.load()
261
262
263 def _structured_load_func():
264 x = np.arange(-10, 10, 0.25)
265 y = np.arange(-10, 10, 0.25)
266 x, y = np.meshgrid(x, y)
267 r = np.sqrt(x**2 + y**2)
268 z = np.sin(r)
269 return pv.StructuredGrid(x, y, z)
270
271
272 _dataset_structured = _DatasetLoader(_structured_load_func)
273
274
275 def load_globe():
276 """Load a globe source.
277
278 Returns
279 -------
280 pyvista.PolyData
281 Globe dataset with earth texture.
282
283 Examples
284 --------
285 >>> from pyvista import examples
286 >>> dataset = examples.load_globe()
287 >>> texture = examples.load_globe_texture()
288 >>> dataset.plot(texture=texture)
289
290 .. seealso::
291
292 :ref:`Globe Dataset <globe_dataset>`
293 See this dataset in the Dataset Gallery for more info.
294
295 """
296 return _dataset_globe.load()
297
298
299 _dataset_globe = _SingleFileDownloadableDatasetLoader(globefile, read_func=pv.PolyData)
300
301
302 def load_globe_texture():
303 """Load a pyvista.Texture that can be applied to the globe source.
304
305 Returns
306 -------
307 pyvista.Texture
308 Dataset.
309
310 Examples
311 --------
312 >>> from pyvista import examples
313 >>> dataset = examples.load_globe_texture()
314 >>> dataset.plot()
315
316 .. seealso::
317
318 :ref:`Globe Texture Dataset <globe_texture_dataset>`
319 See this dataset in the Dataset Gallery for more info.
320
321 """
322 return _dataset_globe_texture.load()
323
324
325 _dataset_globe_texture = _SingleFileDownloadableDatasetLoader(
326 mapfile,
327 read_func=pv.read_texture,
328 )
329
330
331 def load_channels():
332 """Load a uniform grid of fluvial channels in the subsurface.
333
334 Returns
335 -------
336 pyvista.ImageData
337 Dataset.
338
339 Examples
340 --------
341 >>> from pyvista import examples
342 >>> dataset = examples.load_channels()
343 >>> dataset.plot()
344
345 .. seealso::
346
347 :ref:`Channels Dataset <channels_dataset>`
348 See this dataset in the Dataset Gallery for more info.
349
350 """
351 return _dataset_channels.load()
352
353
354 _dataset_channels = _SingleFileDownloadableDatasetLoader(channelsfile)
355
356
357 def load_spline():
358 """Load an example spline mesh.
359
360 This example data was created with:
361
362 .. code-block:: python
363
364 >>> import numpy as np
365 >>> import pyvista as pv
366 >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
367 >>> z = np.linspace(-2, 2, 100)
368 >>> r = z**2 + 1
369 >>> x = r * np.sin(theta)
370 >>> y = r * np.cos(theta)
371 >>> points = np.column_stack((x, y, z))
372 >>> mesh = pv.Spline(points, 1000)
373
374 Returns
375 -------
376 pyvista.PolyData
377 Spline mesh.
378
379 Examples
380 --------
381 >>> from pyvista import examples
382 >>> spline = examples.load_spline()
383 >>> spline.plot()
384
385 .. seealso::
386
387 :ref:`Spline Dataset <spline_dataset>`
388 See this dataset in the Dataset Gallery for more info.
389
390 """
391 return _dataset_spline.load()
392
393
394 def _spline_load_func():
395 theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
396 z = np.linspace(-2, 2, 100)
397 r = z**2 + 1
398 x = r * np.sin(theta)
399 y = r * np.cos(theta)
400 points = np.column_stack((x, y, z))
401 return pv.Spline(points, 1000)
402
403
404 _dataset_spline = _DatasetLoader(_spline_load_func)
405
406
407 def load_random_hills():
408 """Create random hills toy example.
409
410 Uses the parametric random hill function to create hills oriented
411 like topography and adds an elevation array.
412
413 This example dataset was created with:
414
415 .. code-block:: python
416
417 >>> mesh = pv.ParametricRandomHills() # doctest:+SKIP
418 >>> mesh = mesh.elevation() # doctest:+SKIP
419
420 Returns
421 -------
422 pyvista.PolyData
423 Random hills mesh.
424
425 Examples
426 --------
427 >>> from pyvista import examples
428 >>> mesh = examples.load_random_hills()
429 >>> mesh.plot()
430
431 .. seealso::
432
433 :ref:`Random Hills Dataset <random_hills_dataset>`
434 See this dataset in the Dataset Gallery for more info.
435
436 """
437 return _dataset_random_hills.load()
438
439
440 def _random_hills_load_func():
441 mesh = pv.ParametricRandomHills()
442 return mesh.elevation()
443
444
445 _dataset_random_hills = _DatasetLoader(_random_hills_load_func)
446
447
448 def load_sphere_vectors():
449 """Create example sphere with a swirly vector field defined on nodes.
450
451 Returns
452 -------
453 pyvista.PolyData
454 Mesh containing vectors.
455
456 Examples
457 --------
458 >>> from pyvista import examples
459 >>> mesh = examples.load_sphere_vectors()
460 >>> mesh.point_data
461 pyvista DataSetAttributes
462 Association : POINT
463 Active Scalars : vectors
464 Active Vectors : vectors
465 Active Texture : None
466 Active Normals : Normals
467 Contains arrays :
468 Normals float32 (842, 3) NORMALS
469 vectors float32 (842, 3) VECTORS
470
471 .. seealso::
472
473 :ref:`Sphere Vectors Dataset <sphere_vectors_dataset>`
474 See this dataset in the Dataset Gallery for more info.
475
476 """
477 return _dataset_sphere_vectors.load()
478
479
480 def _sphere_vectors_load_func() -> PolyData:
481 sphere = pv.Sphere(radius=math.pi)
482
483 # make cool swirly pattern
484 vectors = np.vstack(
485 (
486 np.sin(sphere.points[:, 0]),
487 np.cos(sphere.points[:, 1]),
488 np.cos(sphere.points[:, 2]),
489 ),
490 ).T
491
492 # add and scale
493 sphere['vectors'] = vectors * 0.3
494 sphere.set_active_vectors('vectors')
495 return sphere
496
497
498 _dataset_sphere_vectors = _DatasetLoader(_sphere_vectors_load_func)
499
500
501 def load_explicit_structured(dimensions=(5, 6, 7), spacing=(20, 10, 1)):
502 """Load a simple explicit structured grid.
503
504 Parameters
505 ----------
506 dimensions : tuple(int), optional
507 Grid dimensions. Default is (5, 6, 7).
508 spacing : tuple(int), optional
509 Grid spacing. Default is (20, 10, 1).
510
511 Returns
512 -------
513 pyvista.ExplicitStructuredGrid
514 An explicit structured grid.
515
516 Examples
517 --------
518 >>> from pyvista import examples
519 >>> grid = examples.load_explicit_structured()
520 >>> grid.plot(show_edges=True)
521
522 .. seealso::
523
524 :ref:`Explicit Structured Dataset <explicit_structured_dataset>`
525 See this dataset in the Dataset Gallery for more info.
526
527 """
528 return _dataset_explicit_structured.load(dimensions=dimensions, spacing=spacing)
529
530
531 def _explicit_structured_load_func(dimensions=(5, 6, 7), spacing=(20, 10, 1)):
532 ni, nj, nk = np.asarray(dimensions) - 1
533 si, sj, sk = spacing
534 xi = np.arange(0.0, (ni + 1) * si, si)
535 yi = np.arange(0.0, (nj + 1) * sj, sj)
536 zi = np.arange(0.0, (nk + 1) * sk, sk)
537
538 return pv.StructuredGrid(
539 *np.meshgrid(xi, yi, zi, indexing='ij')
540 ).cast_to_explicit_structured_grid()
541
542
543 _dataset_explicit_structured = _DatasetLoader(_explicit_structured_load_func)
544
545
546 def load_nut():
547 """Load an example nut mesh.
548
549 Returns
550 -------
551 pyvista.PolyData
552 A sample nut surface dataset.
553
554 Examples
555 --------
556 Load an example nut and plot with smooth shading.
557
558 >>> from pyvista import examples
559 >>> mesh = examples.load_nut()
560 >>> mesh.plot(smooth_shading=True, split_sharp_edges=True)
561
562 .. seealso::
563
564 :ref:`Nut Dataset <nut_dataset>`
565 See this dataset in the Dataset Gallery for more info.
566
567 """
568 return _dataset_nut.load()
569
570
571 _dataset_nut = _SingleFileDownloadableDatasetLoader(nutfile)
572
573
574 def load_hydrogen_orbital(n=1, l=0, m=0, zoom_fac=1.0): # noqa: PLR0917
575 """Load the hydrogen wave function for a :class:`pyvista.ImageData`.
576
577 This is the solution to the Schrödinger equation for hydrogen
578 evaluated in three-dimensional Cartesian space.
579
580 Inspired by `Hydrogen Wave Function
581 <http://staff.ustc.edu.cn/~zqj/posts/Hydrogen-Wavefunction/>`_.
582
583 Parameters
584 ----------
585 n : int, default: 1
586 Principal quantum number. Must be a positive integer. This is often
587 referred to as the "energy level" or "shell".
588
589 l : int, default: 0
590 Azimuthal quantum number. Must be a non-negative integer strictly
591 smaller than ``n``. By convention this value is represented by the
592 letters s, p, d, f, etc.
593
594 m : int, default: 0
595 Magnetic quantum number. Must be an integer ranging from ``-l`` to
596 ``l`` (inclusive). This is the orientation of the angular momentum in
597 space.
598
599 zoom_fac : float, default: 1.0
600 Zoom factor for the electron cloud. Increase this value to focus on the
601 center of the electron cloud.
602
603 Returns
604 -------
605 pyvista.ImageData
606 ImageData containing two ``point_data`` arrays:
607
608 * ``'real_wf'`` - Real part of the wave function.
609 * ``'wf'`` - Complex wave function.
610
611 Notes
612 -----
613 This example requires `sympy <https://www.sympy.org/>`_.
614
615 Examples
616 --------
617 Plot the 3dxy orbital of a hydrogen atom. This corresponds to the quantum
618 numbers ``n=3``, ``l=2``, and ``m=-2``.
619
620 >>> from pyvista import examples
621 >>> grid = examples.load_hydrogen_orbital(3, 2, -2)
622 >>> grid.plot(volume=True, opacity=[1, 0, 1], cmap='magma')
623
624 See :ref:`atomic_orbitals_example` for additional examples using
625 this function.
626
627 .. seealso::
628
629 :ref:`Hydrogen Orbital Dataset <hydrogen_orbital_dataset>`
630 See this dataset in the Dataset Gallery for more info.
631
632 """
633 return _dataset_hydrogen_orbital.load(n=n, l=l, m=m, zoom_fac=zoom_fac)
634
635
636 def _hydrogen_orbital_load_func(n=1, l=0, m=0, zoom_fac=1.0): # noqa: PLR0917
637 try:
638 from sympy import lambdify
639 from sympy.abc import phi
640 from sympy.abc import r
641 from sympy.abc import theta
642 from sympy.physics.hydrogen import Psi_nlm
643 except ImportError: # pragma: no cover
644 msg = '\n\nInstall sympy to run this example. Run:\n\n pip install sympy\n'
645 raise ImportError(msg) from None
646
647 if n < 1:
648 msg = '`n` must be at least 1'
649 raise ValueError(msg)
650 if l not in range(n):
651 msg = f'`l` must be one of: {list(range(n))}'
652 raise ValueError(msg)
653 if m not in range(-l, l + 1):
654 msg = f'`m` must be one of: {list(range(-l, l + 1))}'
655 raise ValueError(msg)
656
657 psi = lambdify((r, phi, theta), Psi_nlm(n, l, m, r, phi, theta, 1), 'numpy')
658
659 org = 1.5 * n**2 + 1.0 if n == 1 else 1.5 * n**2 + 10.0
660
661 org /= zoom_fac
662
663 dim = 100
664 sp = (org * 2) / (dim - 1)
665 grid = pv.ImageData(
666 dimensions=(dim, dim, dim),
667 spacing=(sp, sp, sp),
668 origin=(-org, -org, -org),
669 )
670
671 r, theta, phi = pv.cartesian_to_spherical(grid.x, grid.y, grid.z)
672 wfc = psi(r, phi, theta).reshape(grid.dimensions)
673
674 grid['real_wf'] = np.real(wfc.ravel())
675 grid['wf'] = wfc.ravel()
676 return grid
677
678
679 _dataset_hydrogen_orbital = _DatasetLoader(_hydrogen_orbital_load_func)
680
681
682 def load_logo():
683 """Load the PyVista logo as a :class:`pyvista.ImageData`.
684
685 .. note::
686
687 Alternative versions of the logo file are also available from the ``logo``
688 directory at https://github.com/pyvista/pyvista/. This includes
689 higher-resolution ``.png`` files and a vectorized ``.svg`` version.
690
691 .. versionchanged:: 0.45
692
693 The dimensions of the image is now ``1389 x 592``.
694 Previously, it was ``1920 x 718``.
695
696 Returns
697 -------
698 pyvista.ImageData
699 ImageData of the PyVista logo.
700
701 Examples
702 --------
703 >>> from pyvista import examples
704 >>> image = examples.load_logo()
705 >>> image.dimensions
706 (1389, 592, 1)
707
708 >>> image.plot(cpos='xy', zoom='tight', rgb=True, show_axes=False)
709
710 .. seealso::
711
712 :ref:`Logo Dataset <logo_dataset>`
713 See this dataset in the Dataset Gallery for more info.
714
715 """
716 return _dataset_logo.load()
717
718
719 _dataset_logo = _SingleFileDownloadableDatasetLoader(logofile)
720
721
722 def load_frog_tissues():
723 """Load frog tissues dataset.
724
725 This dataset contains tissue segmentation labels for the frog dataset.
726
727 .. versionadded:: 0.44.0
728
729 Returns
730 -------
731 pyvista.ImageData
732 Dataset.
733
734 Examples
735 --------
736 Load data
737
738 >>> import numpy as np
739 >>> import pyvista as pv
740 >>> from pyvista import examples
741 >>> data = examples.load_frog_tissues()
742
743 Plot tissue labels as a volume
744
745 First, define plotting parameters
746
747 >>> # Configure colors / color bar
748 >>> clim = data.get_data_range() # Set color bar limits to match data
749 >>> cmap = 'glasbey' # Use a categorical colormap
750 >>> categories = True # Ensure n_colors matches number of labels
751 >>> opacity = 'foreground' # Make foreground opaque, background transparent
752 >>> opacity_unit_distance = 1
753
754 Set plotting resolution to half the image's spacing
755
756 >>> res = np.array(data.spacing) / 2
757
758 Define rendering parameters
759
760 >>> mapper = 'gpu'
761 >>> shade = True
762 >>> ambient = 0.3
763 >>> diffuse = 0.6
764 >>> specular = 0.5
765 >>> specular_power = 40
766
767 Make and show plot
768
769 >>> pl = pv.Plotter()
770 >>> _ = pl.add_volume(
771 ... data,
772 ... clim=clim,
773 ... ambient=ambient,
774 ... shade=shade,
775 ... diffuse=diffuse,
776 ... specular=specular,
777 ... specular_power=specular_power,
778 ... mapper=mapper,
779 ... opacity=opacity,
780 ... opacity_unit_distance=opacity_unit_distance,
781 ... categories=categories,
782 ... cmap=cmap,
783 ... resolution=res,
784 ... )
785 >>> pl.camera_position = 'yx' # Set camera to provide a dorsal view
786 >>> pl.show()
787
788 .. seealso::
789
790 :ref:`Frog Tissues Dataset <frog_tissues_dataset>`
791 See this dataset in the Dataset Gallery for more info.
792
793 :ref:`Frog Dataset <frog_dataset>`
794
795 :ref:`medical_dataset_gallery`
796 Browse other medical datasets.
797
798 """
799 return _dataset_frog_tissues.load()
800
801
802 _dataset_frog_tissues = _SingleFileDownloadableDatasetLoader(frogtissuesfile)