Debian Codegraph @

pyvista/core/utilities/geometric_objects.py

raw
1 """Provides an easy way of generating several geometric objects."""
2
3 from __future__ import annotations
4
5 import contextlib
6 from itertools import product
7 from typing import Literal
8 from typing import cast
9
10 import numpy as np
11
12 import pyvista as pv
13 from pyvista import _vtk
14 from pyvista._deprecate_positional_args import _deprecate_positional_args
15 from pyvista.core import _validation
16
17 from .arrays import _coerce_pointslike_arg
18 from .geometric_sources import ArrowSource
19 from .geometric_sources import BoxSource
20 from .geometric_sources import ConeSource
21 from .geometric_sources import CubeSource
22 from .geometric_sources import CylinderSource
23 from .geometric_sources import DiscSource
24 from .geometric_sources import LineSource
25 from .geometric_sources import MultipleLinesSource
26 from .geometric_sources import PlaneSource
27 from .geometric_sources import PlatonicSolidSource
28 from .geometric_sources import PolygonSource
29 from .geometric_sources import SphereSource
30 from .geometric_sources import SuperquadricSource
31 from .geometric_sources import Text3DSource
32 from .geometric_sources import translate
33
34 with contextlib.suppress(ImportError):
35 from .geometric_sources import CapsuleSource
36
37 from typing import TYPE_CHECKING
38
39 from .helpers import wrap
40 from .misc import check_valid_vector
41
42 if TYPE_CHECKING:
43 from pyvista import ImageData
44 from pyvista import PolyData
45 from pyvista import StructuredGrid
46 from pyvista import UnstructuredGrid
47 from pyvista.core._typing_core import MatrixLike
48 from pyvista.core._typing_core import NumpyArray
49 from pyvista.core._typing_core import VectorLike
50
51
52 @_deprecate_positional_args
53 def Capsule( # noqa: PLR0917
54 center: VectorLike[float] = (0.0, 0.0, 0.0),
55 direction: VectorLike[float] = (1.0, 0.0, 0.0),
56 radius: float = 0.5,
57 cylinder_length: float = 1.0,
58 resolution: int = 30,
59 ) -> PolyData:
60 """Create the surface of a capsule.
61
62 .. warning::
63 :func:`pyvista.Capsule` function rotates the capsule :class:`pyvista.PolyData`
64 in its own way. It rotates the output 90 degrees in z-axis, translates and
65 orients the mesh to a new ``center`` and ``direction``.
66
67 .. note::
68 A class:`pyvista.CylinderSource` is used to generate the capsule mesh. For vtk
69 versions below 9.3, a separate ``pyvista.CapsuleSource`` class is used instead.
70 The mesh geometries are similar but not identical.
71
72 .. versionadded:: 0.44.0
73
74 Parameters
75 ----------
76 center : sequence[float], default: (0.0, 0.0, 0.0)
77 Location of the centroid in ``[x, y, z]``.
78
79 direction : sequence[float], default: (1.0, 0.0, 0.0)
80 Direction the capsule points to in ``[x, y, z]``.
81
82 radius : float, default: 0.5
83 Radius of the capsule.
84
85 cylinder_length : float, default: 1.0
86 Cylinder length of the capsule.
87
88 resolution : int, default: 30
89 Number of points on the circular face of the cylinder.
90
91 Returns
92 -------
93 pyvista.PolyData
94 Capsule surface.
95
96 See Also
97 --------
98 pyvista.Cylinder
99
100 Examples
101 --------
102 Create a capsule using default parameters.
103
104 >>> import pyvista as pv
105 >>> capsule = pv.Capsule()
106 >>> capsule.plot(show_edges=True)
107
108 """
109 if pv.vtk_version_info >= (9, 3): # pragma: no cover
110 algo = CylinderSource(
111 center=center,
112 direction=direction,
113 radius=radius,
114 height=cylinder_length,
115 capping=True,
116 resolution=resolution,
117 )
118 algo.capsule_cap = True
119 else:
120 algo = CapsuleSource(
121 center=(0, 0, 0),
122 direction=(1, 0, 0),
123 radius=radius,
124 cylinder_length=cylinder_length,
125 theta_resolution=resolution,
126 phi_resolution=resolution,
127 )
128 output = wrap(algo.output)
129 output.rotate_z(90, inplace=True)
130 translate(output, center, direction)
131 return output
132
133
134 @_deprecate_positional_args
135 def Cylinder( # noqa: PLR0917
136 center: VectorLike[float] = (0.0, 0.0, 0.0),
137 direction: VectorLike[float] = (1.0, 0.0, 0.0),
138 radius: float = 0.5,
139 height: float = 1.0,
140 resolution: int = 100,
141 capping: bool = True, # noqa: FBT001, FBT002
142 ) -> PolyData:
143 """Create the surface of a cylinder.
144
145 .. warning::
146 :func:`pyvista.Cylinder` function rotates the :class:`pyvista.CylinderSource` 's
147 :class:`pyvista.PolyData` in its own way.
148 It rotates the :attr:`pyvista.CylinderSource.output` 90 degrees in z-axis, translates and
149 orients the mesh to a new ``center`` and ``direction``.
150
151 See also :func:`pyvista.CylinderStructured`.
152
153 Parameters
154 ----------
155 center : sequence[float], default: (0.0, 0.0, 0.0)
156 Location of the centroid in ``[x, y, z]``.
157
158 direction : sequence[float], default: (1.0, 0.0, 0.0)
159 Direction cylinder points to in ``[x, y, z]``.
160
161 radius : float, default: 0.5
162 Radius of the cylinder.
163
164 height : float, default: 1.0
165 Height of the cylinder.
166
167 resolution : int, default: 100
168 Number of points on the circular face of the cylinder.
169
170 capping : bool, default: True
171 Cap cylinder ends with polygons.
172
173 Returns
174 -------
175 pyvista.PolyData
176 Cylinder surface.
177
178 Examples
179 --------
180 >>> import pyvista as pv
181 >>> cylinder = pv.Cylinder(
182 ... center=[1, 2, 3], direction=[1, 1, 1], radius=1, height=2
183 ... )
184 >>> cylinder.plot(show_edges=True, line_width=5, cpos='xy')
185
186 >>> pl = pv.Plotter()
187 >>> _ = pl.add_mesh(
188 ... pv.Cylinder(center=[1, 2, 3], direction=[1, 1, 1], radius=1, height=2),
189 ... show_edges=True,
190 ... line_width=5,
191 ... )
192 >>> pl.camera_position = 'xy'
193 >>> pl.show()
194
195 The above examples are similar in terms of their behavior.
196
197 See :ref:`chemistry_molecule_example` for more examples using this function.
198
199 """
200 algo = CylinderSource(
201 center=center,
202 direction=direction,
203 radius=radius,
204 height=height,
205 capping=capping,
206 resolution=resolution,
207 )
208 output = wrap(algo.output)
209 output.rotate_z(90, inplace=True)
210 translate(output, center, direction)
211 return output
212
213
214 @_deprecate_positional_args
215 def CylinderStructured( # noqa: PLR0917
216 radius: float = 0.5,
217 height: float = 1.0,
218 center: VectorLike[float] = (0.0, 0.0, 0.0),
219 direction: VectorLike[float] = (1.0, 0.0, 0.0),
220 theta_resolution: int = 32,
221 z_resolution: int = 10,
222 ) -> StructuredGrid:
223 """Create a cylinder mesh as a :class:`pyvista.StructuredGrid`.
224
225 The end caps are left open. This can create a surface mesh if a single
226 value for the ``radius`` is given or a 3D mesh if multiple radii are given
227 as a list/array in the ``radius`` argument.
228
229 Parameters
230 ----------
231 radius : float | sequence[float], default: 0.5
232 Radius of the cylinder. If a sequence, then describes the
233 radial coordinates of the cells as a range of values as
234 specified by the ``radius``.
235
236 height : float, default: 1.0
237 Height of the cylinder along its Z-axis.
238
239 center : sequence[float], default: (0.0, 0.0, 0.0)
240 Location of the centroid in ``[x, y, z]``.
241
242 direction : sequence[float], default: (1.0, 0.0, 0.0)
243 Direction cylinder Z-axis in ``[x, y, z]``.
244
245 theta_resolution : int, default: 32
246 Number of points on the circular face of the cylinder.
247 Ignored if ``radius`` is an iterable.
248
249 z_resolution : int, default: 10
250 Number of points along the height (Z-axis) of the cylinder.
251
252 Returns
253 -------
254 pyvista.StructuredGrid
255 Structured cylinder.
256
257 Notes
258 -----
259 .. versionchanged:: 0.38.0
260 Prior to version 0.38, this method had incorrect results, producing
261 inconsistent number of points on the circular face of the cylinder.
262
263 Examples
264 --------
265 Default structured cylinder
266
267 >>> import pyvista as pv
268 >>> mesh = pv.CylinderStructured()
269 >>> mesh.plot(show_edges=True)
270
271 Structured cylinder with an inner radius of 1, outer of 2, with 5
272 segments.
273
274 >>> import numpy as np
275 >>> mesh = pv.CylinderStructured(radius=np.linspace(1, 2, 5))
276 >>> mesh.plot(show_edges=True)
277
278 """
279 # Define grid in polar coordinates
280 r = np.array([radius]).ravel()
281 nr = len(r)
282 theta = np.linspace(0, 2 * np.pi, num=theta_resolution + 1)
283 radius_matrix, theta_matrix = np.meshgrid(r, theta)
284
285 # Transform to cartesian space
286 X = radius_matrix * np.cos(theta_matrix)
287 Y = radius_matrix * np.sin(theta_matrix)
288
289 # Make all the nodes in the grid
290 xx = np.array([X] * z_resolution).ravel()
291 yy = np.array([Y] * z_resolution).ravel()
292 dz = height / (z_resolution - 1)
293 zz = np.empty(yy.size)
294 zz = np.full((X.size, z_resolution), dz)
295 zz *= np.arange(z_resolution)
296 zz = zz.ravel(order='f') # type: ignore[arg-type]
297
298 # Create the grid
299 grid = pv.StructuredGrid()
300 grid.points = np.c_[xx, yy, zz]
301 grid.dimensions = [nr, theta_resolution + 1, z_resolution]
302
303 # Center at origin
304 grid.points -= np.array(grid.center)
305
306 # rotate initially to face +X direction
307 grid.rotate_y(90, inplace=True)
308
309 # rotate points 180 for compatibility with previous versions
310 grid.rotate_x(180, inplace=True)
311
312 # move to final position
313 translate(grid, center=center, direction=direction)
314 return grid
315
316
317 @_deprecate_positional_args
318 def Arrow( # noqa: PLR0917
319 start: VectorLike[float] = (0.0, 0.0, 0.0),
320 direction: VectorLike[float] = (1.0, 0.0, 0.0),
321 tip_length: float = 0.25,
322 tip_radius: float = 0.1,
323 tip_resolution: int = 20,
324 shaft_radius: float = 0.05,
325 shaft_resolution: int = 20,
326 scale: float | Literal['auto'] | None = 1.0,
327 ) -> PolyData:
328 """Create an arrow.
329
330 Parameters
331 ----------
332 start : sequence[float], default: (0.0, 0.0, 0.0)
333 Start location in ``[x, y, z]``.
334
335 direction : sequence[float], default: (1.0, 0.0, 0.0)
336 Direction the arrow points to in ``[x, y, z]``.
337
338 tip_length : float, default: 0.25
339 Length of the tip.
340
341 tip_radius : float, default: 0.1
342 Radius of the tip.
343
344 tip_resolution : int, default: 20
345 Number of faces around the tip.
346
347 shaft_radius : float, default: 0.05
348 Radius of the shaft.
349
350 shaft_resolution : int, default: 20
351 Number of faces around the shaft.
352
353 scale : float | str, optional
354 Scale factor of the entire object, defaults to a scale of 1.
355 ``'auto'`` scales to length of direction array.
356
357 Returns
358 -------
359 pyvista.PolyData
360 Arrow mesh.
361
362 Examples
363 --------
364 Plot a default arrow.
365
366 >>> import pyvista as pv
367 >>> mesh = pv.Arrow()
368 >>> mesh.plot(show_edges=True)
369
370 """
371 arrow = ArrowSource(
372 tip_length=tip_length,
373 tip_radius=tip_radius,
374 tip_resolution=tip_resolution,
375 shaft_radius=shaft_radius,
376 shaft_resolution=shaft_resolution,
377 )
378 surf = arrow.output
379
380 if scale == 'auto':
381 scale = float(np.linalg.norm(direction))
382 if isinstance(scale, (float, int)):
383 surf.points *= scale
384 elif scale is not None:
385 msg = "Scale must be either float, int or 'auto'." # type: ignore[unreachable]
386 raise TypeError(msg)
387
388 translate(surf, start, direction)
389 return surf
390
391
392 @_deprecate_positional_args
393 def Sphere( # noqa: PLR0917
394 radius: float = 0.5,
395 center: VectorLike[float] = (0.0, 0.0, 0.0),
396 direction: VectorLike[float] = (0.0, 0.0, 1.0),
397 theta_resolution: int = 30,
398 phi_resolution: int = 30,
399 start_theta: float = 0.0,
400 end_theta: float = 360.0,
401 start_phi: float = 0.0,
402 end_phi: float = 180.0,
403 ) -> PolyData:
404 """Create a sphere.
405
406 A sphere describes a 2D surface in comparison to
407 :func:`pyvista.SolidSphere`, which fills a 3D volume.
408
409 PyVista uses a convention where ``theta`` represents the azimuthal
410 angle (similar to degrees longitude on the globe) and ``phi``
411 represents the polar angle (similar to degrees latitude on the
412 globe). In contrast to latitude on the globe, here
413 ``phi`` is 0 degrees at the North Pole and 180 degrees at the South
414 Pole. ``phi=0`` is on the positive z-axis by default.
415 ``theta=0`` is on the positive x-axis by default.
416
417 See :ref:`create_sphere_example` for examples on creating spheres in
418 other ways.
419
420 Parameters
421 ----------
422 radius : float, default: 0.5
423 Sphere radius.
424
425 center : sequence[float], default: (0.0, 0.0, 0.0)
426 Center coordinate vector in ``[x, y, z]``.
427
428 direction : sequence[float], default: (0.0, 0.0, 1.0)
429 Direction coordinate vector in ``[x, y, z]`` pointing from ``center`` to
430 the sphere's north pole at zero degrees ``phi``.
431
432 theta_resolution : int, default: 30
433 Set the number of points in the azimuthal direction (ranging
434 from ``start_theta`` to ``end_theta``).
435
436 phi_resolution : int, default: 30
437 Set the number of points in the polar direction (ranging from
438 ``start_phi`` to ``end_phi``).
439
440 start_theta : float, default: 0.0
441 Starting azimuthal angle in degrees ``[0, 360]``.
442
443 end_theta : float, default: 360.0
444 Ending azimuthal angle in degrees ``[0, 360]``.
445
446 start_phi : float, default: 0.0
447 Starting polar angle in degrees ``[0, 180]``.
448
449 end_phi : float, default: 180.0
450 Ending polar angle in degrees ``[0, 180]``.
451
452 Returns
453 -------
454 pyvista.PolyData
455 Sphere mesh.
456
457 See Also
458 --------
459 pyvista.Icosphere : Sphere created from projection of icosahedron.
460 pyvista.SolidSphere : Sphere that fills 3D space.
461 :ref:`sphere_eversion_example` : Example turning a sphere inside-out.
462
463 Examples
464 --------
465 Create a sphere using default parameters.
466
467 >>> import pyvista as pv
468 >>> sphere = pv.Sphere()
469 >>> sphere.plot(show_edges=True)
470
471 Create a quarter sphere by setting ``end_theta``.
472
473 >>> sphere = pv.Sphere(end_theta=90)
474 >>> out = sphere.plot(show_edges=True)
475
476 Create a hemisphere by setting ``end_phi``.
477
478 >>> sphere = pv.Sphere(end_phi=90)
479 >>> out = sphere.plot(show_edges=True)
480
481 """
482 sphere = SphereSource(
483 radius=radius,
484 theta_resolution=theta_resolution,
485 phi_resolution=phi_resolution,
486 start_theta=start_theta,
487 end_theta=end_theta,
488 start_phi=start_phi,
489 end_phi=end_phi,
490 )
491 surf = sphere.output
492 surf.rotate_y(90, inplace=True)
493 translate(surf, center, direction)
494 return surf
495
496
497 @_deprecate_positional_args
498 def SolidSphere( # noqa: PLR0917
499 outer_radius: float = 0.5,
500 inner_radius: float = 0.0,
501 radius_resolution: int = 5,
502 start_theta: float = 0.0,
503 end_theta: float | None = None,
504 theta_resolution: int = 30,
505 start_phi: float = 0.0,
506 end_phi: float | None = None,
507 phi_resolution: int = 30,
508 center: VectorLike[float] = (0.0, 0.0, 0.0),
509 direction: VectorLike[float] = (0.0, 0.0, 1.0),
510 radians: bool = False, # noqa: FBT001, FBT002
511 tol_radius: float = 1.0e-8,
512 tol_angle: float | None = None,
513 ) -> UnstructuredGrid:
514 """Create a solid sphere.
515
516 A solid sphere fills space in 3D in comparison to
517 :func:`pyvista.Sphere`, which is a 2D surface.
518
519 This function uses a linear sampling of each spherical
520 coordinate, whereas :func:`pyvista.SolidSphereGeneric`
521 allows for nonuniform sampling. Angles are by default
522 specified in degrees.
523
524 PyVista uses a convention where ``theta`` represents the azimuthal
525 angle (similar to degrees longitude on the globe) and ``phi``
526 represents the polar angle (similar to degrees latitude on the
527 globe). In contrast to latitude on the globe, here
528 ``phi`` is 0 degrees at the North Pole and 180 degrees at the South
529 Pole. ``phi=0`` is on the positive z-axis by default.
530 ``theta=0`` is on the positive x-axis by default.
531
532 While values for theta can be any value with a maximum span of
533 360 degrees, large magnitudes may result in problems with endpoint
534 overlap detection.
535
536 Parameters
537 ----------
538 outer_radius : float, default: 0.5
539 Outer radius of sphere. Must be non-negative.
540
541 inner_radius : float, default: 0.0
542 Inner radius of sphere. Must be non-negative
543 and smaller than ``outer_radius``.
544
545 radius_resolution : int, default: 5
546 Number of points in radial direction.
547
548 start_theta : float, default: 0.0
549 Starting azimuthal angle.
550
551 end_theta : float, default: 360.0
552 Ending azimuthal angle.
553 ``end_theta`` must be greater than ``start_theta``.
554
555 theta_resolution : int, default: 30
556 Number of points in ``theta`` direction.
557
558 start_phi : float, default: 0.0
559 Starting polar angle.
560 ``phi`` must lie between 0 and 180 in degrees.
561
562 end_phi : float, default: 180.0
563 Ending polar angle.
564 ``phi`` must lie between 0 and 180 in degrees.
565 ``end_phi`` must be greater than ``start_phi``.
566
567 phi_resolution : int, default: 30
568 Number of points in ``phi`` direction,
569 inclusive of polar axis, i.e. ``phi=0`` and ``phi=180``
570 in degrees, if applicable.
571
572 center : sequence[float], default: (0.0, 0.0, 0.0)
573 Center coordinate vector in ``[x, y, z]``.
574
575 direction : sequence[float], default: (0.0, 0.0, 1.0)
576 Direction coordinate vector in ``[x, y, z]`` pointing from ``center`` to
577 the sphere's north pole at zero degrees ``phi``.
578
579 radians : bool, default: False
580 Whether to use radians for ``theta`` and ``phi``. Default is degrees.
581
582 tol_radius : float, default: 1.0e-8
583 Absolute tolerance for endpoint detection for ``radius``.
584
585 tol_angle : float, optional
586 Absolute tolerance for endpoint detection
587 for ``phi`` and ``theta``. Unit is determined by choice
588 of ``radians`` parameter. Default is 1.0e-8 degrees or
589 1.0e-8 degrees converted to radians.
590
591 Returns
592 -------
593 pyvista.UnstructuredGrid
594 Solid sphere mesh.
595
596 See Also
597 --------
598 pyvista.Sphere: Sphere that describes outer 2D surface.
599 pyvista.SolidSphereGeneric: Uses more flexible parameter definition.
600
601 Examples
602 --------
603 Create a solid sphere.
604
605 >>> import pyvista as pv
606 >>> import numpy as np
607 >>> solid_sphere = pv.SolidSphere()
608 >>> solid_sphere.plot(show_edges=True)
609
610 A solid sphere is 3D in comparison to the 2d :func:`pyvista.Sphere`.
611 Generate a solid hemisphere to see the internal structure.
612
613 >>> isinstance(solid_sphere, pv.UnstructuredGrid)
614 True
615 >>> partial_solid_sphere = pv.SolidSphere(start_theta=180, end_theta=360)
616 >>> partial_solid_sphere.plot(show_edges=True)
617
618 To see the cell structure inside the solid sphere,
619 only 1/4 of the sphere is generated. The cells are exploded
620 and colored by radial position.
621
622 >>> partial_solid_sphere = pv.SolidSphere(
623 ... start_theta=180,
624 ... end_theta=360,
625 ... start_phi=0,
626 ... end_phi=90,
627 ... radius_resolution=5,
628 ... theta_resolution=8,
629 ... phi_resolution=8,
630 ... )
631 >>> partial_solid_sphere['cell_radial_pos'] = np.linalg.norm(
632 ... partial_solid_sphere.cell_centers().points, axis=-1
633 ... )
634 >>> partial_solid_sphere.explode(1).plot()
635
636 """
637 if end_theta is None:
638 end_theta = 2 * np.pi if radians else 360.0
639 if end_phi is None:
640 end_phi = np.pi if radians else 180.0
641
642 radius = np.linspace(inner_radius, outer_radius, radius_resolution)
643 theta = np.linspace(start_theta, end_theta, theta_resolution)
644 phi = np.linspace(start_phi, end_phi, phi_resolution)
645 return SolidSphereGeneric(
646 radius=radius,
647 theta=theta,
648 phi=phi,
649 center=center,
650 direction=direction,
651 radians=radians,
652 tol_radius=tol_radius,
653 tol_angle=tol_angle,
654 )
655
656
657 @_deprecate_positional_args
658 def SolidSphereGeneric( # noqa: PLR0917
659 radius: VectorLike[float] | None = None,
660 theta: VectorLike[float] | None = None,
661 phi: VectorLike[float] | None = None,
662 center: VectorLike[float] = (0.0, 0.0, 0.0),
663 direction: VectorLike[float] = (0.0, 0.0, 1.0),
664 radians: bool = False, # noqa: FBT001, FBT002
665 tol_radius: float = 1.0e-8,
666 tol_angle: float | None = None,
667 ) -> UnstructuredGrid:
668 """Create a solid sphere with flexible sampling.
669
670 A solid sphere fills space in 3D in comparison to
671 :func:`pyvista.Sphere`, which is a 2D surface.
672
673 This function allows user defined sampling of each spherical
674 coordinate, whereas :func:`pyvista.SolidSphere`
675 only allows linear sampling. Angles are by default
676 specified in degrees.
677
678 PyVista uses a convention where ``theta`` represents the azimuthal
679 angle (similar to degrees longitude on the globe) and ``phi``
680 represents the polar angle (similar to degrees latitude on the
681 globe). In contrast to latitude on the globe, here
682 ``phi`` is 0 degrees at the North Pole and 180 degrees at the South
683 Pole. ``phi=0`` is on the positive z-axis by default.
684 ``theta=0`` is on the positive x-axis by default.
685
686 Parameters
687 ----------
688 radius : sequence[float], optional
689 A monotonically increasing sequence of values specifying radial
690 points. Must have at least two points and be non-negative.
691
692 theta : sequence[float], optional
693 A monotonically increasing sequence of values specifying ``theta``
694 points. Must have at least two points. Can have any value as long
695 as range is within 360 degrees. Large magnitudes may result in
696 problems with endpoint overlap detection.
697
698 phi : sequence[float], optional
699 A monotonically increasing sequence of values specifying ``phi``
700 points. Must have at least two points. Must be between
701 0 and 180 degrees.
702
703 center : sequence[float], default: (0.0, 0.0, 0.0)
704 Center coordinate vector in ``[x, y, z]``.
705
706 direction : sequence[float], default: (0.0, 0.0, 1.0)
707 Direction coordinate vector in ``[x, y, z]`` pointing from ``center`` to
708 the sphere's north pole at zero degrees ``phi``.
709
710 radians : bool, default: False
711 Whether to use radians for ``theta`` and ``phi``. Default is degrees.
712
713 tol_radius : float, default: 1.0e-8
714 Absolute tolerance for endpoint detection for ``radius``.
715
716 tol_angle : float, optional
717 Absolute tolerance for endpoint detection
718 for ``phi`` and ``theta``. Unit is determined by choice
719 of ``radians`` parameter. Default is 1.0e-8 degrees or
720 1.0e-8 degrees converted to radians.
721
722 Returns
723 -------
724 pyvista.UnstructuredGrid
725 Solid sphere mesh.
726
727 See Also
728 --------
729 pyvista.SolidSphere: Sphere creation using linear sampling.
730 pyvista.Sphere: Sphere that describes outer 2D surface.
731
732 Examples
733 --------
734 Linearly sampling spherical coordinates does not lead to
735 cells of all the same size at each radial position.
736 Cells near the poles have smaller sizes.
737
738 >>> import pyvista as pv
739 >>> import numpy as np
740 >>> solid_sphere = pv.SolidSphereGeneric(
741 ... radius=np.linspace(0, 0.5, 2),
742 ... theta=np.linspace(180, 360, 30),
743 ... phi=np.linspace(0, 180, 30),
744 ... )
745 >>> solid_sphere = solid_sphere.compute_cell_sizes()
746 >>> solid_sphere.plot(scalars='Volume', show_edges=True, clim=[3e-5, 5e-4])
747
748 Sampling the polar angle in a nonlinear manner allows for consistent cell volumes. See
749 `Sphere Point Picking <https://mathworld.wolfram.com/SpherePointPicking.html>`_.
750
751 >>> phi = np.rad2deg(np.arccos(np.linspace(1, -1, 30)))
752 >>> solid_sphere = pv.SolidSphereGeneric(
753 ... radius=np.linspace(0, 0.5, 2),
754 ... theta=np.linspace(180, 360, 30),
755 ... phi=phi,
756 ... )
757 >>> solid_sphere = solid_sphere.compute_cell_sizes()
758 >>> solid_sphere.plot(scalars='Volume', show_edges=True, clim=[3e-5, 5e-4])
759
760 """
761 if radius is None:
762 radius = np.linspace(0, 0.5, 5)
763 radius = np.asanyarray(radius)
764
765 # Default tolerance from user is set in degrees
766 # But code is in radians.
767 if tol_angle is None:
768 tol_angle_ = np.deg2rad(1e-8)
769 else:
770 tol_angle_ = tol_angle if radians else np.deg2rad(tol_angle)
771
772 if theta is None:
773 theta = np.linspace(0, 2 * np.pi, 30)
774 else:
775 theta = np.asanyarray(theta) if radians else np.deg2rad(theta)
776
777 if phi is None:
778 phi = np.linspace(0, np.pi, 30)
779 else:
780 phi = np.asanyarray(phi) if radians else np.deg2rad(phi)
781
782 # Hereafter all degrees are in radians
783 # radius, phi, theta are now np.ndarrays
784
785 nr = len(radius)
786 ntheta = len(theta)
787 nphi = len(phi)
788
789 if nr < 2:
790 msg = 'radius resolution must be 2 or more'
791 raise ValueError(msg)
792 if ntheta < 2:
793 msg = 'theta resolution must be 2 or more'
794 raise ValueError(msg)
795 if nphi < 2:
796 msg = 'phi resolution must be 2 or more'
797 raise ValueError(msg)
798
799 def _is_sorted(a: NumpyArray[float]) -> np.bool_:
800 return np.all(a[:-1] < a[1:])
801
802 if not _is_sorted(radius):
803 msg = 'radius is not monotonically increasing'
804 raise ValueError(msg)
805 if not _is_sorted(theta):
806 msg = 'theta is not monotonically increasing'
807 raise ValueError(msg)
808 if not _is_sorted(phi):
809 msg = 'phi is not monotonically increasing'
810 raise ValueError(msg)
811
812 def _greater_than_equal_or_close(value1: float, value2: float, atol: float) -> bool | np.bool_:
813 return value1 >= value2 or np.isclose(value1, value2, rtol=0.0, atol=atol)
814
815 def _less_than_equal_or_close(value1: float, value2: float, atol: float) -> bool | np.bool_:
816 return value1 <= value2 or np.isclose(value1, value2, rtol=0.0, atol=atol)
817
818 if not _greater_than_equal_or_close(radius[0], 0.0, tol_radius):
819 msg = 'minimum radius cannot be negative'
820 raise ValueError(msg)
821
822 # range of theta cannot be greater than 360 degrees
823 if not _less_than_equal_or_close(theta[-1] - theta[0], 2 * np.pi, tol_angle_):
824 max_angle = '2 * np.pi' if radians else '360 degrees'
825 msg = f'max theta and min theta must be within {max_angle}'
826 raise ValueError(msg)
827
828 if not _greater_than_equal_or_close(phi[0], 0.0, tol_angle_):
829 msg = 'minimum phi cannot be negative'
830 raise ValueError(msg)
831 if not _less_than_equal_or_close(phi[-1], np.pi, tol_angle_):
832 max_angle = 'np.pi' if radians else '180 degrees'
833 msg = f'maximum phi cannot be > {max_angle}'
834 raise ValueError(msg)
835
836 def _spherical_to_cartesian(
837 r: float | VectorLike[float],
838 phi: float | VectorLike[float],
839 theta: float | VectorLike[float],
840 ) -> NumpyArray[float]:
841 """Convert spherical coordinate sequences to a ``(n,3)`` Cartesian coordinate array.
842
843 Parameters
844 ----------
845 r : sequence[float]
846 Ordered sequence of floats of radii.
847 phi : sequence[float]
848 Ordered sequence of floats for phi direction.
849 theta : sequence[float]
850 Ordered sequence of floats for theta direction.
851
852 Returns
853 -------
854 np.ndarray
855 ``(n, 3)`` Cartesian coordinate array.
856
857 """
858 r, phi, theta = np.meshgrid(r, phi, theta, indexing='ij')
859 x, y, z = pv.spherical_to_cartesian(r, phi, theta)
860 return np.vstack((x.ravel(), y.ravel(), z.ravel())).transpose()
861
862 points = []
863
864 npoints_on_axis = 0
865
866 if np.isclose(radius[0], 0.0, rtol=0.0, atol=tol_radius):
867 points.append([0.0, 0.0, 0.0])
868 include_origin = True
869 nr = nr - 1
870 radius = radius[1:]
871 npoints_on_axis += 1
872 else:
873 include_origin = False
874
875 if np.isclose(theta[-1] - theta[0], 2 * np.pi, rtol=0.0, atol=tol_angle_):
876 duplicate_theta = True
877 theta = theta[:-1]
878 else:
879 duplicate_theta = False
880
881 if np.isclose(phi[0], 0.0, rtol=0.0, atol=tol_angle_):
882 points.extend(_spherical_to_cartesian(radius, 0.0, theta[0]))
883 positive_axis = True
884 phi = phi[1:]
885 nphi = nphi - 1
886 npoints_on_axis += nr
887 else:
888 positive_axis = False
889 npoints_on_pos_axis = npoints_on_axis
890
891 if np.isclose(phi[-1], np.pi, rtol=0.0, atol=tol_angle_):
892 points.extend(_spherical_to_cartesian(radius, np.pi, theta[0]))
893 negative_axis = True
894 phi = phi[:-1]
895 nphi = nphi - 1
896 npoints_on_axis += nr
897 else:
898 negative_axis = False
899
900 # rest of points with theta changing quickest
901 for ir, iphi in product(radius, phi):
902 points.extend(_spherical_to_cartesian(ir, iphi, theta))
903
904 cells = []
905 celltypes = []
906
907 def _index(ir: int, iphi: int, itheta: int) -> int:
908 """Index for points not on axis.
909
910 Values of ir and phi here are relative to the first nonaxis values.
911 """
912 if duplicate_theta:
913 ntheta_ = ntheta - 1
914 itheta = itheta % ntheta_
915 else:
916 ntheta_ = ntheta
917
918 return npoints_on_axis + ir * nphi * ntheta_ + iphi * ntheta_ + itheta
919
920 if include_origin:
921 # First make the tetras that form with origin and axis point
922 # origin is 0
923 # first axis point is 1
924 # other points at first phi position off axis
925 if positive_axis:
926 for itheta in range(ntheta - 1):
927 cells.append(4)
928 cells.extend([0, 1, _index(0, 0, itheta), _index(0, 0, itheta + 1)])
929 celltypes.append(pv.CellType.TETRA)
930
931 # Next tetras that form with origin and bottom axis point
932 # origin is 0
933 # axis point is first in negative dir
934 # other points at last phi position off axis
935 if negative_axis:
936 for itheta in range(ntheta - 1):
937 cells.append(4)
938 cells.extend(
939 [
940 0,
941 npoints_on_pos_axis,
942 _index(0, nphi - 1, itheta + 1),
943 _index(0, nphi - 1, itheta),
944 ],
945 )
946 celltypes.append(pv.CellType.TETRA)
947
948 # Pyramids that form to origin but without an axis point
949 for iphi, itheta in product(range(nphi - 1), range(ntheta - 1)):
950 cells.append(5)
951 cells.extend(
952 [
953 _index(0, iphi, itheta),
954 _index(0, iphi, itheta + 1),
955 _index(0, iphi + 1, itheta + 1),
956 _index(0, iphi + 1, itheta),
957 0,
958 ],
959 )
960 celltypes.append(pv.CellType.PYRAMID)
961
962 def _reorder_wedge(points: list[int]) -> list[int]:
963 """Swap points 1,2 and 4,5 for wedge cells."""
964 points[1], points[2] = points[2], points[1]
965 points[4], points[5] = points[5], points[4]
966 return points
967
968 # Wedges form between two r levels at first and last phi position
969 # At each r level, the triangle is formed with axis point, two theta positions
970 # First go upwards
971 if positive_axis:
972 for ir, itheta in product(range(nr - 1), range(ntheta - 1)):
973 axis0 = ir + 1 if include_origin else ir
974 axis1 = ir + 2 if include_origin else ir + 1
975
976 raw_points = [
977 axis0,
978 _index(ir, 0, itheta),
979 _index(ir, 0, itheta + 1),
980 axis1,
981 _index(ir + 1, 0, itheta),
982 _index(ir + 1, 0, itheta + 1),
983 ]
984 if pv.vtk_version_info < (9, 6, 99): # < (9,7,0)
985 raw_points = _reorder_wedge(raw_points)
986
987 cells.append(6)
988 cells.extend(raw_points)
989 celltypes.append(pv.CellType.WEDGE)
990
991 # now go downwards
992 if negative_axis:
993 for ir, itheta in product(range(nr - 1), range(ntheta - 1)):
994 axis0 = npoints_on_pos_axis + ir
995 axis1 = npoints_on_pos_axis + ir + 1
996
997 raw_points = [
998 axis0,
999 _index(ir, nphi - 1, itheta + 1),
1000 _index(ir, nphi - 1, itheta),
1001 axis1,
1002 _index(ir + 1, nphi - 1, itheta + 1),
1003 _index(ir + 1, nphi - 1, itheta),
1004 ]
1005 if pv.vtk_version_info < (9, 6, 99): # < (9,7,0)
1006 raw_points = _reorder_wedge(raw_points)
1007
1008 cells.append(6)
1009 cells.extend(raw_points)
1010 celltypes.append(pv.CellType.WEDGE)
1011
1012 # Form Hexahedra
1013 # Hexahedra form between two r levels and two phi levels and two theta levels
1014 # Order by r levels
1015 for ir, iphi, itheta in product(range(nr - 1), range(nphi - 1), range(ntheta - 1)):
1016 cells.append(8)
1017 cells.extend(
1018 [
1019 _index(ir, iphi, itheta),
1020 _index(ir, iphi + 1, itheta),
1021 _index(ir, iphi + 1, itheta + 1),
1022 _index(ir, iphi, itheta + 1),
1023 _index(ir + 1, iphi, itheta),
1024 _index(ir + 1, iphi + 1, itheta),
1025 _index(ir + 1, iphi + 1, itheta + 1),
1026 _index(ir + 1, iphi, itheta + 1),
1027 ],
1028 )
1029 celltypes.append(pv.CellType.HEXAHEDRON)
1030
1031 mesh = pv.UnstructuredGrid(cells, celltypes, points)
1032 mesh.rotate_y(90, inplace=True)
1033 translate(mesh, center, direction)
1034 return mesh
1035
1036
1037 @_deprecate_positional_args
1038 def Plane( # noqa: PLR0917
1039 center: VectorLike[float] = (0.0, 0.0, 0.0),
1040 direction: VectorLike[float] = (0.0, 0.0, 1.0),
1041 i_size: float = 1.0,
1042 j_size: float = 1.0,
1043 i_resolution: int = 10,
1044 j_resolution: int = 10,
1045 ) -> PolyData:
1046 """Create a plane.
1047
1048 Parameters
1049 ----------
1050 center : sequence[float], default: (0.0, 0.0, 0.0)
1051 Location of the centroid in ``[x, y, z]``.
1052
1053 direction : sequence[float], default: (0.0, 0.0, 1.0)
1054 Direction of the plane's normal in ``[x, y, z]``.
1055
1056 i_size : float, default: 1.0
1057 Size of the plane in the i direction.
1058
1059 j_size : float, default: 1.0
1060 Size of the plane in the j direction.
1061
1062 i_resolution : int, default: 10
1063 Number of points on the plane in the i direction.
1064
1065 j_resolution : int, default: 10
1066 Number of points on the plane in the j direction.
1067
1068 Returns
1069 -------
1070 pyvista.PolyData
1071 Plane mesh.
1072
1073 Examples
1074 --------
1075 Create a default plane.
1076
1077 >>> import pyvista as pv
1078 >>> mesh = pv.Plane()
1079 >>> mesh.point_data.clear()
1080 >>> mesh.plot(show_edges=True)
1081
1082 """
1083 planeSource = PlaneSource(i_resolution=i_resolution, j_resolution=j_resolution)
1084 surf = planeSource.output
1085
1086 surf.points[:, 0] *= i_size
1087 surf.points[:, 1] *= j_size
1088 surf.rotate_y(90, inplace=True)
1089 translate(surf, center, direction)
1090 return surf
1091
1092
1093 @_deprecate_positional_args(allowed=['pointa', 'pointb'])
1094 def Line(
1095 pointa: VectorLike[float] = (-0.5, 0.0, 0.0),
1096 pointb: VectorLike[float] = (0.5, 0.0, 0.0),
1097 resolution: int = 1,
1098 ) -> PolyData:
1099 """Create a line.
1100
1101 Parameters
1102 ----------
1103 pointa : sequence[float], default: (-0.5, 0.0, 0.0)
1104 Location in ``[x, y, z]``.
1105
1106 pointb : sequence[float], default: (0.5, 0.0, 0.0)
1107 Location in ``[x, y, z]``.
1108
1109 resolution : int, default: 1
1110 Number of pieces to divide line into.
1111
1112 Returns
1113 -------
1114 pyvista.PolyData
1115 Line mesh.
1116
1117 Examples
1118 --------
1119 Create a line between ``(0, 0, 0)`` and ``(0, 0, 1)``.
1120
1121 >>> import pyvista as pv
1122 >>> mesh = pv.Line((0, 0, 0), (0, 0, 1))
1123 >>> mesh.plot(color='k', line_width=10)
1124
1125 """
1126 src = LineSource(pointa, pointb, resolution)
1127 line = src.output
1128 # Compute distance of every point along line
1129 compute = lambda p0, p1: np.sqrt(np.sum((p1 - p0) ** 2, axis=1))
1130 distance = compute(np.array(pointa), line.points)
1131 line['Distance'] = distance
1132 return line
1133
1134
1135 def MultipleLines(points: MatrixLike[float] | None = None) -> PolyData:
1136 """Create multiple lines.
1137
1138 Parameters
1139 ----------
1140 points : array_like[float], default: [[-0.5, 0.0, 0.0], [0.5, 0.0, 0.0]]
1141 List of points defining a broken line.
1142
1143 Returns
1144 -------
1145 pyvista.PolyData
1146 Line mesh.
1147
1148 Examples
1149 --------
1150 Create a multiple lines between ``(0, 0, 0)``, ``(1, 1, 1)`` and ``(0, 0, 1)``.
1151
1152 >>> import pyvista as pv
1153 >>> mesh = pv.MultipleLines(points=[[0, 0, 0], [1, 1, 1], [0, 0, 1]])
1154 >>> pl = pv.Plotter()
1155 >>> actor = pl.add_mesh(mesh, color='k', line_width=10)
1156 >>> pl.camera.azimuth = 45
1157 >>> pl.camera.zoom(0.8)
1158 >>> pl.show()
1159
1160 See :ref:`create_multiple_lines_example` and :ref:`color_lines_example`
1161 for more examples.
1162
1163 """
1164 if points is None:
1165 points = [[-0.5, 0.0, 0.0], [0.5, 0.0, 0.0]]
1166 return MultipleLinesSource(points=points).output
1167
1168
1169 @_deprecate_positional_args
1170 def Tube( # noqa: PLR0917
1171 pointa: VectorLike[float] = (-0.5, 0.0, 0.0),
1172 pointb: VectorLike[float] = (0.5, 0.0, 0.0),
1173 resolution: int = 1,
1174 radius: float = 1.0,
1175 n_sides: int = 15,
1176 capping: bool = False, # noqa: FBT001, FBT002
1177 ) -> PolyData:
1178 """Create a tube.
1179
1180 Parameters
1181 ----------
1182 pointa : sequence[float], default: (-0.5, 0.0, 0.0)
1183 Location in ``[x, y, z]``.
1184
1185 pointb : sequence[float], default: (0.5, 0.0, 0.0)
1186 Location in ``[x, y, z]``.
1187
1188 resolution : int, default: 1
1189 Number of pieces to divide tube into.
1190
1191 radius : float, default: 1.0
1192 Minimum tube radius (minimum because the tube radius may vary).
1193
1194 n_sides : int, default: 15
1195 Number of sides for the tube.
1196
1197 capping : bool, default: False
1198 Turn on/off whether to cap the ends with polygons.
1199
1200 .. versionadded:: 0.45
1201
1202 Returns
1203 -------
1204 pyvista.PolyData
1205 Tube mesh.
1206
1207 Examples
1208 --------
1209 Create a tube between ``(0, 0, 0)`` and ``(0, 0, 1)``.
1210
1211 >>> import pyvista as pv
1212 >>> mesh = pv.Tube(pointa=(0, 0, 0), pointb=(0, 0, 1))
1213 >>> mesh.plot()
1214
1215 """
1216 line_src = LineSource(pointa, pointb, resolution)
1217 return line_src.output.tube(radius=radius, n_sides=n_sides, capping=capping)
1218
1219
1220 @_deprecate_positional_args
1221 def Cube( # noqa: PLR0917
1222 center: VectorLike[float] = (0.0, 0.0, 0.0),
1223 x_length: float = 1.0,
1224 y_length: float = 1.0,
1225 z_length: float = 1.0,
1226 bounds: VectorLike[float] | None = None,
1227 clean: bool = True, # noqa: FBT001, FBT002
1228 point_dtype: str = 'float32',
1229 ) -> PolyData:
1230 """Create a cube.
1231
1232 It's possible to specify either the center and side lengths or
1233 just the bounds of the cube. If ``bounds`` are given, all other
1234 arguments are ignored.
1235
1236 .. versionchanged:: 0.33.0
1237 The cube is created using :vtk:`vtkCubeSource`. For
1238 compatibility with :func:`pyvista.PlatonicSolid`, face indices
1239 are also added as cell data. For full compatibility with
1240 :func:`~pyvista.PlatonicSolid`, one has to
1241 use ``x_length = y_length = z_length = 2 * radius / 3**0.5``.
1242 The cube points are also cleaned by default now, leaving only
1243 the 8 corners and a watertight (manifold) mesh.
1244
1245 Parameters
1246 ----------
1247 center : sequence[float], default: (0.0, 0.0, 0.0)
1248 Center in ``[x, y, z]``.
1249
1250 x_length : float, default: 1.0
1251 Length of the cube in the x-direction.
1252
1253 y_length : float, default: 1.0
1254 Length of the cube in the y-direction.
1255
1256 z_length : float, default: 1.0
1257 Length of the cube in the z-direction.
1258
1259 bounds : sequence[float], optional
1260 Specify the bounding box of the cube. If given, all other size
1261 arguments are ignored. ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
1262
1263 clean : bool, default: True
1264 Whether to clean the raw points of the mesh, making the cube
1265 manifold. Note that this will degrade the texture coordinates
1266 that come with the mesh, so if you plan to map a texture on
1267 the cube, consider setting this to ``False``.
1268
1269 .. versionadded:: 0.33.0
1270
1271 point_dtype : str, default: 'float32'
1272 Set the desired output point types. It must be either 'float32' or 'float64'.
1273
1274 .. versionadded:: 0.44.0
1275
1276 Returns
1277 -------
1278 pyvista.PolyData
1279 Mesh of the cube.
1280
1281 Examples
1282 --------
1283 Create a default cube.
1284
1285 >>> import pyvista as pv
1286 >>> mesh = pv.Cube()
1287 >>> mesh.plot(show_edges=True, line_width=5)
1288
1289 """
1290 algo = CubeSource(
1291 center=center,
1292 x_length=x_length,
1293 y_length=y_length,
1294 z_length=z_length,
1295 bounds=bounds,
1296 point_dtype=point_dtype,
1297 )
1298 cube = algo.output
1299
1300 # add face index data for compatibility with PlatonicSolid
1301 # but make it inactive for backwards compatibility
1302 cube.cell_data.set_array([1, 4, 0, 3, 5, 2], 'FaceIndex')
1303
1304 # clean duplicate points
1305 if clean:
1306 cube.clean(inplace=True)
1307
1308 # Fix incorrect default point normals
1309 del cube.point_data['Normals']
1310 cube = cube.compute_normals(point_normals=True, cell_normals=False)
1311
1312 return cube
1313
1314
1315 @_deprecate_positional_args(allowed=['bounds'])
1316 def Box(
1317 bounds: VectorLike[float] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
1318 level: int | VectorLike[int] = 0,
1319 quads: bool = True, # noqa: FBT001, FBT002
1320 ) -> PolyData:
1321 """Create a box with solid faces for the given bounds.
1322
1323 Parameters
1324 ----------
1325 bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
1326 Specify the bounding box of the cube.
1327 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
1328
1329 level : int | VectorLike[int], default: 0
1330 Level of subdivision of the faces.
1331
1332 .. note::
1333 The algorithm is not optimized when a 3 length vector is given.
1334
1335 .. versionadded:: 0.47
1336 Enable specifying different values for x, y and z directions.
1337
1338 quads : bool, default: True
1339 Flag to tell the source to generate either a quad or two
1340 triangle for a set of four points.
1341
1342 Returns
1343 -------
1344 pyvista.PolyData
1345 Mesh of the box.
1346
1347 Examples
1348 --------
1349 Create a box with subdivision ``level=2``.
1350
1351 >>> import pyvista as pv
1352 >>> mesh = pv.Box(level=2)
1353 >>> mesh.plot(show_edges=True)
1354
1355 Set the level separately for each axis.
1356
1357 >>> mesh = pv.Box(level=[1, 2, 3])
1358 >>> mesh.plot(show_edges=True)
1359
1360 """
1361 level_vector = _validation.validate_array3(level, broadcast=True, dtype_out=int, name='level')
1362 if np.all(level_vector == level_vector[0]):
1363 return BoxSource(level=level_vector[0], quads=quads, bounds=bounds).output
1364
1365 mesh = pv.ImageData(dimensions=level_vector + 2)
1366 mesh = mesh.extract_surface(algorithm=None, pass_pointid=False, pass_cellid=False).resize(
1367 bounds=bounds
1368 )
1369 if not quads:
1370 mesh = mesh.triangulate()
1371 return mesh
1372
1373
1374 @_deprecate_positional_args
1375 def Cone( # noqa: PLR0917
1376 center: VectorLike[float] = (0.0, 0.0, 0.0),
1377 direction: VectorLike[float] = (1.0, 0.0, 0.0),
1378 height: float = 1.0,
1379 radius: float | None = None,
1380 capping: bool = True, # noqa: FBT001, FBT002
1381 angle: float | None = None,
1382 resolution: int = 6,
1383 ) -> PolyData:
1384 """Create a cone.
1385
1386 Parameters
1387 ----------
1388 center : sequence[float], default: (0.0, 0.0, 0.0)
1389 Center in ``[x, y, z]``. Axis of the cone passes through this
1390 point.
1391
1392 direction : sequence[float], default: (1.0, 0.0, 0.0)
1393 Direction vector in ``[x, y, z]``. Orientation vector of the
1394 cone.
1395
1396 height : float, default: 1.0
1397 Height along the cone in its specified direction.
1398
1399 radius : float, optional
1400 Base radius of the cone.
1401
1402 capping : bool, optional
1403 Enable or disable the capping the base of the cone with a
1404 polygon.
1405
1406 angle : float, optional
1407 The angle in degrees between the axis of the cone and a
1408 generatrix.
1409
1410 resolution : int, default: 6
1411 Number of facets used to represent the cone.
1412
1413 Returns
1414 -------
1415 pyvista.PolyData
1416 Cone mesh.
1417
1418 Examples
1419 --------
1420 Create a default Cone.
1421
1422 >>> import pyvista as pv
1423 >>> mesh = pv.Cone()
1424 >>> mesh.plot(show_edges=True, line_width=5)
1425
1426 """
1427 algo = ConeSource(
1428 capping=capping,
1429 direction=direction,
1430 center=center,
1431 height=height,
1432 angle=angle,
1433 radius=radius,
1434 resolution=resolution,
1435 )
1436 return algo.output
1437
1438
1439 @_deprecate_positional_args
1440 def Polygon( # noqa: PLR0917
1441 center: VectorLike[float] = (0.0, 0.0, 0.0),
1442 radius: float = 1.0,
1443 normal: VectorLike[float] = (0.0, 0.0, 1.0),
1444 n_sides: int = 6,
1445 fill: bool = True, # noqa: FBT001, FBT002
1446 ) -> PolyData:
1447 """Create a polygon.
1448
1449 Parameters
1450 ----------
1451 center : sequence[float], default: (0.0, 0.0, 0.0)
1452 Center in ``[x, y, z]``. Central axis of the polygon passes
1453 through this point.
1454
1455 radius : float, default: 1.0
1456 The radius of the polygon.
1457
1458 normal : sequence[float], default: (0.0, 0.0, 1.0)
1459 Direction vector in ``[x, y, z]``. Orientation vector of the polygon.
1460
1461 n_sides : int, default: 6
1462 Number of sides of the polygon.
1463
1464 fill : bool, default: True
1465 Enable or disable producing filled polygons.
1466
1467 Returns
1468 -------
1469 pyvista.PolyData
1470 Mesh of the polygon.
1471
1472 Examples
1473 --------
1474 Create an 8 sided polygon.
1475
1476 >>> import pyvista as pv
1477 >>> mesh = pv.Polygon(n_sides=8)
1478 >>> mesh.plot(show_edges=True, line_width=5)
1479
1480 """
1481 src = PolygonSource(fill=fill, center=center, n_sides=n_sides, radius=radius, normal=normal)
1482 return src.output
1483
1484
1485 @_deprecate_positional_args
1486 def Disc( # noqa: PLR0917
1487 center: VectorLike[float] = (0.0, 0.0, 0.0),
1488 inner: float = 0.25,
1489 outer: float = 0.5,
1490 normal: VectorLike[float] = (0.0, 0.0, 1.0),
1491 r_res: int = 1,
1492 c_res: int = 6,
1493 ) -> PolyData:
1494 """Create a polygonal disk with a hole in the center.
1495
1496 The disk has zero height. The user can specify the inner and outer
1497 radius of the disk, and the radial and circumferential resolution
1498 of the polygonal representation.
1499
1500 Parameters
1501 ----------
1502 center : sequence[float], default: (0.0, 0.0, 0.0)
1503 Center in ``[x, y, z]``. Middle of the axis of the disc.
1504
1505 inner : float, default: 0.25
1506 The inner radius.
1507
1508 outer : float, default: 0.5
1509 The outer radius.
1510
1511 normal : sequence[float], default: (0.0, 0.0, 1.0)
1512 Direction vector in ``[x, y, z]``. Orientation vector of the disc.
1513
1514 r_res : int, default: 1
1515 Number of points in radial direction.
1516
1517 c_res : int, default: 6
1518 Number of points in circumferential direction.
1519
1520 Returns
1521 -------
1522 pyvista.PolyData
1523 Disk mesh.
1524
1525 Examples
1526 --------
1527 Create a disc with 50 points in the circumferential direction.
1528
1529 >>> import pyvista as pv
1530 >>> mesh = pv.Disc(c_res=50)
1531 >>> mesh.plot(show_edges=True, line_width=5)
1532
1533 """
1534 algo = DiscSource(inner=inner, outer=outer, r_res=r_res, c_res=c_res)
1535 normal = np.array(normal)
1536 center = np.array(center)
1537 surf = algo.output
1538 surf.rotate_y(90, inplace=True)
1539 translate(surf, center, normal)
1540 return surf
1541
1542
1543 @_deprecate_positional_args(allowed=['string'])
1544 def Text3D( # noqa: PLR0917
1545 string: str,
1546 depth: float | None = None,
1547 width: float | None = None,
1548 height: float | None = None,
1549 center: VectorLike[float] = (0.0, 0.0, 0.0),
1550 normal: VectorLike[float] = (0.0, 0.0, 1.0),
1551 ) -> PolyData:
1552 """Create 3D text from a string.
1553
1554 The text may be configured to have a specified width, height or depth.
1555
1556 Parameters
1557 ----------
1558 string : str
1559 String to generate 3D text from. If ``None`` or an empty string,
1560 the output mesh will have a single point at ``center``.
1561
1562 depth : float, optional
1563 Depth of the text. If ``None``, the depth is set to half
1564 the ``height`` by default. Set to ``0.0`` for planar
1565 text.
1566
1567 .. versionchanged:: 0.43
1568
1569 The default depth is now calculated dynamically as
1570 half the height. Previously, the default depth had
1571 a fixed value of ``0.5``.
1572
1573 width : float, optional
1574 Width of the text. If ``None``, the width is scaled
1575 proportional to ``height``.
1576
1577 .. versionadded:: 0.43
1578
1579 height : float, optional
1580 Height of the text. If ``None``, the height is scaled
1581 proportional to ``width``.
1582
1583 .. versionadded:: 0.43
1584
1585 center : Sequence[float], default: (0.0, 0.0, 0.0)
1586 Center of the text, defined as the middle of the axis-aligned
1587 bounding box of the text.
1588
1589 .. versionadded:: 0.43
1590
1591 normal : Sequence[float], default: (0.0, 0.0, 1.0)
1592 Normal direction of the text. The direction is parallel to the
1593 ``depth`` of the text and points away from the front surface
1594 of the text.
1595
1596 .. versionadded:: 0.43
1597
1598
1599 Returns
1600 -------
1601 pyvista.PolyData
1602 3D text mesh.
1603
1604 Examples
1605 --------
1606 Create 3D text.
1607
1608 >>> import pyvista as pv
1609 >>> text_mesh = pv.Text3D('PyVista')
1610 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1611
1612 Create planar text.
1613
1614 >>> text_mesh = pv.Text3D('PyVista', depth=0)
1615 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1616
1617 Set the depth explicitly.
1618
1619 >>> text_mesh = pv.Text3D('PyVista', depth=5)
1620 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1621
1622 Set the width explicitly. The height and depth are automatically scaled proportionally.
1623
1624 >>> text_mesh = pv.Text3D('PyVista', width=10)
1625 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1626
1627 Set the height explicitly. The width and depth are automatically scaled proportionally.
1628
1629 >>> text_mesh = pv.Text3D('PyVista', height=10)
1630 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1631
1632 Set the height `and` width. The depth is automatically scaled proportional to height.
1633
1634 >>> text_mesh = pv.Text3D('PyVista', height=10, width=10)
1635 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1636
1637 Set the height, width, and depth independently, and adjust the center.
1638
1639 >>> text_mesh = pv.Text3D(
1640 ... 'PyVista', height=10, width=10, depth=0, center=(5, 5, 0)
1641 ... )
1642 >>> text_mesh.plot(cpos='xy', show_bounds=True)
1643
1644 See :ref:`create_text_3d_example` for more examples using this function.
1645
1646 """
1647 return Text3DSource(
1648 string,
1649 width=width,
1650 height=height,
1651 depth=depth,
1652 center=center,
1653 normal=normal,
1654 process_empty_string=True,
1655 ).output
1656
1657
1658 @_deprecate_positional_args
1659 def Wavelet( # noqa: PLR0917
1660 extent: VectorLike[float] = (-10, 10, -10, 10, -10, 10),
1661 center: VectorLike[float] = (0.0, 0.0, 0.0),
1662 maximum: float = 255.0,
1663 x_freq: float = 60.0,
1664 y_freq: float = 30.0,
1665 z_freq: float = 40.0,
1666 x_mag: float = 10.0,
1667 y_mag: float = 18.0,
1668 z_mag: float = 5.0,
1669 std: float = 0.5,
1670 subsample_rate: int = 1,
1671 ) -> ImageData:
1672 """Create a wavelet.
1673
1674 Produces images with pixel values determined by
1675 ``Maximum*Gaussian*x_mag*sin(x_freq*x)*sin(y_freq*y)*cos(z_freq*z)``
1676
1677 Values are float scalars on point data with name ``"RTData"``.
1678
1679 Parameters
1680 ----------
1681 extent : sequence[int], default: (-10, 10, -10, 10, -10, 10)
1682 Set/Get the extent of the whole output image.
1683
1684 center : sequence[float], default: (0.0, 0.0, 0.0)
1685 Center of the wavelet.
1686
1687 maximum : float, default: 255.0
1688 Maximum of the wavelet function.
1689
1690 x_freq : float, default: 60.0
1691 Natural frequency in the x direction.
1692
1693 y_freq : float, default: 30.0
1694 Natural frequency in the y direction.
1695
1696 z_freq : float, default: 40.0
1697 Natural frequency in the z direction.
1698
1699 x_mag : float, default: 10.0
1700 Magnitude in the x direction.
1701
1702 y_mag : float, default: 18.0
1703 Magnitude in the y direction.
1704
1705 z_mag : float, default: 5.0
1706 Magnitude in the z direction.
1707
1708 std : float, default: 0.5
1709 Standard deviation.
1710
1711 subsample_rate : int, default: 1
1712 The sub-sample rate.
1713
1714 Returns
1715 -------
1716 pyvista.ImageData
1717 Wavelet mesh.
1718
1719 Examples
1720 --------
1721 >>> import pyvista as pv
1722 >>> wavelet = pv.Wavelet(
1723 ... extent=(0, 50, 0, 50, 0, 10),
1724 ... x_freq=20,
1725 ... y_freq=10,
1726 ... z_freq=1,
1727 ... x_mag=100,
1728 ... y_mag=100,
1729 ... z_mag=1000,
1730 ... )
1731 >>> wavelet.plot(show_scalar_bar=False)
1732
1733 Extract lower valued cells of the wavelet and create a surface from it.
1734
1735 >>> thresh = wavelet.threshold(800).extract_surface(algorithm=None)
1736 >>> thresh.plot(show_scalar_bar=False)
1737
1738 Smooth it to create "waves"
1739
1740 >>> waves = thresh.smooth(n_iter=100, relaxation_factor=0.1)
1741 >>> waves.plot(color='white', smooth_shading=True, show_edges=True)
1742
1743 """
1744 wavelet_source = _vtk.vtkRTAnalyticSource()
1745 wavelet_source.SetWholeExtent(*extent)
1746 wavelet_source.SetCenter(*center)
1747 wavelet_source.SetMaximum(maximum)
1748 wavelet_source.SetXFreq(x_freq)
1749 wavelet_source.SetYFreq(y_freq)
1750 wavelet_source.SetZFreq(z_freq)
1751 wavelet_source.SetXMag(x_mag)
1752 wavelet_source.SetYMag(y_mag)
1753 wavelet_source.SetZMag(z_mag)
1754 wavelet_source.SetStandardDeviation(std)
1755 wavelet_source.SetSubsampleRate(subsample_rate)
1756 wavelet_source.Update()
1757 return cast('pv.ImageData', wrap(wavelet_source.GetOutput()))
1758
1759
1760 @_deprecate_positional_args
1761 def CircularArc( # noqa: PLR0917
1762 pointa: VectorLike[float],
1763 pointb: VectorLike[float],
1764 center: VectorLike[float],
1765 resolution: int = 100,
1766 negative: bool = False, # noqa: FBT001, FBT002
1767 ) -> PolyData:
1768 """Create a circular arc defined by two endpoints and a center.
1769
1770 The number of segments composing the polyline is controlled by
1771 setting the object resolution.
1772
1773 Parameters
1774 ----------
1775 pointa : sequence[float]
1776 Position of the first end point.
1777
1778 pointb : sequence[float]
1779 Position of the other end point.
1780
1781 center : sequence[float]
1782 Center of the circle that defines the arc.
1783
1784 resolution : int, default: 100
1785 The number of segments of the polyline that draws the arc.
1786 Resolution of 1 will just create a line.
1787
1788 negative : bool, default: False
1789 By default the arc spans the shortest angular sector between
1790 ``pointa`` and ``pointb``.
1791
1792 By setting this to ``True``, the longest angular sector is
1793 used instead (i.e. the negative coterminal angle to the
1794 shortest one).
1795
1796 Returns
1797 -------
1798 pyvista.PolyData
1799 Circular arc mesh.
1800
1801 Examples
1802 --------
1803 Create a quarter arc centered at the origin in the xy plane.
1804
1805 >>> import pyvista as pv
1806 >>> arc = pv.CircularArc(pointa=[-1, 0, 0], pointb=[0, 1, 0], center=[0, 0, 0])
1807 >>> pl = pv.Plotter()
1808 >>> _ = pl.add_mesh(arc, color='k', line_width=10)
1809 >>> _ = pl.show_bounds(location='all', font_size=30, use_2d=True)
1810 >>> _ = pl.view_xy()
1811 >>> pl.show()
1812
1813 See :ref:`create_circular_arc_example` and :ref:`flight_paths_example`
1814 for more examples using this function.
1815
1816 """
1817 check_valid_vector(pointa, 'pointa')
1818 check_valid_vector(pointb, 'pointb')
1819 check_valid_vector(center, 'center')
1820 if not np.isclose(
1821 np.linalg.norm(np.array(pointa) - np.array(center)),
1822 np.linalg.norm(np.array(pointb) - np.array(center)),
1823 ):
1824 msg = 'pointa and pointb are not equidistant from center'
1825 raise ValueError(msg)
1826
1827 # fix half-arc bug: if a half arc travels directly through the
1828 # center point, it becomes a line
1829 pointb = list(pointb)
1830 pointb[0] -= 1e-10
1831 pointb[1] -= 1e-10
1832
1833 arc = _vtk.vtkArcSource()
1834 arc.SetPoint1(*pointa)
1835 arc.SetPoint2(*pointb)
1836 arc.SetCenter(*center)
1837 arc.SetResolution(resolution)
1838 arc.SetNegative(negative)
1839
1840 arc.Update()
1841 angle = np.deg2rad(arc.GetAngle())
1842 arc = wrap(arc.GetOutput()) # type: ignore[assignment]
1843 # Compute distance of every point along circular arc
1844 center = np.array(center).ravel()
1845 radius = np.sqrt(np.sum((arc.points[0] - center) ** 2, axis=0)) # type: ignore[attr-defined]
1846 angles = np.linspace(0.0, 1.0, arc.n_points) * angle # type: ignore[attr-defined]
1847 arc['Distance'] = radius * angles # type: ignore[index]
1848 return cast('pv.PolyData', arc)
1849
1850
1851 @_deprecate_positional_args
1852 def CircularArcFromNormal( # noqa: PLR0917
1853 center: VectorLike[float],
1854 resolution: int = 100,
1855 normal: VectorLike[float] | None = None,
1856 polar: VectorLike[float] | None = None,
1857 angle: float | None = None,
1858 ) -> PolyData:
1859 """Create a circular arc defined by normal to the plane of the arc, and an angle.
1860
1861 The number of segments composing the polyline is controlled by
1862 setting the object resolution.
1863
1864 Parameters
1865 ----------
1866 center : sequence[float]
1867 Center of the circle that defines the arc.
1868
1869 resolution : int, default: 100
1870 The number of segments of the polyline that draws the arc.
1871 Resolution of 1 will just create a line.
1872
1873 normal : sequence[float], optional
1874 The normal vector to the plane of the arc. By default it
1875 points in the positive Z direction.
1876
1877 polar : sequence[float], optional
1878 Starting point of the arc in polar coordinates. By default it
1879 is the unit vector in the positive x direction.
1880
1881 angle : float, optional
1882 Arc length (in degrees) beginning at the polar vector. The
1883 direction is counterclockwise. By default it is 90.
1884
1885 Returns
1886 -------
1887 pyvista.PolyData
1888 Circular arc mesh.
1889
1890 Examples
1891 --------
1892 Quarter arc centered at the origin in the xy plane.
1893
1894 >>> import pyvista as pv
1895 >>> normal = [0, 0, 1]
1896 >>> polar = [-1, 0, 0]
1897 >>> arc = pv.CircularArcFromNormal(
1898 ... center=[0, 0, 0], normal=normal, polar=polar
1899 ... )
1900 >>> pl = pv.Plotter()
1901 >>> _ = pl.add_mesh(arc, color='k', line_width=10)
1902 >>> _ = pl.show_bounds(location='all', font_size=30, use_2d=True)
1903 >>> _ = pl.view_xy()
1904 >>> pl.show()
1905
1906 See :ref:`create_circular_arc_example` for more examples using this function.
1907
1908 """
1909 check_valid_vector(center, 'center')
1910 if normal is None:
1911 normal = [0, 0, 1]
1912 if polar is None:
1913 polar = [1, 0, 0]
1914 angle_ = 90.0 if angle is None else angle
1915
1916 arc = _vtk.vtkArcSource()
1917 arc.SetCenter(*center)
1918 arc.SetResolution(resolution)
1919 arc.UseNormalAndAngleOn()
1920 check_valid_vector(normal, 'normal')
1921 arc.SetNormal(*normal)
1922 check_valid_vector(polar, 'polar')
1923 arc.SetPolarVector(*polar)
1924 arc.SetAngle(angle_)
1925 arc.Update()
1926 angle_ = np.deg2rad(arc.GetAngle())
1927 arc = wrap(arc.GetOutput()) # type: ignore[assignment]
1928 # Compute distance of every point along circular arc
1929 center = np.array(center)
1930 radius = np.sqrt(np.sum((arc.points[0] - center) ** 2, axis=0)) # type: ignore[attr-defined]
1931 angles = np.linspace(0.0, angle_, resolution + 1)
1932 arc['Distance'] = radius * angles # type: ignore[index]
1933 return cast('pv.PolyData', arc)
1934
1935
1936 def Pyramid(points: MatrixLike[float] | None = None) -> UnstructuredGrid:
1937 """Create a pyramid defined by 5 points.
1938
1939 Parameters
1940 ----------
1941 points : array_like[float], optional
1942 Points of the pyramid. Points are ordered such that the first
1943 four points are the four counterclockwise points on the
1944 quadrilateral face, and the last point is the apex.
1945
1946 Defaults to pyramid in example.
1947
1948 Returns
1949 -------
1950 pyvista.UnstructuredGrid
1951 Unstructured grid containing a single pyramid cell.
1952
1953 Examples
1954 --------
1955 >>> import pyvista as pv
1956 >>> pointa = [1.0, 1.0, 0.0]
1957 >>> pointb = [-1.0, 1.0, 0.0]
1958 >>> pointc = [-1.0, -1.0, 0.0]
1959 >>> pointd = [1.0, -1.0, 0.0]
1960 >>> pointe = [0.0, 0.0, 1.608]
1961 >>> pyramid = pv.Pyramid([pointa, pointb, pointc, pointd, pointe])
1962 >>> pyramid.plot(show_edges=True, line_width=5)
1963
1964 """
1965 if points is None:
1966 points = [
1967 [1.0, 1.0, 0.0],
1968 [-1.0, 1.0, 0.0],
1969 [-1.0, -1.0, 0.0],
1970 [1.0, -1.0, 0.0],
1971 [0.0, 0.0, (4 - 2**0.5) ** 0.5],
1972 ]
1973
1974 if len(points) != 5:
1975 msg = 'Points must be given as length 5 np.ndarray or list.'
1976 raise TypeError(msg)
1977
1978 check_valid_vector(points[0], 'points[0]')
1979 check_valid_vector(points[1], 'points[1]')
1980 check_valid_vector(points[2], 'points[2]')
1981 check_valid_vector(points[3], 'points[3]')
1982 check_valid_vector(points[4], 'points[4]')
1983
1984 pyramid = _vtk.vtkPyramid()
1985 pyramid.GetPointIds().SetId(0, 0)
1986 pyramid.GetPointIds().SetId(1, 1)
1987 pyramid.GetPointIds().SetId(2, 2)
1988 pyramid.GetPointIds().SetId(3, 3)
1989 pyramid.GetPointIds().SetId(4, 4)
1990
1991 ug = _vtk.vtkUnstructuredGrid()
1992 ug.SetPoints(pv.vtk_points(np.array(points), deep=False))
1993 ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())
1994
1995 return wrap(ug)
1996
1997
1998 def Triangle(points: MatrixLike[float] | None = None) -> PolyData:
1999 """Create a triangle defined by 3 points.
2000
2001 Parameters
2002 ----------
2003 points : array_like[float], optional
2004 Points of the triangle. Defaults to a right isosceles
2005 triangle (see example).
2006
2007 Returns
2008 -------
2009 pyvista.PolyData
2010 Triangle mesh.
2011
2012 Examples
2013 --------
2014 >>> import pyvista as pv
2015 >>> pointa = [0, 0, 0]
2016 >>> pointb = [1, 0, 0]
2017 >>> pointc = [0.5, 0.707, 0]
2018 >>> triangle = pv.Triangle([pointa, pointb, pointc])
2019 >>> triangle.plot(show_edges=True, line_width=5)
2020
2021 """
2022 if points is None:
2023 points = [[0, 0, 0], [1, 0, 0], [0.5, 0.5**0.5, 0]]
2024
2025 if len(points) != 3:
2026 msg = 'Points must be given as length 3 np.ndarray or list'
2027 raise TypeError(msg)
2028
2029 check_valid_vector(points[0], 'points[0]')
2030 check_valid_vector(points[1], 'points[1]')
2031 check_valid_vector(points[2], 'points[2]')
2032
2033 cells = np.array([[3, 0, 1, 2]])
2034 return wrap(pv.PolyData(points, cells))
2035
2036
2037 def Rectangle(points: MatrixLike[float] | None = None) -> PolyData:
2038 """Create a rectangle defined by 3 points.
2039
2040 The 3 points must define an orthogonal set of vectors.
2041
2042 Parameters
2043 ----------
2044 points : array_like[float], optional
2045 Points of the rectangle. Defaults to a unit square in xy-plane.
2046
2047 Returns
2048 -------
2049 pyvista.PolyData
2050 Rectangle mesh.
2051
2052 Examples
2053 --------
2054 >>> import pyvista as pv
2055 >>> pointa = [1.0, 0.0, 0.0]
2056 >>> pointb = [1.0, 1.0, 0.0]
2057 >>> pointc = [0.0, 1.0, 0.0]
2058 >>> rectangle = pv.Rectangle([pointa, pointb, pointc])
2059 >>> rectangle.plot(show_edges=True, line_width=5)
2060
2061 """
2062 if points is None:
2063 points = [[1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]
2064 if len(points) != 3:
2065 msg = 'Points must be given as length 3 np.ndarray or list'
2066 raise TypeError(msg)
2067
2068 points, _ = _coerce_pointslike_arg(points)
2069
2070 point_0 = points[0]
2071 point_1 = points[1]
2072 point_2 = points[2]
2073
2074 vec_01 = point_1 - point_0
2075 vec_02 = point_2 - point_0
2076 vec_12 = point_2 - point_1
2077
2078 mag_01 = np.linalg.norm(vec_01)
2079 mag_02 = np.linalg.norm(vec_02)
2080 mag_12 = np.linalg.norm(vec_12)
2081
2082 if np.isclose(mag_01, 0) or np.isclose(mag_02, 0) or np.isclose(mag_12, 0):
2083 msg = 'Unable to build a rectangle with less than three different points'
2084 raise ValueError(msg)
2085
2086 scalar_pdct_01_02 = np.dot(vec_01, vec_02) / min(mag_01, mag_02) ** 2
2087 scalar_pdct_01_12 = np.dot(vec_01, vec_12) / min(mag_01, mag_12) ** 2
2088 scalar_pdct_02_12 = np.dot(vec_02, vec_12) / min(mag_02, mag_12) ** 2
2089
2090 null_scalar_products = [
2091 val
2092 for val in [scalar_pdct_01_02, scalar_pdct_01_12, scalar_pdct_02_12]
2093 if np.isclose(val, 0)
2094 ]
2095 if len(null_scalar_products) == 0:
2096 msg = 'The three points should defined orthogonal vectors'
2097 raise ValueError(msg)
2098
2099 points = np.array([point_0, point_1, point_2, point_0])
2100 if np.isclose(scalar_pdct_01_02, 0):
2101 points[3] = point_0 + vec_01 + vec_02
2102 cells = np.array([[4, 0, 1, 3, 2]])
2103 elif np.isclose(scalar_pdct_01_12, 0):
2104 points[3] = point_1 + vec_12 - vec_01
2105 cells = np.array([[4, 0, 1, 2, 3]])
2106 else:
2107 points[3] = point_2 - vec_02 - vec_12
2108 cells = np.array([[4, 0, 2, 1, 3]])
2109
2110 return wrap(pv.PolyData(points, cells))
2111
2112
2113 def Quadrilateral(points: MatrixLike[float] | None = None) -> PolyData:
2114 """Create a quadrilateral defined by 4 points.
2115
2116 Parameters
2117 ----------
2118 points : array_like[float], optional
2119 Points of the quadrilateral. Defaults to a unit square in xy-plane.
2120
2121 Returns
2122 -------
2123 pyvista.PolyData
2124 Quadrilateral mesh.
2125
2126 Examples
2127 --------
2128 >>> import pyvista as pv
2129 >>> pointa = [1.0, 0.0, 0.0]
2130 >>> pointb = [1.0, 1.0, 0.0]
2131 >>> pointc = [0.0, 1.0, 0.0]
2132 >>> pointd = [0.0, 0.0, 0.0]
2133 >>> quadrilateral = pv.Quadrilateral([pointa, pointb, pointc, pointd])
2134 >>> quadrilateral.plot(show_edges=True, line_width=5)
2135
2136 """
2137 if points is None:
2138 points = [[1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]
2139 if len(points) != 4:
2140 msg = 'Points must be given as length 4 np.ndarray or list'
2141 raise TypeError(msg)
2142
2143 points, _ = _coerce_pointslike_arg(points)
2144
2145 cells = np.array([[4, 0, 1, 2, 3]])
2146 return wrap(pv.PolyData(points, cells))
2147
2148
2149 @_deprecate_positional_args
2150 def Circle(radius: float = 0.5, resolution: int = 100) -> PolyData:
2151 """Create a single PolyData circle defined by radius in the XY plane.
2152
2153 Parameters
2154 ----------
2155 radius : float, default: 0.5
2156 Radius of circle.
2157
2158 resolution : int, default: 100
2159 Number of points on the circle.
2160
2161 Returns
2162 -------
2163 pyvista.PolyData
2164 Circle mesh.
2165
2166 Notes
2167 -----
2168 .. versionchanged:: 0.38.0
2169 Prior to version 0.38, this method had incorrect results, producing
2170 inconsistent edge lengths and a duplicated point which is now fixed.
2171
2172 Examples
2173 --------
2174 >>> import pyvista as pv
2175 >>> radius = 0.5
2176 >>> circle = pv.Circle(radius=radius)
2177 >>> circle.plot(show_edges=True, line_width=5)
2178
2179 """
2180 points = np.zeros((resolution, 3))
2181 theta = np.linspace(0.0, 2.0 * np.pi, resolution, endpoint=False)
2182 points[:, 0] = radius * np.cos(theta)
2183 points[:, 1] = radius * np.sin(theta)
2184 cells = np.array([np.append(np.array([resolution]), np.arange(resolution))])
2185 return wrap(pv.PolyData(points, cells))
2186
2187
2188 @_deprecate_positional_args(allowed=['semi_major_axis', 'semi_minor_axis'])
2189 def Ellipse(
2190 semi_major_axis: float = 0.5, semi_minor_axis: float = 0.2, resolution: int = 100
2191 ) -> PolyData:
2192 """Create a single ellipse defined by the Semi-major and Semi-minor axes in the XY plane.
2193
2194 Parameters
2195 ----------
2196 semi_major_axis : float, default: 0.5
2197 Semi-major axis of ellipse.
2198
2199 semi_minor_axis : float, default: 0.2
2200 Semi-minor axis of ellipse.
2201
2202 resolution : int, default: 100
2203 Number of points on the ellipse.
2204
2205 Returns
2206 -------
2207 pyvista.PolyData
2208 Ellipse mesh.
2209
2210 Notes
2211 -----
2212 .. versionchanged:: 0.38.0
2213 Prior to version 0.38, this method had incorrect results, producing
2214 inconsistent edge lengths and a duplicated point which is now fixed.
2215
2216 Examples
2217 --------
2218 >>> import pyvista as pv
2219 >>> ellipse = pv.Ellipse(semi_major_axis=8, semi_minor_axis=4)
2220 >>> ellipse.plot(show_edges=True, line_width=5)
2221
2222 """
2223 points = np.zeros((resolution, 3))
2224 theta = np.linspace(0.0, 2.0 * np.pi, resolution, endpoint=False)
2225 points[:, 0] = semi_major_axis * np.cos(theta)
2226 points[:, 1] = semi_minor_axis * np.sin(theta)
2227 cells = np.array([np.append(np.array([resolution]), np.arange(resolution))])
2228 return wrap(pv.PolyData(points, cells))
2229
2230
2231 @_deprecate_positional_args
2232 def Superquadric( # noqa: PLR0917
2233 center: VectorLike[float] = (0.0, 0.0, 0.0),
2234 scale: VectorLike[float] = (1.0, 1.0, 1.0),
2235 size: float = 0.5,
2236 theta_roundness: float = 1.0,
2237 phi_roundness: float = 1.0,
2238 theta_resolution: int = 16,
2239 phi_resolution: int = 16,
2240 toroidal: bool = False, # noqa: FBT001, FBT002
2241 thickness: float = 1 / 3,
2242 ) -> PolyData:
2243 """Create a superquadric.
2244
2245 Parameters
2246 ----------
2247 center : sequence[float], default: (0.0, 0.0, 0.0)
2248 Center of the superquadric in ``[x, y, z]``.
2249
2250 scale : sequence[float], default: (1.0, 1.0, 1.0)
2251 Scale factors of the superquadric in ``[x, y, z]``.
2252
2253 size : float, default: 0.5
2254 Superquadric isotropic size.
2255
2256 theta_roundness : float, default: 1.0
2257 Superquadric east/west roundness.
2258 Values range from 0 (rectangular) to 1 (circular) to higher orders.
2259
2260 phi_roundness : float, default: 1.0
2261 Superquadric north/south roundness.
2262 Values range from 0 (rectangular) to 1 (circular) to higher orders.
2263
2264 theta_resolution : int, default: 16
2265 Number of points in the longitude direction.
2266 Values are rounded to nearest multiple of 4.
2267
2268 phi_resolution : int, default: 16
2269 Number of points in the latitude direction.
2270 Values are rounded to nearest multiple of 8.
2271
2272 toroidal : bool, default: False
2273 Whether or not the superquadric is toroidal (``True``)
2274 or ellipsoidal (``False``).
2275
2276 thickness : float, default: 0.3333333333
2277 Superquadric ring thickness.
2278 Only applies if toroidal is set to ``True``.
2279
2280 Returns
2281 -------
2282 pyvista.PolyData
2283 Superquadric mesh.
2284
2285 See Also
2286 --------
2287 pyvista.ParametricSuperEllipsoid :
2288 Parametric superquadric if toroidal is ``False``.
2289 pyvista.ParametricSuperToroid :
2290 Parametric superquadric if toroidal is ``True``.
2291
2292 Examples
2293 --------
2294 >>> import pyvista as pv
2295 >>> superquadric = pv.Superquadric(
2296 ... scale=(3.0, 1.0, 0.5),
2297 ... phi_roundness=0.1,
2298 ... theta_roundness=0.5,
2299 ... )
2300 >>> superquadric.plot(show_edges=True)
2301
2302 """
2303 source = SuperquadricSource(
2304 center=center,
2305 scale=scale,
2306 size=size,
2307 theta_roundness=theta_roundness,
2308 phi_roundness=phi_roundness,
2309 theta_resolution=theta_resolution,
2310 phi_resolution=phi_resolution,
2311 toroidal=toroidal,
2312 thickness=thickness,
2313 )
2314 return source.output
2315
2316
2317 @_deprecate_positional_args(allowed=['kind'])
2318 def PlatonicSolid(
2319 kind: str = 'tetrahedron', radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0)
2320 ) -> PolyData:
2321 """Create a Platonic solid of a given size.
2322
2323 Parameters
2324 ----------
2325 kind : str | int, default: 'tetrahedron'
2326 The kind of Platonic solid to create. Either the name of the
2327 polyhedron or an integer index:
2328
2329 * ``'tetrahedron'`` or ``0``
2330 * ``'cube'`` or ``1``
2331 * ``'octahedron'`` or ``2``
2332 * ``'icosahedron'`` or ``3``
2333 * ``'dodecahedron'`` or ``4``
2334
2335 radius : float, default: 1.0
2336 The radius of the circumscribed sphere for the solid to create.
2337
2338 center : sequence[float], default: (0.0, 0.0, 0.0)
2339 Sequence defining the center of the solid to create.
2340
2341 Returns
2342 -------
2343 pyvista.PolyData
2344 One of the five Platonic solids. Cell scalars are defined that
2345 assign integer labels to each face (with array name
2346 ``"FaceIndex"``).
2347
2348 Examples
2349 --------
2350 Create and plot a dodecahedron.
2351
2352 >>> import pyvista as pv
2353 >>> dodeca = pv.PlatonicSolid('dodecahedron')
2354 >>> dodeca.plot(categories=True)
2355
2356 See :ref:`create_platonic_solids_example` for more examples using this filter.
2357
2358 """
2359 check_valid_vector(center, 'center')
2360
2361 source = PlatonicSolidSource()
2362 source.kind = kind
2363 solid = source.output
2364 # rename and activate cell scalars
2365 cell_data = solid.cell_data.get_array(0)
2366 solid.clear_data()
2367 solid.cell_data['FaceIndex'] = cell_data
2368 # scale and translate
2369 solid.scale(radius, inplace=True)
2370 solid.points += np.asanyarray(center) - solid.center
2371 return solid
2372
2373
2374 def Tetrahedron(radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0)) -> PolyData:
2375 """Create a tetrahedron of a given size.
2376
2377 A tetrahedron is composed of four congruent equilateral triangles.
2378
2379 Parameters
2380 ----------
2381 radius : float, default: 1.0
2382 The radius of the circumscribed sphere for the tetrahedron.
2383
2384 center : sequence[float], default: (0.0, 0.0, 0.0)
2385 Three-length sequence defining the center of the tetrahedron.
2386
2387 Returns
2388 -------
2389 pyvista.PolyData
2390 Mesh for the tetrahedron. Cell scalars are defined that assign
2391 integer labels to each face (with array name ``"FaceIndex"``).
2392
2393 Examples
2394 --------
2395 Create and plot a tetrahedron.
2396
2397 >>> import pyvista as pv
2398 >>> tetra = pv.Tetrahedron()
2399 >>> tetra.plot(categories=True)
2400
2401 See :ref:`create_platonic_solids_example` for more examples using this filter.
2402
2403 """
2404 return PlatonicSolid(kind='tetrahedron', radius=radius, center=center)
2405
2406
2407 def Octahedron(radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0)) -> PolyData:
2408 """Create an octahedron of a given size.
2409
2410 An octahedron is composed of eight congruent equilateral
2411 triangles.
2412
2413 Parameters
2414 ----------
2415 radius : float, default: 1.0
2416 The radius of the circumscribed sphere for the octahedron.
2417
2418 center : sequence[float], default: (0.0, 0.0, 0.0)
2419 Three-length sequence defining the center of the octahedron.
2420
2421 Returns
2422 -------
2423 pyvista.PolyData
2424 Mesh for the octahedron. Cell scalars are defined that assign
2425 integer labels to each face (with array name ``"FaceIndex"``).
2426
2427 Examples
2428 --------
2429 Create and plot an octahedron.
2430
2431 >>> import pyvista as pv
2432 >>> tetra = pv.Octahedron()
2433 >>> tetra.plot(categories=True)
2434
2435 See :ref:`create_platonic_solids_example` for more examples using this filter.
2436
2437 """
2438 return PlatonicSolid(kind='octahedron', radius=radius, center=center)
2439
2440
2441 def Dodecahedron(radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0)) -> PolyData:
2442 """Create a dodecahedron of a given size.
2443
2444 A dodecahedron is composed of twelve congruent regular pentagons.
2445
2446 Parameters
2447 ----------
2448 radius : float, default: 1.0
2449 The radius of the circumscribed sphere for the dodecahedron.
2450
2451 center : sequence[float], default: (0.0, 0.0, 0.0)
2452 Three-length sequence defining the center of the dodecahedron.
2453
2454 Returns
2455 -------
2456 pyvista.PolyData
2457 Mesh for the dodecahedron. Cell scalars are defined that assign
2458 integer labels to each face (with array name ``"FaceIndex"``).
2459
2460 Examples
2461 --------
2462 Create and plot a dodecahedron.
2463
2464 >>> import pyvista as pv
2465 >>> tetra = pv.Dodecahedron()
2466 >>> tetra.plot(categories=True)
2467
2468 See :ref:`create_platonic_solids_example` for more examples using this filter.
2469
2470 """
2471 return PlatonicSolid(kind='dodecahedron', radius=radius, center=center)
2472
2473
2474 def Icosahedron(radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0)) -> PolyData:
2475 """Create an icosahedron of a given size.
2476
2477 An icosahedron is composed of twenty congruent equilateral
2478 triangles.
2479
2480 Parameters
2481 ----------
2482 radius : float, default: 1.0
2483 The radius of the circumscribed sphere for the icosahedron.
2484
2485 center : sequence[float], default: (0.0, 0.0, 0.0)
2486 Three-length sequence defining the center of the icosahedron.
2487
2488 Returns
2489 -------
2490 pyvista.PolyData
2491 Mesh for the icosahedron. Cell scalars are defined that assign
2492 integer labels to each face (with array name ``"FaceIndex"``).
2493
2494 Examples
2495 --------
2496 Create and plot an icosahedron.
2497
2498 >>> import pyvista as pv
2499 >>> tetra = pv.Icosahedron()
2500 >>> tetra.plot(categories=True)
2501
2502 See :ref:`create_platonic_solids_example` for more examples using this filter.
2503
2504 """
2505 return PlatonicSolid(kind='icosahedron', radius=radius, center=center)
2506
2507
2508 def Icosphere(
2509 radius: float = 1.0, center: VectorLike[float] = (0.0, 0.0, 0.0), nsub: int = 3
2510 ) -> PolyData:
2511 """Create an icosphere.
2512
2513 An icosphere is a `geodesic polyhedron
2514 <https://en.wikipedia.org/wiki/Geodesic_polyhedron>`_, which is a
2515 convex polyhedron made from triangles.
2516
2517 Geodesic polyhedra are constructed by subdividing faces of simpler
2518 polyhedra, and then projecting the new vertices onto the surface of
2519 a sphere. A geodesic polyhedron has straight edges and flat faces
2520 that approximate a sphere,
2521
2522 Parameters
2523 ----------
2524 radius : float, default: 1.0
2525 Radius of the icosphere.
2526
2527 center : sequence[float], default: (0.0, 0.0, 0.0)
2528 Center of the icosphere.
2529
2530 nsub : int, default: 3
2531 This is the number of times each triangle of the original
2532 :func:`pyvista.Icosahedron` is subdivided.
2533
2534 Returns
2535 -------
2536 pyvista.PolyData
2537 Mesh of the icosphere.
2538
2539 See Also
2540 --------
2541 pyvista.Sphere
2542
2543 Examples
2544 --------
2545 Create the icosphere and plot it with edges.
2546
2547 >>> import pyvista as pv
2548 >>> icosphere = pv.Icosphere()
2549 >>> icosphere.plot(show_edges=True)
2550
2551 Show how this icosphere was created.
2552
2553 >>> import numpy as np
2554 >>> icosahedron = pv.Icosahedron()
2555 >>> icosahedron.clear_data() # remove extra scalars
2556 >>> icosahedron_sub = icosahedron.subdivide(nsub=3)
2557 >>> pl = pv.Plotter(shape=(1, 3))
2558 >>> _ = pl.add_mesh(icosahedron, show_edges=True)
2559 >>> pl.subplot(0, 1)
2560 >>> _ = pl.add_mesh(icosahedron_sub, show_edges=True)
2561 >>> pl.subplot(0, 2)
2562 >>> _ = pl.add_mesh(icosphere, show_edges=True)
2563 >>> pl.show()
2564
2565 Show how the triangles are not uniform in area. This is because the
2566 ones farther from the edges from the original triangles have farther
2567 to travel to the sphere.
2568
2569 >>> icosphere = pv.Icosphere(nsub=4)
2570 >>> icosphere.compute_cell_sizes().plot(scalars='Area')
2571
2572 """
2573 mesh = Icosahedron()
2574 mesh.clear_data()
2575 mesh = mesh.subdivide(nsub=nsub)
2576
2577 # scale to desired radius and translate origin
2578 dist = np.linalg.norm(mesh.points, axis=1, keepdims=True) # distance from origin
2579 mesh.points = mesh.points * (radius / dist) + center
2580 return mesh