Debian Codegraph @

pyvista/core/pointset.py

raw
1 """Sub-classes and wrappers for :vtk:`vtkPointSet`."""
2
3 from __future__ import annotations
4
5 from collections.abc import Iterable
6 from collections.abc import Sequence
7 import contextlib
8 from functools import cached_property
9 from functools import wraps
10 import numbers
11 from pathlib import Path
12 from textwrap import dedent
13 from typing import TYPE_CHECKING
14 from typing import ClassVar
15 from typing import cast
16
17 import numpy as np
18
19 import pyvista as pv
20 from pyvista import _vtk
21 from pyvista._deprecate_positional_args import _deprecate_positional_args
22 from pyvista._warn_external import warn_external
23 from pyvista.core._vtk_utilities import vtk_version_info
24 from pyvista.core.errors import PyVistaDeprecationWarning
25
26 from .cell import CellArray
27 from .cell import _get_connectivity_array
28 from .cell import _get_irregular_cells
29 from .cell import _get_offset_array
30 from .cell import _get_regular_cells
31 from .celltype import CellType
32 from .dataset import DataSet
33 from .errors import CellSizeError
34 from .errors import PointSetCellOperationError
35 from .errors import PointSetDimensionReductionError
36 from .errors import PointSetNotSupported
37 from .filters import PolyDataFilters
38 from .filters import StructuredGridFilters
39 from .filters import UnstructuredGridFilters
40 from .filters import _get_output
41 from .utilities.arrays import convert_array
42 from .utilities.cells import create_mixed_cells
43 from .utilities.cells import get_mixed_cells
44 from .utilities.cells import numpy_to_idarr
45 from .utilities.fileio import _CompressionOptions
46 from .utilities.fileio import get_ext
47 from .utilities.misc import abstract_class
48 from .utilities.points import vtk_points
49 from .utilities.writer import BaseWriter
50 from .utilities.writer import HDFWriter
51 from .utilities.writer import HoudiniPolyDataWriter
52 from .utilities.writer import IVWriter
53 from .utilities.writer import OBJWriter
54 from .utilities.writer import PLYWriter
55 from .utilities.writer import PolyDataWriter
56 from .utilities.writer import SimplePointsWriter
57 from .utilities.writer import STLWriter
58 from .utilities.writer import StructuredGridWriter
59 from .utilities.writer import UnstructuredGridWriter
60 from .utilities.writer import XMLPolyDataWriter
61 from .utilities.writer import XMLStructuredGridWriter
62 from .utilities.writer import XMLUnstructuredGridWriter
63
64 if TYPE_CHECKING:
65 from typing import Any
66
67 from typing_extensions import Self
68
69 from ._typing_core import ArrayLike
70 from ._typing_core import BoundsTuple
71 from ._typing_core import CellArrayLike
72 from ._typing_core import MatrixLike
73 from ._typing_core import NumpyArray
74 from ._typing_core import VectorLike
75 from .filters.data_object import _NestedMeshValidationFields
76
77 DEFAULT_INPLACE_WARNING = (
78 'You did not specify a value for `inplace` and the default value will '
79 'be changing to `False` in future versions for point-based meshes (e.g., '
80 '`PolyData`). Please make sure you are not assuming this to be an inplace '
81 'operation.'
82 )
83
84
85 @abstract_class
86 class _PointSet(DataSet):
87 """PyVista's equivalent of :vtk:`vtkPointSet`.
88
89 This holds methods common to PolyData and UnstructuredGrid.
90 """
91
92 _WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {
93 '.xyz': SimplePointsWriter,
94 }
95
96 @_deprecate_positional_args
97 def center_of_mass(self, scalars_weight: bool = False) -> NumpyArray[float]: # noqa: FBT001, FBT002
98 """Return the coordinates for the center of mass of the mesh.
99
100 Parameters
101 ----------
102 scalars_weight : bool, default: False
103 Flag for using the mesh scalars as weights.
104
105 Returns
106 -------
107 numpy.ndarray
108 Coordinates for the center of mass.
109
110 Examples
111 --------
112 >>> import pyvista as pv
113 >>> mesh = pv.Sphere(center=(1, 1, 1))
114 >>> mesh.center_of_mass()
115 array([1., 1., 1.])
116
117 """
118 alg = _vtk.vtkCenterOfMass()
119 alg.SetInputDataObject(self)
120 alg.SetUseScalarsAsWeights(scalars_weight)
121 alg.Update()
122 return np.array(alg.GetCenter())
123
124 def shallow_copy(self, to_copy: DataSet) -> None: # type: ignore[override]
125 """Create a shallow copy from a different dataset into this one.
126
127 This method mutates this dataset and returns ``None``.
128
129 Parameters
130 ----------
131 to_copy : pyvista.DataSet
132 Data object to perform the shallow copy from.
133
134 """
135 # Set default points if needed
136 if not to_copy.GetPoints():
137 to_copy.SetPoints(_vtk.vtkPoints())
138 DataSet.shallow_copy(self, cast('_vtk.vtkDataObject', to_copy))
139
140 @_deprecate_positional_args(allowed=['ind'])
141 def remove_cells(
142 self,
143 ind: VectorLike[bool] | VectorLike[int],
144 inplace: bool = False, # noqa: FBT001, FBT002
145 ) -> _PointSet:
146 """Remove cells.
147
148 Parameters
149 ----------
150 ind : VectorLike[int] | VectorLike[bool]
151 Cell indices to be removed. The array can also be a
152 boolean array of the same size as the number of cells.
153
154 inplace : bool, default: False
155 Whether to update the mesh in-place.
156
157 Returns
158 -------
159 pyvista.DataSet
160 Same type as the input, but with the specified cells
161 removed.
162
163 See Also
164 --------
165 :ref:`ghost_cells_example`
166
167 Examples
168 --------
169 Remove 20 cells from an unstructured grid.
170
171 >>> from pyvista import examples
172 >>> import pyvista as pv
173 >>> hex_mesh = pv.read(examples.hexbeamfile)
174 >>> removed = hex_mesh.remove_cells(range(10, 20))
175 >>> removed.plot(color='lightblue', show_edges=True, line_width=3)
176
177 """
178 if isinstance(ind, np.ndarray):
179 if ind.dtype == np.bool_ and ind.size != self.n_cells:
180 msg = f'Boolean array size must match the number of cells ({self.n_cells})'
181 raise ValueError(msg)
182 ghost_cells = np.zeros(self.n_cells, np.uint8)
183 ghost_cells[ind] = _vtk.vtkDataSetAttributes.DUPLICATECELL
184
185 target = self if inplace else self.copy()
186
187 target.cell_data[_vtk.vtkDataSetAttributes.GhostArrayName()] = ghost_cells
188 target.RemoveGhostCells()
189 return target
190
191 def points_to_double(self) -> Self:
192 """Convert the points datatype to double precision.
193
194 Returns
195 -------
196 pyvista.PointSet
197 Pointset with points in double precision.
198
199 Notes
200 -----
201 This operates in place.
202
203 Examples
204 --------
205 Create a mesh that has points of the type ``float32`` and
206 convert the points to ``float64``.
207
208 >>> import pyvista as pv
209 >>> mesh = pv.Sphere()
210 >>> mesh.points.dtype
211 dtype('float32')
212 >>> _ = mesh.points_to_double()
213 >>> mesh.points.dtype
214 dtype('float64')
215
216 """
217 if self.points.dtype != np.double:
218 self.points = self.points.astype(np.double)
219 return self
220
221 # todo: `transform_all_input_vectors` is not handled when modifying inplace
222 @_deprecate_positional_args(allowed=['xyz'])
223 def translate(
224 self: Self,
225 xyz: VectorLike[float],
226 transform_all_input_vectors: bool = False, # noqa: FBT001, FBT002
227 inplace: bool = False, # noqa: FBT001, FBT002
228 ):
229 """Translate the mesh.
230
231 Parameters
232 ----------
233 xyz : VectorLike[float]
234 A vector of three floats of cartesian values to translate the mesh with.
235
236 transform_all_input_vectors : bool, default: False
237 When ``True``, all input vectors are transformed. Otherwise, only
238 the points, normals and active vectors are transformed. This is
239 only valid when not updating in place.
240
241 inplace : bool, default: False
242 Updates mesh in-place.
243
244 Returns
245 -------
246 pyvista.PointSet
247 Translated pointset.
248
249 Examples
250 --------
251 Create a sphere and translate it by ``(2, 1, 2)``.
252
253 >>> import pyvista as pv
254 >>> mesh = pv.Sphere()
255 >>> mesh.center
256 (0.0, 0.0, 0.0)
257 >>> trans = mesh.translate((2, 1, 2), inplace=True)
258 >>> trans.center
259 (2.0, 1.0, 2.0)
260
261 """
262 if inplace:
263 self.points += np.asarray(xyz)
264 return self
265 return pv.DataObjectFilters.translate(
266 self,
267 xyz,
268 transform_all_input_vectors=transform_all_input_vectors,
269 inplace=inplace,
270 )
271
272
273 class PointSet(_PointSet, _vtk.vtkPointSet):
274 """Concrete class for storing a set of points.
275
276 This is a concrete class representing a set of points that specifies the
277 interface for datasets that explicitly use "point" arrays to represent
278 geometry. This class is useful for improving the performance of filters on
279 point clouds, but not plotting.
280
281 For further details see :vtk:`vtkPointSet`.
282
283 Parameters
284 ----------
285 var_inp : :vtk:`vtkPointSet`, MatrixLike[float], optional
286 Flexible input type. Can be a :vtk:`vtkPointSet`, in which case
287 this PointSet object will be copied if ``deep=True`` and will
288 be a shallow copy if ``deep=False``.
289
290 List, numpy array, or sequence containing point locations. Must be an
291 ``(N, 3)`` array of points.
292
293 deep : bool, default: False
294 Whether to copy the input ``points``, or to create a PointSet from them
295 without copying them. Setting ``deep=True`` ensures that the original
296 arrays can be modified outside the mesh without affecting the
297 mesh.
298
299 force_float : bool, default: True
300 Casts the datatype to ``float32`` if points datatype is non-float. Set
301 this to ``False`` to allow non-float types, though this may lead to
302 truncation of intermediate floats when transforming datasets.
303
304 validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False
305 Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after
306 initialization. Set this to ``True`` to validate all fields, or specify any
307 combination of fields allowed by ``validate_mesh``.
308
309 .. versionadded:: 0.47
310
311 Examples
312 --------
313 Create a simple point cloud of 10 points from a numpy array.
314
315 >>> import numpy as np
316 >>> import pyvista as pv
317 >>> rng = np.random.default_rng(seed=0)
318 >>> points = rng.random((10, 3))
319 >>> pset = pv.PointSet(points)
320
321 Plot the pointset. Note: this casts to a :class:`pyvista.PolyData`
322 internally when plotting.
323
324 >>> pset.plot(point_size=10)
325
326 """
327
328 @_deprecate_positional_args(allowed=['var_inp'])
329 def __init__(
330 self,
331 var_inp=None,
332 deep: bool = False, # noqa: FBT001, FBT002
333 force_float: bool = True, # noqa: FBT001, FBT002
334 *,
335 validate: bool | _NestedMeshValidationFields = False,
336 ) -> None:
337 """Initialize the pointset."""
338 super().__init__()
339
340 if var_inp is None:
341 return
342 elif isinstance(var_inp, _vtk.vtkPointSet):
343 if deep:
344 self.deep_copy(var_inp)
345 else:
346 self.shallow_copy(var_inp) # type: ignore[arg-type]
347 else:
348 self.SetPoints(vtk_points(var_inp, deep=deep, force_float=force_float))
349
350 if validate:
351 self._validate_mesh(validate)
352
353 def __repr__(self):
354 """Return the standard representation."""
355 return DataSet.__repr__(self)
356
357 def __str__(self):
358 """Return the standard str representation."""
359 return DataSet.__str__(self)
360
361 @_deprecate_positional_args
362 def cast_to_polydata(self, deep: bool = True): # noqa: FBT001, FBT002
363 """Cast this dataset to polydata.
364
365 Parameters
366 ----------
367 deep : bool, deep: True
368 Whether to copy the pointset points, or to create a PolyData
369 without copying them. Setting ``deep=True`` ensures that the
370 original arrays can be modified outside the PolyData without
371 affecting the PolyData.
372
373 Returns
374 -------
375 pyvista.PolyData
376 PointSet cast to a ``pyvista.PolyData``.
377
378 """
379 pdata = PolyData(self.points, deep=deep)
380 if deep:
381 pdata.point_data.update(self.point_data) # update performs deep copy
382 else:
383 for key, value in self.point_data.items():
384 pdata.point_data[key] = value
385 return pdata
386
387 def cast_to_unstructured_grid(self) -> pv.UnstructuredGrid:
388 """Cast this dataset to :class:`pyvista.UnstructuredGrid`.
389
390 A deep copy of the points and point data is made.
391
392 Returns
393 -------
394 pyvista.UnstructuredGrid
395 Dataset cast to a :class:`pyvista.UnstructuredGrid`.
396
397 Examples
398 --------
399 Cast a :class:`pyvista.PointSet` to a
400 :class:`pyvista.UnstructuredGrid`.
401
402 >>> import pyvista as pv
403 >>> from pyvista import examples
404 >>> mesh = examples.download_cloud_dark_matter()
405 >>> type(mesh)
406 <class 'pyvista.core.pointset.PointSet'>
407 >>> grid = mesh.cast_to_unstructured_grid()
408 >>> type(grid)
409 <class 'pyvista.core.pointset.UnstructuredGrid'>
410
411 """
412 return self.cast_to_polydata(deep=False).cast_to_unstructured_grid()
413
414 @wraps(DataSet.plot)
415 def plot(self, *args, **kwargs): # type: ignore[override] # numpydoc ignore=RT01
416 """Cast to PolyData and plot."""
417 pdata = self.cast_to_polydata(deep=False)
418 kwargs.setdefault('style', 'points')
419 return pdata.plot(*args, **kwargs)
420
421 @wraps(PolyDataFilters.threshold)
422 def threshold(self, *args, **kwargs): # type: ignore[override] # numpydoc ignore=RT01
423 """Cast to PolyData and threshold.
424
425 Need this because cell-wise operations fail for PointSets.
426 """
427 return self.cast_to_polydata(deep=False).threshold(*args, **kwargs).cast_to_pointset()
428
429 @wraps(PolyDataFilters.threshold_percent)
430 def threshold_percent(self, *args, **kwargs): # type: ignore[override] # numpydoc ignore=RT01
431 """Cast to PolyData and threshold.
432
433 Need this because cell-wise operations fail for PointSets.
434 """
435 return (
436 self.cast_to_polydata(deep=False).threshold_percent(*args, **kwargs).cast_to_pointset()
437 )
438
439 @wraps(PolyDataFilters.explode)
440 def explode(self, *args, **kwargs): # type: ignore[override] # numpydoc ignore=RT01
441 """Cast to PolyData and explode.
442
443 The explode filter relies on cells.
444
445 """
446 return self.cast_to_polydata(deep=False).explode(*args, **kwargs).cast_to_pointset()
447
448 @wraps(PolyDataFilters.delaunay_3d)
449 def delaunay_3d(self, *args, **kwargs): # type: ignore[override] # numpydoc ignore=RT01
450 """Cast to PolyData and run delaunay_3d."""
451 return self.cast_to_polydata(deep=False).delaunay_3d(*args, **kwargs)
452
453 @property
454 def area(self) -> float: # numpydoc ignore=RT01
455 """Return 0.0 since a PointSet has no area."""
456 return 0.0
457
458 @property
459 def volume(self) -> float: # numpydoc ignore=RT01
460 """Return 0.0 since a PointSet has no volume."""
461 return 0.0
462
463 def contour(self, *args, **kwargs): # noqa: ARG002
464 """Raise dimension reducing operations are not supported."""
465 msg = 'Contour and other dimension reducing filters are not supported on PointSets'
466 raise PointSetNotSupported(msg)
467
468 def cell_data_to_point_data(self, *args, **kwargs): # noqa: ARG002
469 """Raise PointSets do not have cells."""
470 msg = 'PointSets contain no cells or cell data.'
471 raise PointSetNotSupported(msg)
472
473 def point_data_to_cell_data(self, *args, **kwargs): # noqa: ARG002
474 """Raise PointSets do not have cells."""
475 msg = 'PointSets contain no cells or cell data.'
476 raise PointSetNotSupported(msg)
477
478 def triangulate(self, *args, **kwargs): # noqa: ARG002
479 """Raise cell operations are not supported."""
480 raise PointSetCellOperationError
481
482 def decimate_boundary(self, *args, **kwargs): # noqa: ARG002
483 """Raise cell operations are not supported."""
484 raise PointSetCellOperationError
485
486 def find_cells_along_line(self, *args, **kwargs): # noqa: ARG002
487 """Raise cell operations are not supported."""
488 raise PointSetCellOperationError
489
490 def tessellate(self, *args, **kwargs): # noqa: ARG002
491 """Raise cell operations are not supported."""
492 raise PointSetCellOperationError
493
494 def slice(self, *args, **kwargs): # noqa: ARG002
495 """Raise dimension reducing operations are not supported."""
496 raise PointSetDimensionReductionError
497
498 def slice_along_axis(self, *args, **kwargs): # noqa: ARG002
499 """Raise dimension reducing operations are not supported."""
500 raise PointSetDimensionReductionError
501
502 def slice_along_line(self, *args, **kwargs): # noqa: ARG002
503 """Raise dimension reducing operations are not supported."""
504 raise PointSetDimensionReductionError
505
506 def slice_implicit(self, *args, **kwargs): # noqa: ARG002
507 """Raise dimension reducing operations are not supported."""
508 raise PointSetDimensionReductionError
509
510 def slice_orthogonal(self, *args, **kwargs): # noqa: ARG002
511 """Raise dimension reducing operations are not supported."""
512 raise PointSetDimensionReductionError
513
514 def shrink(self, *args, **kwargs): # noqa: ARG002
515 """Raise cell operations are not supported."""
516 raise PointSetCellOperationError
517
518 def separate_cells(self, *args, **kwargs): # noqa: ARG002
519 """Raise cell operations are not supported."""
520 raise PointSetCellOperationError
521
522 def remove_cells(self, *args, **kwargs): # noqa: ARG002
523 """Raise cell operations are not supported."""
524 raise PointSetCellOperationError
525
526 def point_is_inside_cell(self, *args, **kwargs): # noqa: ARG002
527 """Raise cell operations are not supported."""
528 raise PointSetCellOperationError
529
530 def extract_surface(self, *args, **kwargs): # noqa: ARG002
531 """Raise extract surface are not supported."""
532 raise PointSetCellOperationError
533
534 def extract_geometry(self, *args, **kwargs): # noqa: ARG002
535 """Raise extract geometry are not supported.
536
537 ..deprecated:: 0.47
538
539 """
540 warn_external(
541 '`extract_geometry` is deprecated. Use `extract_surface(algorithm=None)` instead.',
542 PyVistaDeprecationWarning,
543 )
544 if pv.version_info >= (0, 50): # pragma: no cover
545 msg = 'Convert this deprecation warning into an error.'
546 raise RuntimeError(msg)
547 if pv.version_info >= (0, 53): # pragma: no cover
548 msg = 'Remove this deprecated filter.'
549 raise RuntimeError(msg)
550 raise PointSetCellOperationError
551
552 def cell_validator(self, *args, **kwargs): # noqa: ARG002
553 """Raise cell operations are not supported."""
554 raise PointSetCellOperationError
555
556
557 class PolyData(_PointSet, PolyDataFilters, _vtk.vtkPolyData):
558 """Dataset consisting of surface geometry (e.g. vertices, lines, and polygons).
559
560 The surface geometry is defined by its :attr:`~pyvista.DataSet.points` and four separate
561 cell connectivity arrays:
562
563 - :attr:`verts` for 0-dimensional :attr:`~pyvista.CellType.VERTEX` and
564 :attr:`~pyvista.CellType.POLY_VERTEX` cells.
565 - :attr:`lines` for 1-dimensional :attr:`~pyvista.CellType.LINE` and
566 :attr:`~pyvista.CellType.POLY_LINE` cells.
567 - :attr:`faces` for 2-dimensional :attr:`~pyvista.CellType.TRIANGLE`,
568 :attr:`~pyvista.CellType.QUAD`, and :attr:`~pyvista.CellType.POLYGON` cells.
569 - :attr:`strips` for 2-dimensional :attr:`~pyvista.CellType.TRIANGLE_STRIP` cells.
570
571 Cell types can be mixed, and any combination of cell connectivity array(s) may be specified.
572
573 :class:`~pyvista.PolyData` can be initialized in several ways:
574
575 - Create an empty mesh
576 - Initialize from a :vtk:`vtkPolyData`
577 - Using points only
578 - Using points with verts, faces, lines, and/or strips
579 - From a file
580
581 If a points array is provided with no cell connectivity, the :attr:`verts` connectivity is
582 populated by default, and each point is automatically associated with a single
583 :attr:`~pyvista.CellType.VERTEX` to create a point cloud where :attr:`n_verts` equals
584 :attr:`~pyvista.DataSet.n_points`.
585
586 Parameters
587 ----------
588 var_inp : :vtk:`vtkPolyData`, str, sequence, optional
589 Flexible input type. Can be a :vtk:`vtkPolyData`, in which case
590 this PolyData object will be copied if ``deep=True`` and will
591 be a shallow copy if ``deep=False``.
592
593 Also accepts a path, which may be local path as in
594 ``'my_mesh.stl'`` or global path like ``'/tmp/my_mesh.ply'``
595 or ``'C:/Users/user/my_mesh.ply'``.
596
597 Otherwise, this must be a points array or list containing one
598 or more points. Each point must have 3 dimensions. If
599 ``faces``, ``lines``, ``strips``, and ``verts`` are all
600 ``None``, then the ``PolyData`` object will be created with
601 vertex cells with ``n_verts`` equal to the number of ``points``.
602
603 faces : CellArrayLike, optional
604 Connectivity of polygonal :attr:`faces`. Can be either a padded connectivity
605 array or an explicit cell array object.
606
607 In the padded array format, faces must contain padding
608 indicating the number of points in the face. For example, the
609 two faces ``[10, 11, 12]`` and ``[20, 21, 22, 23]`` will be
610 represented as ``[3, 10, 11, 12, 4, 20, 21, 22, 23]``. This
611 lets you have an arbitrary number of points per face.
612
613 lines : CellArrayLike, optional
614 Connectivity of :attr:`lines`. Like ``faces``, this can be either a padded
615 connectivity array or an explicit cell array object. The padded
616 array format requires padding indicating the number of points in
617 a line segment. For example, the two line segments ``[0, 1]``
618 and ``[1, 2, 3, 4]`` will be represented as
619 ``[2, 0, 1, 4, 1, 2, 3, 4]``.
620
621 strips : CellArrayLike optional
622 Connectivity of triangle :attr:`strips`. Triangle strips require an
623 initial triangle, and the following points of the strip. Each
624 triangle is built with the new point and the two previous
625 points.
626
627 Just as in ``lines`` and ``faces``, this connectivity can be
628 specified as either a padded array or an explicit cell array
629 object. The padded array requires a padding indicating the
630 number of points. For example, a single triangle strip of the 10
631 point indices ``[0, 1, 2, 3, 6, 7, 4, 5, 0, 1]`` requires
632 padding of ``10`` and should be input as
633 ``[10, 0, 1, 2, 3, 6, 7, 4, 5, 0, 1]``.
634
635 deep : bool, optional
636 Whether to copy the inputs, or to create a mesh from them
637 without copying them. Setting ``deep=True`` ensures that the
638 original arrays can be modified outside the mesh without
639 affecting the mesh. Default is ``False``.
640
641 force_ext : str, optional
642 If initializing from a file, force the reader to treat the
643 file as if it had this extension as opposed to the one in the
644 file.
645
646 force_float : bool, optional
647 Casts the datatype to ``float32`` if points datatype is
648 non-float. Default ``True``. Set this to ``False`` to allow
649 non-float types, though this may lead to truncation of
650 intermediate floats when transforming datasets.
651
652 verts : CellArrayLike, optional
653 The :attr:`verts` connectivity. Like ``faces``, ``lines``, and
654 ``strips`` this can be supplied as either a padded array or an
655 explicit cell array object. In the padded array format,
656 the padding indicates the number of vertices in each cell. For
657 example, ``[1, 0, 1, 1, 1, 2]`` indicates three vertex cells
658 each with one point, and ``[2, 0, 1, 2, 2, 3]`` indicates two
659 polyvertex cells each with two points.
660
661 validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False
662 Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after
663 initialization. Set this to ``True`` to validate all fields, or specify any
664 combination of fields allowed by ``validate_mesh``.
665
666 .. versionadded:: 0.47
667
668 See Also
669 --------
670 pyvista.PolyData.from_regular_faces
671 pyvista.PolyData.from_irregular_faces
672
673 Examples
674 --------
675 >>> import vtk
676 >>> import numpy as np
677 >>> from pyvista import examples
678 >>> import pyvista as pv
679
680 Seed random number generator for reproducible plots
681
682 >>> rng = np.random.default_rng(seed=0)
683
684 Create an empty mesh.
685
686 >>> mesh = pv.PolyData()
687
688 Initialize from a :vtk:`vtkPolyData` object.
689
690 >>> vtkobj = vtk.vtkPolyData()
691 >>> mesh = pv.PolyData(vtkobj)
692
693 Initialize from just points, creating vertices
694
695 >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 0.5, 0], [0, 0.5, 0]])
696 >>> mesh = pv.PolyData(points)
697
698 Initialize from points and faces, creating polygonal faces.
699
700 >>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2]])
701 >>> mesh = pv.PolyData(points, faces)
702
703 Initialize from points and lines.
704
705 >>> lines = np.hstack([[2, 0, 1], [2, 1, 2]])
706 >>> mesh = pv.PolyData(points, lines=lines)
707
708 Initialize from points and triangle strips.
709
710 >>> strips = np.hstack([[4, 0, 1, 3, 2]])
711 >>> mesh = pv.PolyData(points, strips=strips)
712
713 It is also possible to create with multiple cell types.
714
715 >>> verts = [1, 0]
716 >>> lines = [2, 1, 2]
717 >>> mesh = pv.PolyData(points, verts=verts, lines=lines)
718
719 Initialize from a filename.
720
721 >>> mesh = pv.PolyData(examples.antfile)
722
723 Construct a set of random line segments using a ``pv.CellArray``.
724 Because every line in this example has the same size, in this case
725 two points, we can use ``pv.CellArray.from_regular_cells`` to
726 construct the ``lines`` cell array. This is the most efficient
727 method to construct a cell array.
728
729 >>> n_points = 20
730 >>> n_lines = n_points // 2
731 >>> points = rng.random((n_points, 3))
732 >>> lines = rng.integers(low=0, high=n_points, size=(n_lines, 2))
733 >>> mesh = pv.PolyData(points, lines=pv.CellArray.from_regular_cells(lines))
734 >>> mesh.cell_data['line_idx'] = np.arange(n_lines)
735 >>> mesh.plot(scalars='line_idx')
736
737 Construct a set of random triangle strips using a ``pv.CellArray``.
738 Because each strip in this example can have a different number
739 of points, we use ``pv.CellArray.from_irregular_cells`` to construct
740 the ``strips`` cell array.
741
742 >>> n_strips = 4
743 >>> n_verts_per_strip = rng.integers(low=3, high=7, size=n_strips)
744 >>> n_points = 10 * sum(n_verts_per_strip)
745 >>> points = rng.random((n_points, 3))
746 >>> strips = [
747 ... rng.integers(low=0, high=n_points, size=nv) for nv in n_verts_per_strip
748 ... ]
749 >>> mesh = pv.PolyData(
750 ... points, strips=pv.CellArray.from_irregular_cells(strips)
751 ... )
752 >>> mesh.cell_data['strip_idx'] = np.arange(n_strips)
753 >>> mesh.plot(show_edges=True, scalars='strip_idx')
754
755 Construct a mesh reusing the ``faces`` ``pv.CellArray`` from another
756 mesh. The VTK methods ``GetPolys``, ``GetLines``, ``GetStrips``, and
757 ``GetVerts`` return the underlying ``CellArray``s for the ``faces``,
758 ``lines``, ``strips``, and ``verts`` properties respectively.
759 Reusing cell arrays like this can be a performance optimization for
760 large meshes because it avoids allocating new arrays.
761
762 >>> small_sphere = pv.Sphere().compute_normals()
763 >>> inflated_points = (
764 ... small_sphere.points + 0.1 * small_sphere.point_data['Normals']
765 ... )
766 >>> larger_sphere = pv.PolyData(inflated_points, faces=small_sphere.GetPolys())
767 >>> pl = pv.Plotter()
768 >>> _ = pl.add_mesh(small_sphere, color='red', show_edges=True)
769 >>> _ = pl.add_mesh(larger_sphere, color='blue', opacity=0.3, show_edges=True)
770 >>> pl.show()
771
772 See :ref:`create_poly_example` for more examples.
773
774 """
775
776 _WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {
777 '.ply': PLYWriter,
778 '.vtp': XMLPolyDataWriter,
779 '.stl': STLWriter,
780 '.vtk': PolyDataWriter,
781 '.geo': HoudiniPolyDataWriter,
782 '.obj': OBJWriter,
783 '.iv': IVWriter,
784 }
785 if vtk_version_info >= (9, 4):
786 _WRITERS.update({'.vtkhdf': HDFWriter})
787
788 @_deprecate_positional_args(allowed=['var_inp', 'faces'])
789 def __init__( # noqa: PLR0917
790 self,
791 var_inp: _vtk.vtkPolyData | str | Path | MatrixLike[float] | None = None,
792 faces: CellArrayLike | None = None,
793 lines: CellArrayLike | None = None,
794 strips: CellArrayLike | None = None,
795 deep: bool = False, # noqa: FBT001, FBT002
796 force_ext: str | None = None,
797 force_float: bool = True, # noqa: FBT001, FBT002
798 verts: CellArrayLike | None = None,
799 *,
800 validate: bool | _NestedMeshValidationFields = False,
801 ) -> None:
802 """Initialize the polydata."""
803 local_parms = locals()
804 super().__init__()
805
806 # allow empty input
807 if var_inp is None:
808 return
809
810 # filename
811 opt_kwarg = ['faces', 'lines']
812 if isinstance(var_inp, (str, Path)):
813 for kwarg in opt_kwarg:
814 if local_parms[kwarg]:
815 msg = 'No other arguments should be set when first parameter is a string'
816 raise ValueError(msg)
817 self._from_file(var_inp, force_ext=force_ext) # is filename
818 if validate:
819 self._validate_mesh(validate)
820 return
821
822 # PolyData-like
823 if isinstance(var_inp, _vtk.vtkPolyData):
824 for kwarg in opt_kwarg:
825 if local_parms[kwarg]:
826 msg = 'No other arguments should be set when first parameter is a PolyData'
827 raise ValueError(msg)
828 if deep:
829 self.deep_copy(var_inp)
830 else:
831 self.shallow_copy(var_inp) # type: ignore[arg-type]
832 if validate:
833 self._validate_mesh(validate)
834 return
835
836 # First parameter is points
837 if isinstance(var_inp, (np.ndarray, list, _vtk.vtkDataArray)):
838 self.SetPoints(vtk_points(var_inp, deep=deep, force_float=force_float))
839
840 else:
841 msg = f"""
842 Invalid Input type:
843
844 Expected first argument to be either a:
845 - vtkPolyData
846 - pyvista.PolyData
847 - numeric numpy.ndarray (1 or 2 dimensions)
848 - List (flat or nested with 3 points per vertex)
849 - vtkDataArray
850
851 Instead got: {type(var_inp)}"""
852 raise TypeError(dedent(msg.strip('\n')))
853
854 # At this point, points have been setup, add faces and/or lines
855 if faces is lines is strips is verts is None:
856 # one cell per point (point cloud case)
857 verts = self._make_vertex_cells(self.n_points)
858
859 for k, v in (('verts', verts), ('strips', strips), ('faces', faces), ('lines', lines)):
860 if v is None:
861 continue
862
863 # These properties can be supplied as either arrays or pre-constructed `CellArray`s
864 if not isinstance(v, _vtk.vtkCellArray):
865 try:
866 v = CellArray(v) # noqa: PLW2901
867 except CellSizeError as err:
868 # Raise an additional error so user knows which property triggered the error
869 msg = f'`{k}` cell array size is invalid.'
870 raise CellSizeError(msg) from err
871
872 setattr(self, k, v)
873
874 if validate:
875 self._validate_mesh(validate)
876
877 def _post_file_load_processing(self) -> None:
878 """Execute after loading a PolyData from file."""
879 # When loading files with just point arrays, create and
880 # set the polydata vertices
881 if self.n_points > 0 and self.n_cells == 0:
882 self.verts = self._make_vertex_cells(self.n_points)
883
884 def __repr__(self) -> str:
885 """Return the standard representation."""
886 return DataSet.__repr__(self)
887
888 def __str__(self) -> str:
889 """Return the standard str representation."""
890 return DataSet.__str__(self)
891
892 @staticmethod
893 def _make_vertex_cells(npoints: int) -> NumpyArray[int]:
894 cells = np.empty((npoints, 2), dtype=pv.ID_TYPE)
895 cells[:, 0] = 1
896 cells[:, 1] = np.arange(npoints, dtype=pv.ID_TYPE)
897 return cells
898
899 @property
900 def verts(self) -> NumpyArray[int]: # numpydoc ignore=RT01
901 """Return or set the vertex padded connectivity array.
902
903 Like all padded VTK connectivity arrays, the array is structured as::
904
905 [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]
906
907 where ``n0`` is the number of points in vertex 0, and ``pX_Y`` is the
908 Y'th point in vertex X.
909
910 Vertices can be a single :attr:`~pyvista.CellType.VERTEX` cell with connectivity
911 to a single point, or a :attr:`~pyvista.CellType.POLY_VERTEX` with connectivity
912 to multiple points.
913
914 For example, a single vertex and poly-vertex with five points might be represented as::
915
916 [1, 0, 5, 3, 2, 4, 1, 5]
917
918 Where the two separate vertex cells are ``[1, 0]`` and ``[5, 3, 2, 4, 1, 5]``.
919
920 See Also
921 --------
922 n_verts
923 lines, faces, strips
924 Padded connectivity arrays for other :class:`~pyvista.PolyData` cell types.
925
926 Returns
927 -------
928 numpy.ndarray
929 Array of vertex cell connectivity.
930
931 Examples
932 --------
933 Create a point cloud polydata and return the vertex cells.
934
935 >>> import pyvista as pv
936 >>> import numpy as np
937 >>> rng = np.random.default_rng(seed=0)
938 >>> points = rng.random((5, 3))
939 >>> pdata = pv.PolyData(points)
940 >>> pdata.verts
941 array([1, 0, 1, 1, 1, 2, 1, 3, 1, 4])
942
943 Set vertex cells. Note how the mesh plots both the surface
944 mesh and the additional vertices in a single plot.
945
946 >>> mesh = pv.Plane(i_resolution=3, j_resolution=3)
947 >>> mesh.verts = np.vstack(
948 ... (
949 ... np.ones(mesh.n_points, dtype=np.int64),
950 ... np.arange(mesh.n_points),
951 ... )
952 ... ).T
953 >>> mesh.plot(
954 ... color='lightblue',
955 ... render_points_as_spheres=True,
956 ... point_size=60,
957 ... )
958
959 Vertex cells can also be set to a ``CellArray``. The following
960 ``verts`` assignment is equivalent to the one above.
961
962 >>> mesh.verts = pv.CellArray.from_regular_cells(
963 ... np.arange(mesh.n_points).reshape((-1, 1))
964 ... )
965
966 """
967 self.GetVerts().ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
968 return _vtk.vtk_to_numpy(arr)
969
970 @verts.setter
971 def verts(self, verts: CellArrayLike) -> None:
972 if isinstance(verts, _vtk.vtkCellArray):
973 self.SetVerts(verts)
974 else:
975 self.SetVerts(CellArray(verts))
976
977 @property
978 def lines(self) -> NumpyArray[int]: # numpydoc ignore=RT01
979 """Return the lines connectivity array.
980
981 Like all padded VTK connectivity arrays, the array is structured as::
982
983 [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]
984
985 where ``n0`` is the number of points in line 0, and ``pX_Y`` is the
986 Y'th point in line X.
987
988 Lines can be a single :attr:`~pyvista.CellType.LINE` cell with connectivity
989 to two points, or a :attr:`~pyvista.CellType.POLY_LINE` with connectivity
990 to any number of points.
991
992 For example, a single line and poly-line with five points might be represented as::
993
994 [2, 0, 1, 5, 3, 2, 4, 6, 5]
995
996 Where the two separate line cells are ``[2, 0, 1]`` and ``[5, 3, 2, 4, 6, 5]``.
997
998 Lines can also be set by assigning a :class:`~pyvista.CellArray`.
999
1000 See Also
1001 --------
1002 n_lines
1003 verts, faces, strips
1004 Padded connectivity arrays for other :class:`~pyvista.PolyData` cell types.
1005
1006 Examples
1007 --------
1008 Return the lines from a spline.
1009
1010 >>> import pyvista as pv
1011 >>> import numpy as np
1012 >>> points = np.random.default_rng().random((3, 3))
1013 >>> spline = pv.Spline(points, 10)
1014 >>> spline.lines
1015 array([10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
1016
1017 """
1018 self.GetLines().ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
1019 return _vtk.vtk_to_numpy(arr).ravel()
1020
1021 @lines.setter
1022 def lines(self, lines: CellArrayLike) -> None:
1023 if isinstance(lines, _vtk.vtkCellArray):
1024 self.SetLines(lines)
1025 else:
1026 self.SetLines(CellArray(lines))
1027
1028 @property
1029 def faces(self) -> NumpyArray[int]: # numpydoc ignore=RT01
1030 """Return the polygonal faces padded connectivity array.
1031
1032 Like all padded VTK connectivity arrays, the array is structured as::
1033
1034 [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]
1035
1036 where ``n0`` is the number of points in face 0, and ``pX_Y`` is the
1037 Y'th point in face X.
1038
1039 Faces can be :attr:`~pyvista.CellType.TRIANGLE`, :attr:`~pyvista.CellType.QUAD`,
1040 or :attr:`~pyvista.CellType.POLYGON` cells.
1041
1042 For example, a triangle and a quadrilateral might be represented as::
1043
1044 [3, 0, 1, 2, 4, 0, 1, 3, 4]
1045
1046 Where the two individual faces are ``[3, 0, 1, 2]`` and ``[4, 0, 1, 3, 4]``.
1047
1048 Faces can also be set by assigning a :class:`~pyvista.CellArray` object
1049 instead of an array.
1050
1051 Returns
1052 -------
1053 numpy.ndarray
1054 Array of face connectivity.
1055
1056 See Also
1057 --------
1058 n_faces
1059 verts, lines, strips
1060 Padded connectivity arrays for other :class:`~pyvista.PolyData` cell types.
1061 pyvista.PolyData.regular_faces, pyvista.PolyData.irregular_faces
1062 Initialize :class:`~pyvista.PolyData` from faces.
1063
1064 Notes
1065 -----
1066 The array returned cannot be modified in place and will raise a
1067 ``ValueError`` if attempted.
1068
1069 You can, however, set the faces directly. See the example.
1070
1071 Examples
1072 --------
1073 >>> import pyvista as pv
1074 >>> plane = pv.Plane(i_resolution=2, j_resolution=2)
1075 >>> plane.faces
1076 array([4, 0, 1, 4, 3, 4, 1, 2, 5, 4, 4, 3, 4, 7, 6, 4, 4, 5, 8, 7])
1077
1078 Note how the faces contain a "padding" indicating the number
1079 of points per face:
1080
1081 >>> plane.faces.reshape(-1, 5)
1082 array([[4, 0, 1, 4, 3],
1083 [4, 1, 2, 5, 4],
1084 [4, 3, 4, 7, 6],
1085 [4, 4, 5, 8, 7]])
1086
1087 Set the faces directly. The following example creates a simple plane
1088 with a single square faces and modifies it to have two triangles
1089 instead.
1090
1091 >>> mesh = pv.Plane(i_resolution=1, j_resolution=1)
1092 >>> mesh.faces = [3, 0, 1, 2, 3, 3, 2, 1]
1093 >>> mesh.faces
1094 array([3, 0, 1, 2, 3, 3, 2, 1])
1095
1096 """
1097 self.GetPolys().ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
1098 array = _vtk.vtk_to_numpy(arr)
1099 # Flag this array as read only to ensure users do not attempt to write to it.
1100 array.flags['WRITEABLE'] = False
1101 return array
1102
1103 @faces.setter
1104 def faces(self, faces: CellArrayLike) -> None:
1105 if isinstance(faces, _vtk.vtkCellArray):
1106 self.SetPolys(faces)
1107 else:
1108 # TODO: faster to mutate in-place if array is same size?
1109 self.SetPolys(CellArray(faces))
1110
1111 @property
1112 def regular_faces(self) -> NumpyArray[int]: # numpydoc ignore=RT01
1113 """Return a face array of point indices when all faces have the same size.
1114
1115 Returns
1116 -------
1117 numpy.ndarray
1118 Array of face indices with shape (n_faces, face_size).
1119
1120 See Also
1121 --------
1122 pyvista.PolyData.faces
1123
1124 Raises
1125 ------
1126 ValueError
1127 If the mesh's faces are irregular.
1128
1129 Examples
1130 --------
1131 Get the regular face array of a plane with 2x2 arrangement of cells
1132 as a 4x4 array.
1133
1134 >>> import pyvista as pv
1135 >>> plane = pv.Plane(i_resolution=2, j_resolution=2)
1136 >>> plane.regular_faces
1137 array([[0, 1, 4, 3],
1138 [1, 2, 5, 4],
1139 [3, 4, 7, 6],
1140 [4, 5, 8, 7]])
1141
1142 """
1143 regular_faces = _get_regular_cells(self.GetPolys())
1144 if len(regular_faces) != self.GetNumberOfPolys():
1145 offsets = _get_offset_array(self.GetPolys())
1146 sizes = sorted(np.unique(np.diff(offsets)).tolist())
1147 msg = (
1148 f'Mesh does not have regular faces. '
1149 f'Multiple face sizes detected with different number of points: {sizes}'
1150 )
1151 raise ValueError(msg)
1152 return regular_faces
1153
1154 @regular_faces.setter
1155 def regular_faces(self, faces: MatrixLike[int]) -> None: # numpydoc ignore=PR01
1156 """Set the face cells from an (n_faces, face_size) array."""
1157 self.faces = CellArray.from_regular_cells(faces)
1158
1159 @classmethod
1160 @_deprecate_positional_args(allowed=['points', 'faces'])
1161 def from_regular_faces(
1162 cls,
1163 points: MatrixLike[float],
1164 faces: MatrixLike[int],
1165 deep: bool = False, # noqa: FBT001, FBT002
1166 ):
1167 """Alternate `pyvista.PolyData` convenience constructor from point and regular face arrays.
1168
1169 Parameters
1170 ----------
1171 points : MatrixLike[float]
1172 A (n_points, 3) array of points.
1173
1174 faces : MatrixLike[int]
1175 A (n_faces, face_size) array of face indices. For a triangle mesh, ``face_size = 3``.
1176
1177 deep : bool, default: False
1178 Whether to deep copy the faces array into :vtk:`vtkCellArray` connectivity data.
1179
1180 Returns
1181 -------
1182 pyvista.PolyData
1183 The newly constructed mesh.
1184
1185 See Also
1186 --------
1187 pyvista.PolyData.from_irregular_faces
1188
1189 Examples
1190 --------
1191 Construct a tetrahedron from four triangles
1192
1193 >>> import pyvista as pv
1194 >>> points = [[1.0, 1, 1], [-1, 1, -1], [1, -1, -1], [-1, -1, 1]]
1195 >>> faces = [[0, 1, 2], [1, 3, 2], [0, 2, 3], [0, 3, 1]]
1196 >>> tetra = pv.PolyData.from_regular_faces(points, faces)
1197 >>> tetra.plot()
1198
1199 """
1200 return cls(points, faces=CellArray.from_regular_cells(faces, deep=deep))
1201
1202 @property
1203 def irregular_faces(self) -> tuple[NumpyArray[int], ...]: # numpydoc ignore=RT01
1204 """Return a tuple of face arrays.
1205
1206 Returns
1207 -------
1208 tuple[numpy.ndarray]
1209 Tuple of length n_faces where each element is an array of point
1210 indices for points in that face.
1211
1212 See Also
1213 --------
1214 pyvista.PolyData.faces
1215 pyvista.PolyData.regular_faces
1216
1217 Examples
1218 --------
1219 Get the face arrays of the five faces of a pyramid.
1220
1221 >>> import pyvista as pv
1222 >>> pyramid = pv.Pyramid().extract_surface(algorithm=None)
1223 >>> pyramid.irregular_faces # doctest: +NORMALIZE_WHITESPACE
1224 (array([0, 4, 3], dtype=int32),
1225 array([0, 1, 4], dtype=int32),
1226 array([0, 3, 2, 1], dtype=int32),
1227 array([1, 2, 4], dtype=int32),
1228 array([2, 3, 4], dtype=int32))
1229
1230 """
1231 return _get_irregular_cells(self.GetPolys())
1232
1233 @irregular_faces.setter
1234 def irregular_faces(self, faces: Sequence[VectorLike[int]]) -> None: # numpydoc ignore=PR01
1235 """Set the faces from a sequence of face arrays."""
1236 self.faces = CellArray.from_irregular_cells(faces) # type: ignore[arg-type]
1237
1238 @classmethod
1239 def from_irregular_faces(cls, points: MatrixLike[float], faces: Sequence[VectorLike[int]]):
1240 """Alternate `pyvista.PolyData` convenience constructor from point and ragged face arrays.
1241
1242 Parameters
1243 ----------
1244 points : MatrixLike[float]
1245 A (n_points, 3) array of points.
1246
1247 faces : Sequence[VectorLike[int]]
1248 A sequence of face vectors containing point indices.
1249
1250 Returns
1251 -------
1252 pyvista.PolyData
1253 The newly constructed mesh.
1254
1255 See Also
1256 --------
1257 pyvista.PolyData.from_regular_faces
1258
1259 Examples
1260 --------
1261 Construct a pyramid from five points and five faces
1262
1263 >>> import pyvista as pv
1264 >>> points = [
1265 ... (1, 1, 0),
1266 ... (-1, 1, 0),
1267 ... (-1, -1, 0),
1268 ... (1, -1, 0),
1269 ... (0, 0, 1.61),
1270 ... ]
1271 >>> faces = [
1272 ... (0, 1, 2, 3),
1273 ... (0, 3, 4),
1274 ... (0, 4, 1),
1275 ... (3, 2, 4),
1276 ... (2, 1, 4),
1277 ... ]
1278 >>> pyramid = pv.PolyData.from_irregular_faces(points, faces)
1279 >>> pyramid.plot()
1280
1281 """
1282 return cls(points, faces=CellArray.from_irregular_cells(faces)) # type: ignore[arg-type]
1283
1284 @property
1285 def strips(self) -> NumpyArray[int]: # numpydoc ignore=RT01
1286 """Return or set the strips padded connectivity array.
1287
1288 Like all padded VTK connectivity arrays, the array is structured as::
1289
1290 [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]
1291
1292 where ``n0`` is the number of points in strip 0, and ``pX_Y`` is the
1293 Y'th point in strip X.
1294
1295 Only the connectivity of :attr:`~pyvista.CellType.TRIANGLE_STRIP` cells is stored in this
1296 array.
1297
1298 For example, two strips with one and two triangles, respectively, might look like::
1299
1300 [3, 0, 1, 2, 4, 3, 4, 5, 6]
1301
1302 Where the individual strips are ``[3, 0, 1, 2]`` and ``[4, 3, 4, 5, 6]``.
1303
1304 Returns
1305 -------
1306 numpy.ndarray
1307 Array of strip indices.
1308
1309 See Also
1310 --------
1311 n_strips
1312 verts, lines, faces
1313 Padded connectivity arrays for other :class:`~pyvista.PolyData` cell types.
1314
1315 Examples
1316 --------
1317 >>> import pyvista as pv
1318 >>> polygon = pv.Rectangle()
1319 >>> extruded = polygon.extrude((0, 0, 1), capping=False)
1320 >>> extruded.strips
1321 array([4, 0, 1, 4, 5, 4, 1, 2, 5, 6, 4, 2, 3, 6, 7, 4, 3, 0, 7, 4])
1322 >>> extruded.n_strips
1323 4
1324
1325 """
1326 self.GetStrips().ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
1327 return _vtk.vtk_to_numpy(arr)
1328
1329 @strips.setter
1330 def strips(self, strips: CellArrayLike) -> None:
1331 if isinstance(strips, _vtk.vtkCellArray):
1332 self.SetStrips(strips)
1333 else:
1334 self.SetStrips(CellArray(strips))
1335
1336 @property
1337 def is_all_triangles(self) -> bool: # numpydoc ignore=RT01
1338 """Return if all the faces of the :class:`pyvista.PolyData` are triangles.
1339
1340 Returns
1341 -------
1342 bool
1343 ``True`` if all the faces of the :class:`pyvista.PolyData`
1344 are triangles and does not contain any vertices or lines.
1345
1346 Examples
1347 --------
1348 Show a mesh from :func:`pyvista.Plane` is not composed of all
1349 triangles.
1350
1351 >>> import pyvista as pv
1352 >>> plane = pv.Plane()
1353 >>> plane.is_all_triangles
1354 False
1355
1356 Show that the mesh from :func:`pyvista.Sphere` contains only
1357 triangles.
1358
1359 >>> sphere = pv.Sphere()
1360 >>> sphere.is_all_triangles
1361 True
1362
1363 """
1364 # Need to make sure there are only face cells and no lines/verts
1365 if not self.n_faces or self.n_lines or self.n_verts:
1366 return False
1367
1368 # early return if not all triangular
1369 if self._connectivity_array.size % 3:
1370 return False
1371
1372 # next, check if there are three points per face
1373 return bool((np.diff(self._offset_array) == 3).all())
1374
1375 def __sub__(self, cutting_mesh):
1376 """Compute boolean difference of two meshes."""
1377 return self.boolean_difference(cutting_mesh)
1378
1379 def __isub__(self, cutting_mesh):
1380 """Compute boolean difference of two meshes and update this mesh."""
1381 return self.boolean_difference(cutting_mesh)
1382
1383 def __and__(self, other_mesh):
1384 """Compute boolean intersection of two meshes."""
1385 return self.boolean_intersection(other_mesh)
1386
1387 def __or__(self, other_mesh):
1388 """Compute boolean union of two meshes."""
1389 return self.boolean_union(other_mesh)
1390
1391 @property
1392 def _offset_array(self) -> NumpyArray[int]:
1393 """Return the array used to store cell offsets."""
1394 return _get_offset_array(self.GetPolys())
1395
1396 @property
1397 def _connectivity_array(self) -> NumpyArray[int]:
1398 """Return the array with the point ids that define the cells' connectivity."""
1399 return _get_connectivity_array(self.GetPolys())
1400
1401 @property
1402 def n_lines(self) -> int: # numpydoc ignore=RT01
1403 """Return the number of line cells.
1404
1405 This is the total number of :attr:`~pyvista.CellType.LINE` and
1406 :attr:`~pyvista.CellType.POLY_LINE` cells defined in the :attr:`lines` connectivity array.
1407
1408 See Also
1409 --------
1410 lines
1411 n_verts, n_faces, n_strips
1412 Number of cells in other connectivity arrays.
1413 pyvista.DataSet.n_cells, pyvista.DataSet.n_points
1414 Number of total cells and points in this mesh.
1415
1416 Examples
1417 --------
1418 >>> import pyvista as pv
1419 >>> mesh = pv.Line()
1420 >>> mesh.n_lines, mesh.n_cells
1421 (1, 1)
1422
1423 """
1424 return self.GetNumberOfLines()
1425
1426 @property
1427 def n_verts(self) -> int: # numpydoc ignore=RT01
1428 """Return the number of vertex cells.
1429
1430 This is the total number of :attr:`~pyvista.CellType.VERTEX` and
1431 :attr:`~pyvista.CellType.POLY_VERTEX` cells defined in the :attr:`verts` connectivity
1432 array.
1433
1434 .. note::
1435 The number of vertices is separate and distinct from :attr:`~pyvista.DataSet.n_points`,
1436 as it's possible for :class:`~pyvista.PolyData` to have :attr:`~pyvista.DataSet.points`
1437 but no :attr:`verts`.
1438
1439 See Also
1440 --------
1441 verts
1442 n_lines, n_faces, n_strips
1443 Number of cells in other connectivity arrays.
1444 pyvista.DataSet.n_cells, pyvista.DataSet.n_points
1445 Number of total cells and points in this mesh.
1446
1447 Examples
1448 --------
1449 Create a simple mesh containing just two points and return the
1450 number of vertices and cells. By default, when constructing a PolyData with points but no
1451 cells, vertices are automatically created, one per point.
1452
1453 >>> import pyvista as pv
1454 >>> mesh = pv.PolyData([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
1455 >>> mesh.n_points, mesh.n_verts, mesh.n_cells
1456 (2, 2, 2)
1457
1458 If any other cells are specified, these vertices are not created.
1459
1460 >>> import pyvista as pv
1461 >>> mesh = pv.PolyData([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0]], lines=[2, 0, 1])
1462 >>> mesh.n_points, mesh.n_verts, mesh.n_cells
1463 (2, 0, 1)
1464
1465 """
1466 return self.GetNumberOfVerts()
1467
1468 @property
1469 def n_strips(self) -> int: # numpydoc ignore=RT01
1470 """Return the number of triangle strips.
1471
1472 This is the total number of :attr:`~pyvista.CellType.TRIANGLE_STRIP` cells defined in the
1473 :attr:`strips` connectivity array.
1474
1475 See Also
1476 --------
1477 strips
1478 n_verts, n_lines, n_faces
1479 Number of cells in other connectivity arrays.
1480 pyvista.DataSet.n_cells, pyvista.DataSet.n_points
1481 Number of total cells and points in this mesh.
1482
1483 Examples
1484 --------
1485 Create a simple mesh with one triangle strip and return the
1486 number of triangles.
1487
1488 >>> import pyvista as pv
1489 >>> import numpy as np
1490 >>> vertices = np.array([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
1491 >>> strip = np.array([3, 0, 1, 2])
1492 >>> mesh = pv.PolyData(vertices, strips=strip)
1493 >>> mesh.n_strips, mesh.n_cells
1494 (1, 1)
1495
1496 """
1497 return self.GetNumberOfStrips()
1498
1499 @property
1500 def n_faces(self) -> int: # numpydoc ignore=RT01
1501 """Return the number of polygonal faces.
1502
1503 This is the total number of :attr:`~pyvista.CellType.TRIANGLE`,
1504 :attr:`~pyvista.CellType.QUAD`, and :attr:`~pyvista.CellType.POLYGON` cells defined in
1505 the :attr:`faces` connectivity array.
1506
1507 See Also
1508 --------
1509 faces
1510 n_verts, n_lines, n_strips
1511 Number of cells in other connectivity arrays.
1512 pyvista.DataSet.n_cells, pyvista.DataSet.n_points
1513 Number of total cells and points in this mesh.
1514
1515 Examples
1516 --------
1517 Create a mesh with one face and one line
1518
1519 >>> import pyvista as pv
1520 >>> mesh = pv.PolyData(
1521 ... [(0.0, 0, 0), (1, 0, 0), (0, 1, 0)],
1522 ... faces=[3, 0, 1, 2],
1523 ... lines=[2, 0, 1],
1524 ... )
1525 >>> mesh.n_cells, mesh.n_faces, mesh.n_lines
1526 (2, 1, 1)
1527
1528 """
1529 return self.GetNumberOfPolys()
1530
1531 @property
1532 def n_faces_strict(self) -> int: # numpydoc ignore=RT01
1533 """Return the number of polygonal faces.
1534
1535 .. deprecated:: 0.49
1536 Use :attr:`n_faces` instead. As of v0.49, :attr:`n_faces` returns the
1537 number of polygonal faces, identical to ``n_faces_strict``.
1538
1539 """
1540 # Deprecated on 0.49.0, estimated removal on 0.51.0
1541 warn_external(
1542 '`n_faces_strict` is deprecated. Use `n_faces` instead, '
1543 'which now returns the number of polygonal faces.',
1544 PyVistaDeprecationWarning,
1545 )
1546 return self.GetNumberOfPolys()
1547
1548 @_deprecate_positional_args(allowed=['filename'])
1549 def save( # type: ignore[override] # noqa: PLR0917
1550 self,
1551 filename: Path | str,
1552 binary: bool = True, # noqa: FBT001, FBT002
1553 texture: NumpyArray[np.uint8] | str | None = None,
1554 recompute_normals: bool = True, # noqa: FBT001, FBT002
1555 compression: _CompressionOptions = 'zlib',
1556 **writer_kwargs: Any,
1557 ) -> None:
1558 """Write a surface mesh to disk.
1559
1560 Written file may be an ASCII or binary ply, stl, or vtk mesh
1561 file.
1562
1563 Parameters
1564 ----------
1565 filename : str, Path
1566 Filename of mesh to be written. File type is inferred from
1567 the extension of the filename unless overridden with
1568 ftype. Can be one of many of the supported the following
1569 types (``'.ply'``, ``'.vtp'``, ``'.stl'``, ``'.vtk``, ``'.geo'``,
1570 ``'.obj'``, ``'.iv'``).
1571
1572 binary : bool, default: True
1573 Writes the file as binary when ``True`` and ASCII when ``False``.
1574
1575 texture : str, numpy.ndarray, optional
1576 Write a single texture array to file when using a PLY
1577 file. Texture array must be a 3 or 4 component array with
1578 the datatype ``np.uint8``. Array may be a cell array or a
1579 point array, and may also be a string if the array already
1580 exists in the PolyData.
1581
1582 If a string is provided, the texture array will be saved
1583 to disk as that name. If an array is provided, the
1584 texture array will be saved as ``'RGBA'`` if the array
1585 contains an alpha channel (i.e. 4 component array), or
1586 as ``'RGB'`` if the array is just a 3 component array.
1587
1588 .. note::
1589 This feature is only available when saving PLY files.
1590
1591 recompute_normals : bool, default: True
1592 When ``True``, if ply or stl format is chosen, the face normals
1593 are computed in place to ensure the mesh is properly saved.
1594 Set this to ``False`` to save instead the already existing normal
1595 array in the PolyData.
1596
1597 compression : str or None, default: 'zlib'
1598 The compression type to use when ``binary`` is ``True``
1599 and VTK writer is of type :vtk:`vtkXMLWriter`. This
1600 argument has no effect otherwise. Acceptable values are
1601 ``'zlib'``, ``'lz4'``, ``'lzma'``, and ``None``. ``None``
1602 indicates no compression.
1603
1604 .. versionadded:: 0.47
1605
1606 **writer_kwargs : dict, optional
1607 Additional keyword arguments forwarded verbatim to a custom
1608 writer registered via :func:`pyvista.register_writer`. When
1609 the target extension dispatches to a built-in VTK writer or
1610 to the pickle path, passing any extra keyword arguments
1611 raises :class:`TypeError`.
1612
1613 .. versionadded:: 0.48
1614
1615 Notes
1616 -----
1617 Binary files write much faster than ASCII and have a smaller
1618 file size.
1619
1620 Examples
1621 --------
1622 Save a mesh as a STL.
1623
1624 >>> import pyvista as pv
1625 >>> sphere = pv.Sphere()
1626 >>> sphere.save('my_mesh.stl') # doctest:+SKIP
1627
1628 Save a mesh as a PLY.
1629
1630 >>> sphere = pv.Sphere()
1631 >>> sphere.save('my_mesh.ply') # doctest:+SKIP
1632
1633 Save a mesh as a PLY with a texture array. Here we also
1634 create a simple RGB array representing the texture.
1635
1636 >>> import numpy as np
1637 >>> sphere = pv.Sphere()
1638 >>> texture = np.zeros((sphere.n_points, 3), np.uint8)
1639 >>> # Just the green channel is set as a repeatedly
1640 >>> # decreasing value
1641 >>> texture[:, 1] = np.arange(sphere.n_points)[::-1]
1642 >>> sphere.point_data['my_texture'] = texture
1643 >>> sphere.save('my_mesh.ply', texture='my_texture') # doctest:+SKIP
1644
1645 Alternatively, provide just the texture array. This will be
1646 written to the file as ``'RGB'`` since it does not contain an
1647 alpha channel.
1648
1649 >>> sphere.save('my_mesh.ply', texture=texture) # doctest:+SKIP
1650
1651 Save a mesh as a VTK file.
1652
1653 >>> sphere = pv.Sphere()
1654 >>> sphere.save('my_mesh.vtk') # doctest:+SKIP
1655
1656 """
1657 filename = Path(filename).expanduser().resolve()
1658 ftype = get_ext(filename)
1659 # Recompute normals prior to save. Corrects a bug were some
1660 # triangular meshes are not saved correctly
1661 if ftype in ['.stl', '.ply'] and recompute_normals:
1662 with contextlib.suppress(TypeError):
1663 self.compute_normals(inplace=True)
1664 super().save(
1665 filename,
1666 binary=binary,
1667 texture=texture,
1668 compression=compression,
1669 **writer_kwargs,
1670 )
1671
1672 @property
1673 def volume(self) -> float: # numpydoc ignore=RT01
1674 """Return the approximate volume of the dataset.
1675
1676 This will throw a VTK error/warning if not a closed surface.
1677
1678 Returns
1679 -------
1680 float
1681 Total volume of the mesh.
1682
1683 Examples
1684 --------
1685 >>> import pyvista as pv
1686 >>> sphere = pv.Sphere()
1687 >>> sphere.volume
1688 0.5183
1689
1690 """
1691 mprop = _vtk.vtkMassProperties()
1692 mprop.SetInputData(self.triangulate())
1693 return mprop.GetVolume()
1694
1695 @property
1696 def point_normals(self) -> pv.pyvista_ndarray: # numpydoc ignore=RT01
1697 """Return the point normals.
1698
1699 The active point normals are returned if they exist. Otherwise, they
1700 are computed with :func:`~pyvista.PolyDataFilters.compute_normals`
1701 using the default options.
1702
1703 Returns
1704 -------
1705 pyvista.pyvista_ndarray
1706 Array of point normals.
1707
1708 Examples
1709 --------
1710 >>> import pyvista as pv
1711 >>> sphere = pv.Sphere()
1712 >>> sphere.point_normals
1713 pyvista_ndarray([[ 0. , 0. , 1. ],
1714 [ 0. , 0. , -1. ],
1715 [ 0.10811902, 0. , 0.99413794],
1716 ...,
1717 [ 0.31232402, -0.06638652, -0.9476532 ],
1718 [ 0.21027282, -0.04469487, -0.97662055],
1719 [ 0.10575636, -0.02247921, -0.99413794]],
1720 shape=(842, 3), dtype=float32)
1721
1722 """
1723 if self.point_data.active_normals is not None:
1724 normals = self.point_data.active_normals
1725 else:
1726 normals = self.compute_normals(cell_normals=False, inplace=False).point_data['Normals']
1727 return normals
1728
1729 @property
1730 def cell_normals(self) -> pv.pyvista_ndarray: # numpydoc ignore=RT01
1731 """Return the cell normals.
1732
1733 The active cell normals are returned if they exist. Otherwise, they
1734 are computed with :func:`~pyvista.PolyDataFilters.compute_normals`
1735 using the default options.
1736
1737 Returns
1738 -------
1739 pyvista.pyvista_ndarray
1740 Array of cell normals.
1741
1742 Examples
1743 --------
1744 >>> import pyvista as pv
1745 >>> sphere = pv.Sphere()
1746 >>> sphere.cell_normals
1747 pyvista_ndarray([[ 0.05413816, 0.00569015, 0.9985172 ],
1748 [ 0.05177207, 0.01682176, 0.9985172 ],
1749 [ 0.04714328, 0.02721819, 0.9985172 ],
1750 ...,
1751 [ 0.26742265, -0.02810723, -0.96316934],
1752 [ 0.1617585 , -0.01700151, -0.9866839 ],
1753 [ 0.1617585 , -0.01700151, -0.9866839 ]],
1754 shape=(1680, 3), dtype=float32)
1755
1756 """
1757 if self.cell_data.active_normals is not None:
1758 normals = self.cell_data.active_normals
1759 else:
1760 normals = self.compute_normals(point_normals=False, inplace=False).cell_data['Normals']
1761 return normals
1762
1763 @property
1764 def face_normals(self) -> pv.pyvista_ndarray: # numpydoc ignore=RT01
1765 """Return the cell normals.
1766
1767 Alias to :func:`PolyData.cell_normals`.
1768
1769 Returns
1770 -------
1771 pyvista.pyvista_ndarray
1772 Array of face normals.
1773
1774 Examples
1775 --------
1776 >>> import pyvista as pv
1777 >>> sphere = pv.Sphere()
1778 >>> sphere.face_normals
1779 pyvista_ndarray([[ 0.05413816, 0.00569015, 0.9985172 ],
1780 [ 0.05177207, 0.01682176, 0.9985172 ],
1781 [ 0.04714328, 0.02721819, 0.9985172 ],
1782 ...,
1783 [ 0.26742265, -0.02810723, -0.96316934],
1784 [ 0.1617585 , -0.01700151, -0.9866839 ],
1785 [ 0.1617585 , -0.01700151, -0.9866839 ]],
1786 shape=(1680, 3), dtype=float32)
1787
1788 """
1789 return self.cell_normals
1790
1791 @cached_property
1792 def obbTree(self) -> _vtk.vtkOBBTree: # noqa: N802 # numpydoc ignore=RT01
1793 """Return the obbTree of the polydata.
1794
1795 An obbTree is an object to generate oriented bounding box (OBB)
1796 trees. An oriented bounding box is a bounding box that does not
1797 necessarily line up along coordinate axes. The OBB tree is a
1798 hierarchical tree structure of such boxes, where deeper levels of OBB
1799 confine smaller regions of space.
1800
1801 .. warning::
1802
1803 This property is expensive to compute and is therefore cached. If the mesh's
1804 geometry is modified, the obb tree will no longer be valid.
1805
1806 """
1807 if self.n_points < 1 or self.n_cells < 1:
1808 msg = 'Building the OBB tree requires PolyData with points and cells.'
1809 raise ValueError(msg)
1810 obb_tree = _vtk.vtkOBBTree()
1811 obb_tree.SetDataSet(self)
1812 obb_tree.BuildLocator()
1813 return obb_tree
1814
1815 @property
1816 def n_open_edges(self) -> int: # numpydoc ignore=RT01
1817 """Return the number of open edges on this mesh.
1818
1819 Examples
1820 --------
1821 Return the number of open edges on a sphere.
1822
1823 >>> import pyvista as pv
1824 >>> sphere = pv.Sphere()
1825 >>> sphere.n_open_edges
1826 0
1827
1828 Return the number of open edges on a plane.
1829
1830 >>> plane = pv.Plane(i_resolution=1, j_resolution=1)
1831 >>> plane.n_open_edges
1832 4
1833
1834 """
1835 alg = _vtk.vtkFeatureEdges()
1836 alg.FeatureEdgesOff()
1837 alg.BoundaryEdgesOn()
1838 alg.NonManifoldEdgesOn()
1839 alg.SetInputDataObject(self)
1840 alg.Update()
1841 return alg.GetOutput().GetNumberOfCells()
1842
1843 @property
1844 def is_manifold(self) -> bool: # numpydoc ignore=RT01
1845 """Return if the mesh is manifold (no open edges).
1846
1847 Examples
1848 --------
1849 Show a sphere is manifold.
1850
1851 >>> import pyvista as pv
1852 >>> pv.Sphere().is_manifold
1853 True
1854
1855 Show a plane is not manifold.
1856
1857 >>> pv.Plane().is_manifold
1858 False
1859
1860 """
1861 return self.n_open_edges == 0
1862
1863 def __del__(self) -> None:
1864 """Delete the object."""
1865 # avoid a reference cycle that can't be resolved with vtkPolyData
1866 self._glyph_geom = None
1867 with contextlib.suppress(KeyError):
1868 del self.__dict__['obbTree']
1869
1870
1871 @abstract_class
1872 class PointGrid(_PointSet):
1873 """Class in common with structured and unstructured grids."""
1874
1875 def __init__(self, *args, **kwargs) -> None: # noqa: ARG002
1876 """Initialize the point grid."""
1877 super().__init__()
1878
1879 def plot_curvature(self: Self, curv_type='mean', **kwargs):
1880 """Plot the curvature of the external surface of the grid.
1881
1882 Parameters
1883 ----------
1884 curv_type : str, default: "mean"
1885 One of the following strings indicating curvature types.
1886 - ``'mean'``
1887 - ``'gaussian'``
1888 - ``'maximum'``
1889 - ``'minimum'``
1890
1891 **kwargs : dict, optional
1892 Optional keyword arguments. See :func:`pyvista.plot`.
1893
1894 Returns
1895 -------
1896 list
1897 Camera position, focal point, and view up. Returned when
1898 ``return_cpos`` is ``True``.
1899
1900 """
1901 trisurf = self.extract_surface(
1902 algorithm=None, pass_cellid=False, pass_pointid=False
1903 ).triangulate()
1904 return trisurf.plot_curvature(curv_type, **kwargs)
1905
1906
1907 class UnstructuredGrid(PointGrid, UnstructuredGridFilters, _vtk.vtkUnstructuredGrid):
1908 """Dataset used for arbitrary combinations of all possible cell types.
1909
1910 Can be initialized by the following:
1911
1912 - Creating an empty grid
1913 - From a :vtk:`vtkPolyData` or :vtk:`vtkStructuredGrid` object
1914 - From cell, cell types, and point arrays
1915 - From a file
1916
1917 Parameters
1918 ----------
1919 args : str, :vtk:`vtkUnstructuredGrid`, iterable
1920 See examples below.
1921
1922 deep : bool, default: False
1923 Whether to deep copy a :vtk:`vtkUnstructuredGrid` object.
1924 Default is ``False``. Keyword only.
1925
1926 validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False
1927 Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after
1928 initialization. Set this to ``True`` to validate all fields, or specify any
1929 combination of fields allowed by ``validate_mesh``.
1930
1931 .. versionadded:: 0.47
1932
1933 Examples
1934 --------
1935 >>> import pyvista as pv
1936 >>> from pyvista import examples
1937 >>> import vtk
1938
1939 Create an empty grid
1940
1941 >>> grid = pv.UnstructuredGrid()
1942
1943 Copy a :vtk:`vtkUnstructuredGrid`
1944
1945 >>> vtkgrid = vtk.vtkUnstructuredGrid()
1946 >>> grid = pv.UnstructuredGrid(vtkgrid)
1947
1948 From a filename.
1949
1950 >>> grid = pv.UnstructuredGrid(examples.hexbeamfile)
1951 >>> grid.plot(show_edges=True)
1952
1953 From arrays. Here we create a single tetrahedron.
1954
1955 >>> cells = [4, 0, 1, 2, 3]
1956 >>> celltypes = [pv.CellType.TETRA]
1957 >>> points = [
1958 ... [1.0, 1.0, 1.0],
1959 ... [1.0, -1.0, -1.0],
1960 ... [-1.0, 1.0, -1.0],
1961 ... [-1.0, -1.0, 1.0],
1962 ... ]
1963 >>> grid = pv.UnstructuredGrid(cells, celltypes, points)
1964 >>> grid.plot(show_edges=True)
1965
1966 See the :ref:`create_unstructured_surface_example` example for more details
1967 on creating unstructured grids within PyVista.
1968
1969 """
1970
1971 _WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {
1972 '.vtu': XMLUnstructuredGridWriter,
1973 '.vtk': UnstructuredGridWriter,
1974 }
1975 if vtk_version_info >= (9, 4):
1976 _WRITERS['.vtkhdf'] = HDFWriter
1977
1978 def __init__(
1979 self,
1980 *args,
1981 deep: bool = False,
1982 validate: bool | _NestedMeshValidationFields = False,
1983 **kwargs,
1984 ) -> None:
1985 """Initialize the unstructured grid."""
1986 super().__init__()
1987
1988 if not args:
1989 return
1990 if len(args) == 1:
1991 if isinstance(args[0], _vtk.vtkUnstructuredGrid):
1992 if deep:
1993 self.deep_copy(args[0])
1994 else:
1995 self.shallow_copy(args[0]) # type: ignore[arg-type]
1996
1997 elif isinstance(args[0], (str, Path)):
1998 self._from_file(args[0], **kwargs)
1999
2000 elif isinstance(args[0], (_vtk.vtkStructuredGrid, _vtk.vtkPolyData)):
2001 vtkappend = _vtk.vtkAppendFilter()
2002 vtkappend.AddInputData(args[0])
2003 vtkappend.Update()
2004 self.shallow_copy(vtkappend.GetOutput())
2005
2006 else:
2007 itype = type(args[0])
2008 msg = f'Cannot work with input type {itype}'
2009 raise TypeError(msg)
2010
2011 # Cell dictionary creation
2012 elif len(args) == 2 and isinstance(args[0], dict) and isinstance(args[1], np.ndarray):
2013 self._from_cells_dict(args[0], args[1], deep=deep)
2014 self._check_for_consistency()
2015
2016 elif len(args) == 3:
2017 arg0_is_seq = isinstance(args[0], (np.ndarray, Sequence))
2018 arg1_is_seq = isinstance(args[1], (np.ndarray, Sequence))
2019 arg2_is_seq = isinstance(args[2], (np.ndarray, Sequence))
2020
2021 if all([arg0_is_seq, arg1_is_seq, arg2_is_seq]):
2022 self._from_arrays(args[0], args[1], args[2], deep=deep, **kwargs)
2023 self._check_for_consistency()
2024 else:
2025 msg = 'All input types must be sequences.'
2026 raise TypeError(msg)
2027 else:
2028 msg = (
2029 'Invalid parameters. Initialization with arrays requires the '
2030 'following arrays:\n`cells`, `cell_type`, `points`'
2031 )
2032 raise TypeError(msg)
2033
2034 if validate:
2035 self._validate_mesh(validate)
2036
2037 def __repr__(self):
2038 """Return the standard representation."""
2039 return DataSet.__repr__(self)
2040
2041 def __str__(self):
2042 """Return the standard str representation."""
2043 return DataSet.__str__(self)
2044
2045 def _from_cells_dict(self, cells_dict, points, *, deep: bool = True):
2046 if points.ndim != 2 or points.shape[-1] != 3:
2047 msg = 'Points array must be a [M, 3] array'
2048 raise ValueError(msg)
2049
2050 nr_points = points.shape[0]
2051 cell_types, cells = create_mixed_cells(cells_dict, nr_points)
2052 self._from_arrays(cells, cell_types, points, deep=deep)
2053
2054 def _from_arrays(
2055 self,
2056 cells,
2057 cell_type,
2058 points,
2059 *,
2060 deep: bool = True,
2061 force_float: bool = True,
2062 ) -> None:
2063 """Create VTK unstructured grid from numpy arrays.
2064
2065 Parameters
2066 ----------
2067 cells : sequence[int]
2068 Array of cells. Each cell contains the number of points in the
2069 cell and the node numbers of the cell.
2070
2071 cell_type : sequence[int]
2072 Cell types of each cell. Each cell type numbers can be found from
2073 vtk documentation. More efficient if using ``np.uint8``. See
2074 example below.
2075
2076 points : sequence[float]
2077 Numpy array containing point locations.
2078
2079 deep : bool, default: True
2080 When ``True``, makes a copy of the points array. Default
2081 ``False``. Cells and cell types are always copied.
2082
2083 force_float : bool, default: True
2084 Casts the datatype to ``float32`` if points datatype is
2085 non-float. Set this to ``False`` to allow non-float types,
2086 though this may lead to truncation of intermediate floats when
2087 transforming datasets.
2088
2089 Examples
2090 --------
2091 >>> import numpy as np
2092 >>> from pyvista import CellType
2093 >>> import pyvista as pv
2094 >>> cell0_ids = [8, 0, 1, 2, 3, 4, 5, 6, 7]
2095 >>> cell1_ids = [8, 8, 9, 10, 11, 12, 13, 14, 15]
2096 >>> cells = np.hstack((cell0_ids, cell1_ids))
2097 >>> cell_type = np.array([CellType.HEXAHEDRON, CellType.HEXAHEDRON], np.int8)
2098
2099 >>> cell1 = np.array(
2100 ... [
2101 ... [0, 0, 0],
2102 ... [1, 0, 0],
2103 ... [1, 1, 0],
2104 ... [0, 1, 0],
2105 ... [0, 0, 1],
2106 ... [1, 0, 1],
2107 ... [1, 1, 1],
2108 ... [0, 1, 1],
2109 ... ],
2110 ... dtype=np.float32,
2111 ... )
2112
2113 >>> cell2 = np.array(
2114 ... [
2115 ... [0, 0, 2],
2116 ... [1, 0, 2],
2117 ... [1, 1, 2],
2118 ... [0, 1, 2],
2119 ... [0, 0, 3],
2120 ... [1, 0, 3],
2121 ... [1, 1, 3],
2122 ... [0, 1, 3],
2123 ... ],
2124 ... dtype=np.float32,
2125 ... )
2126
2127 >>> points = np.vstack((cell1, cell2))
2128
2129 >>> grid = pv.UnstructuredGrid(cells, cell_type, points)
2130
2131 """
2132 # convert to arrays upfront
2133 cells = np.asarray(cells)
2134 cell_type = np.asarray(cell_type)
2135 points = np.asarray(points)
2136
2137 # Convert to vtk arrays
2138 vtkcells = CellArray(cells)
2139 if cell_type.dtype != np.uint8:
2140 cell_type = cell_type.astype(np.uint8)
2141 cell_type = _vtk.numpy_to_vtk(cell_type, deep=deep)
2142
2143 points = vtk_points(points, deep=deep, force_float=force_float)
2144 self.SetPoints(points)
2145
2146 self.SetCells(cell_type, vtkcells)
2147
2148 def _check_for_consistency(self):
2149 """Check if size of offsets and celltypes match the number of cells.
2150
2151 Checks if the number of offsets and celltypes correspond to
2152 the number of cells. Called after initialization of the self
2153 from arrays.
2154 """
2155 if self.n_cells != self.celltypes.size:
2156 msg = (
2157 f'Number of cell types ({self.celltypes.size}) '
2158 f'must match the number of cells {self.n_cells})'
2159 )
2160 raise ValueError(msg)
2161
2162 if self.n_cells != self.offset.size - 1: # pragma: no cover
2163 msg = (
2164 f'Size of the offset ({self.offset.size}) '
2165 f'must be one greater than the number of cells ({self.n_cells})'
2166 )
2167 raise ValueError(msg)
2168
2169 @property
2170 def cells(self) -> NumpyArray[int]: # numpydoc ignore=RT01
2171 """Return the cell data as a numpy object.
2172
2173 This is the old style VTK data layout::
2174
2175 [n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ...]
2176
2177 where ``n0`` is the number of points in cell 0, and ``pX_Y`` is the
2178 Y'th point in cell X.
2179
2180 For example, a triangle and a line might be represented as::
2181
2182 [3, 0, 1, 2, 2, 0, 1]
2183
2184 Where the two individual cells would be ``[3, 0, 1, 2]`` and ``[2, 0, 1]``.
2185
2186 See Also
2187 --------
2188 pyvista.DataSet.get_cell
2189 pyvista.UnstructuredGrid.cell_connectivity
2190 pyvista.UnstructuredGrid.offset
2191
2192 Notes
2193 -----
2194 The array returned cannot be modified in place and will raise a
2195 ``ValueError`` if attempted.
2196
2197 You can, however, set the cells directly. See the example.
2198
2199 Examples
2200 --------
2201 Return the indices of the first two cells from the example hex
2202 beam. Note how the cells have "padding" indicating the number
2203 of points per cell.
2204
2205 >>> import pyvista as pv
2206 >>> from pyvista import examples
2207 >>> grid = examples.load_hexbeam()
2208 >>> grid.cells[:18]
2209 array([ 8, 0, 2, 8, 7, 27, 36, 90, 81, 8, 2, 1, 4, 8, 36, 18, 54,
2210 90])
2211
2212 While you cannot change the array inplace, you can overwrite it. For example:
2213
2214 >>> grid.cells = [8, 0, 1, 2, 3, 4, 5, 6, 7]
2215
2216 """
2217 # Flag this array as read only to ensure users do not attempt to write to it.
2218 self._get_cells().ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
2219 array = _vtk.vtk_to_numpy(arr)
2220 array.flags['WRITEABLE'] = False
2221 return array
2222
2223 @cells.setter
2224 def cells(self, cells) -> None:
2225 vtk_idarr = numpy_to_idarr(cells, deep=False, return_ind=False)
2226 self._get_cells().ImportLegacyFormat(vtk_idarr)
2227
2228 def _get_cells(self) -> _vtk.vtkCellArray:
2229 cells = self.GetCells()
2230 return _vtk.vtkCellArray() if cells is None else cells # type: ignore[redundant-expr]
2231
2232 @property
2233 def faces(self) -> NumpyArray[int]:
2234 """Return the polyhedron faces.
2235
2236 .. deprecated:: 0.45.0
2237 This property is deprecated and will be removed in a future release.
2238 VTK has deprecated `GetFaces` and `GetFaceLocations` in VTK 9.4 and
2239 may be removed in a future release of VTK. Please use
2240 `polyhedral_faces` instead.
2241
2242 Returns
2243 -------
2244 numpy.ndarray
2245 Array of faces.
2246
2247 """
2248 return convert_array(self.GetFaces())
2249
2250 @property
2251 def polyhedron_faces(self) -> NumpyArray[int]:
2252 """Return the polyhedron faces.
2253
2254 Returns
2255 -------
2256 numpy.ndarray
2257 Array of faces.
2258
2259 """
2260 if pv.vtk_version_info < (9, 4):
2261 polyhedron_faces = pv.convert_array(self.GetFaces())
2262
2263 if polyhedron_faces is None:
2264 return np.array([], dtype=int)
2265
2266 cell_faces = []
2267 i = 0
2268
2269 while i < len(polyhedron_faces):
2270 faces_: list[VectorLike[int]] = []
2271 n_faces = polyhedron_faces[i]
2272 i += 1
2273
2274 while len(faces_) < n_faces:
2275 n_vertices = polyhedron_faces[i]
2276 faces_.append([n_vertices, *polyhedron_faces[i + 1 : i + 1 + n_vertices]])
2277 i += n_vertices + 1
2278
2279 cell_faces.append(np.concatenate(faces_))
2280
2281 return np.concatenate(cell_faces)
2282
2283 else:
2284 faces = self.GetPolyhedronFaces() # vtkCellArray
2285 if faces is None:
2286 return np.array([], dtype=int) # type: ignore[unreachable]
2287
2288 faces.ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
2289 return convert_array(arr)
2290
2291 @property
2292 def face_locations(self) -> NumpyArray[int]:
2293 """Return polyhedron face locations.
2294
2295 .. deprecated:: 0.45.0
2296 This property is deprecated and will be removed in a future release.
2297 VTK has deprecated `GetFaces` and `GetFaceLocations` in VTK 9.4 and
2298 may be removed in a future release of VTK. Please use
2299 `polyhedral_face_locations` instead.
2300
2301 Returns
2302 -------
2303 numpy.ndarray
2304 Array of face locations.
2305
2306 """
2307 return convert_array(self.GetFaceLocations())
2308
2309 @property
2310 def polyhedron_face_locations(self) -> NumpyArray[int]:
2311 """Return the polyhedron face locations.
2312
2313 Returns
2314 -------
2315 numpy.ndarray
2316 Array of faces.
2317
2318 """
2319 if pv.vtk_version_info < (9, 4):
2320 polyhedron_faces = pv.convert_array(self.GetFaces())
2321
2322 if polyhedron_faces is None:
2323 return np.array([], dtype=int)
2324
2325 i, face_counts = 0, []
2326
2327 while i < len(polyhedron_faces):
2328 n_faces = polyhedron_faces[i]
2329 face_counts.append(n_faces)
2330 face_count = 0
2331 i += 1
2332
2333 while face_count < n_faces:
2334 i += polyhedron_faces[i] + 1
2335 face_count += 1
2336
2337 locations = [[0]] * self.n_cells
2338 face_count = 0
2339
2340 for i, n_faces in zip(
2341 np.flatnonzero(self.celltypes == pv.CellType.POLYHEDRON),
2342 face_counts,
2343 strict=True,
2344 ):
2345 locations[i] = [n_faces, *(np.arange(n_faces) + face_count)]
2346 face_count += n_faces
2347
2348 return np.concatenate(locations)
2349
2350 else:
2351 faces = self.GetPolyhedronFaceLocations() # vtkCellArray
2352 if faces is None:
2353 return np.array([], dtype=int) # type: ignore[unreachable]
2354
2355 faces.ExportLegacyFormat(arr := _vtk.vtkIdTypeArray())
2356 return convert_array(arr)
2357
2358 @property
2359 def cells_dict(self) -> dict[np.uint8, NumpyArray[int]]: # numpydoc ignore=RT01
2360 """Return a dictionary that contains all cells mapped from cell types.
2361
2362 This function returns a :class:`numpy.ndarray` for each cell
2363 type in an ordered fashion. Note that this function only
2364 works with element types of fixed sizes.
2365
2366 .. versionchanged:: 0.46
2367
2368 An empty dict ``{}`` is returned instead of ``None`` if
2369 the input is empty.
2370
2371 Returns
2372 -------
2373 dict
2374 A dictionary mapping containing all cells of this unstructured grid.
2375 Structure: vtk_enum_type (int) -> cells (:class:`numpy.ndarray`).
2376
2377 See Also
2378 --------
2379 pyvista.DataSet.get_cell
2380
2381 Examples
2382 --------
2383 Return the cells dictionary of the sample hex beam. Note how
2384 there is only one key/value pair as the hex beam example is
2385 composed of only all hexahedral cells, which is
2386 ``CellType.HEXAHEDRON``, which evaluates to 12.
2387
2388 Also note how there is no padding for the cell array. This
2389 approach may be more helpful than the ``cells`` property when
2390 extracting cells.
2391
2392 >>> import pyvista as pv
2393 >>> from pyvista import examples
2394 >>> hex_beam = pv.read(examples.hexbeamfile)
2395 >>> hex_beam.cells_dict # doctest:+SKIP
2396 {12: array([[ 0, 2, 8, 7, 27, 36, 90, 81],
2397 [ 2, 1, 4, 8, 36, 18, 54, 90],
2398 [ 7, 8, 6, 5, 81, 90, 72, 63],
2399 ...
2400 [44, 26, 62, 98, 11, 10, 13, 17],
2401 [89, 98, 80, 71, 16, 17, 15, 14],
2402 [98, 62, 53, 80, 17, 13, 12, 15]])}
2403
2404 """
2405 return get_mixed_cells(self)
2406
2407 @property
2408 def cell_connectivity(self) -> NumpyArray[int]: # numpydoc ignore=RT01
2409 """Return the cell connectivity as a numpy array.
2410
2411 This is effectively :attr:`UnstructuredGrid.cells` without the
2412 padding.
2413
2414 Returns
2415 -------
2416 numpy.ndarray
2417 Connectivity array.
2418
2419 See Also
2420 --------
2421 pyvista.DataSet.get_cell
2422
2423 Examples
2424 --------
2425 Return the cell connectivity for the first two cells.
2426
2427 >>> import pyvista as pv
2428 >>> from pyvista import examples
2429 >>> hex_beam = pv.read(examples.hexbeamfile)
2430 >>> hex_beam.cell_connectivity[:16]
2431 array([ 0, 2, 8, 7, 27, 36, 90, 81, 2, 1, 4, 8, 36, 18, 54, 90])
2432
2433 """
2434 carr = self._get_cells()
2435 return _vtk.vtk_to_numpy(carr.GetConnectivityArray())
2436
2437 @_deprecate_positional_args
2438 def linear_copy(self, deep: bool = False): # noqa: FBT001, FBT002
2439 """Return a copy of the unstructured grid containing only linear cells.
2440
2441 Converts the following cell types to their linear equivalents.
2442
2443 - :attr:`~pyvista.CellType.QUADRATIC_TRIANGLE` --> :attr:`~pyvista.CellType.TRIANGLE`
2444 - :attr:`~pyvista.CellType.QUADRATIC_QUAD` --> :attr:`~pyvista.CellType.QUAD`
2445 - :attr:`~pyvista.CellType.QUADRATIC_TETRA` --> :attr:`~pyvista.CellType.TETRA`
2446 - :attr:`~pyvista.CellType.QUADRATIC_PYRAMID` --> :attr:`~pyvista.CellType.PYRAMID`
2447 - :attr:`~pyvista.CellType.QUADRATIC_WEDGE` --> :attr:`~pyvista.CellType.WEDGE`
2448 - :attr:`~pyvista.CellType.QUADRATIC_HEXAHEDRON` --> :attr:`~pyvista.CellType.HEXAHEDRON`
2449
2450 Parameters
2451 ----------
2452 deep : bool, default: False
2453 When ``True``, makes a copy of the points array.
2454 Cells and cell types are always copied.
2455
2456 Returns
2457 -------
2458 pyvista.UnstructuredGrid
2459 UnstructuredGrid containing only linear cells when
2460 ``deep=False``.
2461
2462 """
2463 lgrid = self.copy(deep=deep)
2464
2465 # grab the vtk object
2466 vtk_cell_type = _vtk.numpy_to_vtk(self._get_cell_types_array(), deep=True)
2467 celltype = _vtk.vtk_to_numpy(vtk_cell_type)
2468 celltype[celltype == CellType.QUADRATIC_TETRA] = CellType.TETRA
2469 celltype[celltype == CellType.QUADRATIC_PYRAMID] = CellType.PYRAMID
2470 celltype[celltype == CellType.QUADRATIC_WEDGE] = CellType.WEDGE
2471 celltype[celltype == CellType.QUADRATIC_HEXAHEDRON] = CellType.HEXAHEDRON
2472
2473 # track quad mask for later
2474 quad_quad_mask = celltype == CellType.QUADRATIC_QUAD
2475 celltype[quad_quad_mask] = CellType.QUAD
2476
2477 quad_tri_mask = celltype == CellType.QUADRATIC_TRIANGLE
2478 celltype[quad_tri_mask] = CellType.TRIANGLE
2479
2480 cells = _vtk.vtkCellArray()
2481 cells.DeepCopy(self._get_cells())
2482 if pv.vtk_version_info >= (9, 5):
2483 face_locations = self.GetPolyhedronFaceLocations()
2484 faces = self.GetPolyhedronFaces()
2485 lgrid.SetPolyhedralCells(vtk_cell_type, cells, face_locations, faces)
2486 else:
2487 vtk_offset = self.GetCellLocationsArray()
2488 lgrid.SetCells(vtk_cell_type, vtk_offset, cells)
2489
2490 # fixing bug with display of quad cells.
2491 # Cache the cell_connectivity array once as each access wraps the
2492 # underlying vtkCellArray's connectivity buffer with vtk_to_numpy,
2493 # so reading it 4-7 times in the loop redundantly allocates wrappers.
2494 if np.any(quad_quad_mask) or np.any(quad_tri_mask):
2495 cell_offsets = lgrid.offset
2496 cell_conn = lgrid.cell_connectivity
2497
2498 if np.any(quad_quad_mask):
2499 quad_offset = cell_offsets[:-1][quad_quad_mask]
2500 base_point = cell_conn[quad_offset]
2501 cell_conn[quad_offset + 4] = base_point
2502 cell_conn[quad_offset + 5] = base_point
2503 cell_conn[quad_offset + 6] = base_point
2504 cell_conn[quad_offset + 7] = base_point
2505
2506 if np.any(quad_tri_mask):
2507 tri_offset = cell_offsets[:-1][quad_tri_mask]
2508 base_point = cell_conn[tri_offset]
2509 cell_conn[tri_offset + 3] = base_point
2510 cell_conn[tri_offset + 4] = base_point
2511 cell_conn[tri_offset + 5] = base_point
2512
2513 return lgrid
2514
2515 @property
2516 def celltypes(self) -> NumpyArray[np.uint8]: # numpydoc ignore=RT01
2517 """Return the cell types array.
2518
2519 The array contains integer values corresponding to the :attr:`pyvista.Cell.type`
2520 of each cell in the dataset. See the :class:`pyvista.CellType` enum for more
2521 information about cell type.
2522
2523 Returns
2524 -------
2525 numpy.ndarray
2526 Array of cell types.
2527
2528 Examples
2529 --------
2530 This mesh contains only linear hexahedral cells, type
2531 :attr:`pyvista.CellType.HEXAHEDRON`, which evaluates to 12.
2532
2533 >>> from pyvista import examples
2534 >>> hex_beam = examples.load_hexbeam()
2535 >>> hex_beam.celltypes
2536 array([12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
2537 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
2538 12, 12, 12, 12, 12, 12], dtype=uint8)
2539
2540 Compare this to :attr:`~pyvista.DataSet.distinct_cell_types`.
2541
2542 >>> hex_beam.distinct_cell_types
2543 {<CellType.HEXAHEDRON: 12>}
2544
2545 """
2546 return _vtk.vtk_to_numpy(self._get_cell_types_array())
2547
2548 def _get_cell_types_array(self):
2549 array = (
2550 self.GetCellTypes() if pv.vtk_version_info >= (9, 6, 0) else self.GetCellTypesArray()
2551 )
2552
2553 if array is None:
2554 array = _vtk.vtkUnsignedCharArray()
2555 return array
2556
2557 @property
2558 def offset(self) -> NumpyArray[float]: # numpydoc ignore=RT01
2559 """Return the cell locations array.
2560
2561 This is the location of the start of each cell in
2562 :attr:`cell_connectivity`.
2563
2564 Returns
2565 -------
2566 numpy.ndarray
2567 Array of cell offsets indicating the start of each cell.
2568
2569 Notes
2570 -----
2571 The array returned is immutable and cannot be written to. If you
2572 need to modify this array, create a copy of it using
2573 :func:`numpy.copy`.
2574
2575 Examples
2576 --------
2577 Return the cell offset array. Since this mesh is composed of
2578 all hexahedral cells, note how each cell starts at 8 greater
2579 than the prior cell.
2580
2581 >>> import pyvista as pv
2582 >>> from pyvista import examples
2583 >>> hex_beam = pv.read(examples.hexbeamfile)
2584 >>> hex_beam.offset
2585 array([ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96,
2586 104, 112, 120, 128, 136, 144, 152, 160, 168, 176, 184, 192, 200,
2587 208, 216, 224, 232, 240, 248, 256, 264, 272, 280, 288, 296, 304,
2588 312, 320])
2589
2590 """
2591 carr = self._get_cells()
2592 # This will be the number of cells + 1.
2593 array = _vtk.vtk_to_numpy(carr.GetOffsetsArray())
2594 array.flags['WRITEABLE'] = False
2595 return array
2596
2597 def cast_to_explicit_structured_grid(self):
2598 """Cast to an explicit structured grid.
2599
2600 Returns
2601 -------
2602 pyvista.ExplicitStructuredGrid
2603 An explicit structured grid.
2604
2605 Raises
2606 ------
2607 TypeError
2608 If the unstructured grid doesn't have the ``'BLOCK_I'``,
2609 ``'BLOCK_J'`` and ``'BLOCK_K'`` cells arrays.
2610
2611 See Also
2612 --------
2613 pyvista.ExplicitStructuredGrid.cast_to_unstructured_grid
2614
2615 Examples
2616 --------
2617 >>> from pyvista import examples
2618 >>> grid = examples.load_explicit_structured()
2619 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
2620
2621 >>> grid = grid.hide_cells(range(80, 120))
2622 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
2623
2624 >>> grid = grid.cast_to_unstructured_grid()
2625 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
2626
2627 >>> grid = grid.cast_to_explicit_structured_grid()
2628 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
2629
2630 """
2631 s1 = {'BLOCK_I', 'BLOCK_J', 'BLOCK_K'}
2632 s2 = self.cell_data.keys()
2633 if not s1.issubset(s2):
2634 msg = "'BLOCK_I', 'BLOCK_J' and 'BLOCK_K' cell arrays are required"
2635 raise TypeError(msg)
2636 alg = _vtk.vtkUnstructuredGridToExplicitStructuredGrid()
2637 alg.SetInputData(self)
2638 alg.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I')
2639 alg.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J')
2640 alg.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K')
2641 alg.Update()
2642 grid = _get_output(alg)
2643 grid.cell_data.remove('ConnectivityFlags') # unrequired
2644 return grid
2645
2646
2647 class StructuredGrid(PointGrid, StructuredGridFilters, _vtk.vtkStructuredGrid):
2648 """Dataset used for topologically regular arrays of data.
2649
2650 Can be initialized in one of the following several ways:
2651
2652 * Create empty grid.
2653 * Initialize from a filename.
2654 * Initialize from a :vtk:`vtkStructuredGrid` object.
2655 * Initialize directly from one or more :class:`numpy.ndarray`. See the
2656 example or the documentation of ``uinput``.
2657
2658 Parameters
2659 ----------
2660 uinput : str, Path, :vtk:`vtkStructuredGrid`, numpy.ndarray, optional
2661 Filename, dataset, or array to initialize the structured grid from. If
2662 a filename is passed, pyvista will attempt to load it as a
2663 :class:`StructuredGrid`. If passed a :vtk:`vtkStructuredGrid`, it will
2664 be wrapped as a deep copy.
2665
2666 If a :class:`numpy.ndarray` is provided and ``y`` and ``z`` are empty,
2667 this array will define the points of this :class:`StructuredGrid`.
2668 Set the dimensions with :attr:`StructuredGrid.dimensions`.
2669
2670 Otherwise, this parameter will be loaded as the ``x`` points, and ``y``
2671 and ``z`` points must be set. The shape of this array defines the shape
2672 of the structured data and the shape should be ``(dimx, dimy,
2673 dimz)``. Missing trailing dimensions are assumed to be ``1``.
2674
2675 y : numpy.ndarray, optional
2676 Coordinates of the points in y direction. If this is passed, ``uinput``
2677 must be a :class:`numpy.ndarray` and match the shape of ``y``.
2678
2679 z : numpy.ndarray, optional
2680 Coordinates of the points in z direction. If this is passed, ``uinput``
2681 and ``y`` must be a :class:`numpy.ndarray` and match the shape of ``z``.
2682
2683 deep : bool, default: False
2684 Whether to deep copy a StructuredGrid object.
2685 Default is ``False``. Keyword only.
2686
2687 validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False
2688 Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after
2689 initialization. Set this to ``True`` to validate all fields, or specify any
2690 combination of fields allowed by ``validate_mesh``.
2691
2692 .. versionadded:: 0.47
2693
2694 **kwargs : dict, optional
2695 Additional keyword arguments passed when reading from a file or loading
2696 from arrays.
2697
2698 See Also
2699 --------
2700 :ref:`create_structured_surface_example`
2701
2702 Examples
2703 --------
2704 >>> import pyvista as pv
2705 >>> import vtk
2706 >>> import numpy as np
2707
2708 Create an empty structured grid.
2709
2710 >>> grid = pv.StructuredGrid()
2711
2712 Initialize from a :vtk:`vtkStructuredGrid` object
2713
2714 >>> vtkgrid = vtk.vtkStructuredGrid()
2715 >>> grid = pv.StructuredGrid(vtkgrid)
2716
2717 Create from NumPy arrays using :func:`numpy.meshgrid`.
2718
2719 >>> xrng = np.linspace(-5, 5, 10)
2720 >>> yrng = np.linspace(-8, 8, 4)
2721 >>> zrng = np.linspace(-7, 4, 20)
2722 >>> x, y, z = np.meshgrid(xrng, yrng, zrng, indexing='ij')
2723 >>> grid = pv.StructuredGrid(x, y, z)
2724 >>> grid
2725 StructuredGrid (...)
2726 N Cells: 513
2727 N Points: 800
2728 X Bounds: -5.000e+00, 5.000e+00
2729 Y Bounds: -8.000e+00, 8.000e+00
2730 Z Bounds: -7.000e+00, 4.000e+00
2731 Dimensions: 10, 4, 20
2732 N Arrays: 0
2733
2734 Note how the grid dimensions match the shape of the input arrays.
2735
2736 >>> (xrng.size, yrng.size, zrng.size)
2737 (10, 4, 20)
2738
2739 """
2740
2741 _WRITERS: ClassVar[dict[str, type[StructuredGridWriter | XMLStructuredGridWriter]]] = {
2742 '.vtk': StructuredGridWriter,
2743 '.vts': XMLStructuredGridWriter,
2744 } # type: ignore[assignment]
2745
2746 def __init__(
2747 self,
2748 uinput=None,
2749 y=None,
2750 z=None,
2751 *args,
2752 deep: bool = False,
2753 validate: bool | _NestedMeshValidationFields = False,
2754 **kwargs,
2755 ) -> None:
2756 """Initialize the structured grid."""
2757 super().__init__()
2758
2759 if args:
2760 msg = 'Too many args to create StructuredGrid.'
2761 raise ValueError(msg)
2762
2763 if isinstance(uinput, _vtk.vtkStructuredGrid):
2764 if deep:
2765 self.deep_copy(uinput)
2766 else:
2767 self.shallow_copy(uinput) # type: ignore[arg-type]
2768 elif isinstance(uinput, (str, Path)):
2769 self._from_file(uinput, **kwargs)
2770 elif (
2771 isinstance(uinput, np.ndarray)
2772 and isinstance(y, np.ndarray)
2773 and isinstance(z, np.ndarray)
2774 ):
2775 self._from_arrays(uinput, y, z, **kwargs)
2776 elif isinstance(uinput, np.ndarray) and y is None and z is None:
2777 self.points = uinput
2778 elif uinput is None:
2779 # do nothing, initialize as empty structured grid
2780 pass
2781 else:
2782 msg = (
2783 'Invalid parameters. Expecting one of the following:\n'
2784 ' - No arguments\n'
2785 ' - Filename as the only argument\n'
2786 ' - StructuredGrid as the only argument\n'
2787 ' - Single `numpy.ndarray` as the only argument'
2788 ' - Three `numpy.ndarray` as the first three arguments'
2789 )
2790 raise TypeError(msg)
2791
2792 if validate:
2793 self._validate_mesh(validate)
2794
2795 def __repr__(self):
2796 """Return the standard representation."""
2797 return DataSet.__repr__(self)
2798
2799 def __str__(self):
2800 """Return the standard str representation."""
2801 return DataSet.__str__(self)
2802
2803 def _from_arrays(self, x, y, z, *, force_float: bool = True):
2804 """Create VTK structured grid directly from numpy arrays.
2805
2806 Parameters
2807 ----------
2808 x : numpy.ndarray
2809 Position of the points in x direction.
2810
2811 y : numpy.ndarray
2812 Position of the points in y direction.
2813
2814 z : numpy.ndarray
2815 Position of the points in z direction.
2816
2817 force_float : bool, optional
2818 Casts the datatype to ``float32`` if points datatype is
2819 non-float. Default ``True``. Set this to ``False`` to allow
2820 non-float types, though this may lead to truncation of
2821 intermediate floats when transforming datasets.
2822
2823 """
2824 if not (x.shape == y.shape == z.shape):
2825 msg = 'Input point array shapes must match exactly'
2826 raise ValueError(msg)
2827
2828 # make the output points the same precision as the input arrays
2829 points = np.empty((x.size, 3), x.dtype)
2830 points[:, 0] = x.ravel('F')
2831 points[:, 1] = y.ravel('F')
2832 points[:, 2] = z.ravel('F')
2833
2834 # ensure that the inputs are 3D
2835 dim = list(x.shape)
2836 while len(dim) < 3:
2837 dim.append(1)
2838
2839 # Create structured grid
2840 self.SetDimensions(dim)
2841 self.SetPoints(vtk_points(points, force_float=force_float))
2842
2843 @property
2844 def dimensions(self): # numpydoc ignore=RT01
2845 """Return a length 3 tuple of the grid's dimensions.
2846
2847 Returns
2848 -------
2849 tuple
2850 Grid dimensions.
2851
2852 Examples
2853 --------
2854 >>> import pyvista as pv
2855 >>> import numpy as np
2856 >>> xrng = np.arange(-10, 10, 1, dtype=np.float32)
2857 >>> yrng = np.arange(-10, 10, 2, dtype=np.float32)
2858 >>> zrng = np.arange(-10, 10, 5, dtype=np.float32)
2859 >>> x, y, z = np.meshgrid(xrng, yrng, zrng, indexing='ij')
2860 >>> grid = pv.StructuredGrid(x, y, z)
2861 >>> grid.dimensions
2862 (20, 10, 4)
2863
2864 """
2865 dims = [0, 0, 0]
2866 self.GetDimensions(dims)
2867 return tuple(dims)
2868
2869 @dimensions.setter
2870 def dimensions(self, dims) -> None:
2871 nx, ny, nz = dims[0], dims[1], dims[2]
2872 self.SetDimensions(nx, ny, nz)
2873 self.Modified()
2874
2875 @property
2876 def x(self): # numpydoc ignore=RT01
2877 """Return the X coordinates of all points.
2878
2879 Returns
2880 -------
2881 numpy.ndarray
2882 Numpy array of all X coordinates.
2883
2884 Examples
2885 --------
2886 >>> import pyvista as pv
2887 >>> import numpy as np
2888 >>> xrng = np.arange(-10, 10, 1, dtype=np.float32)
2889 >>> yrng = np.arange(-10, 10, 2, dtype=np.float32)
2890 >>> zrng = np.arange(-10, 10, 5, dtype=np.float32)
2891 >>> x, y, z = np.meshgrid(xrng, yrng, zrng, indexing='ij')
2892 >>> grid = pv.StructuredGrid(x, y, z)
2893 >>> grid.x.shape
2894 (20, 10, 4)
2895
2896 """
2897 return self._reshape_point_array(self.points[:, 0])
2898
2899 @property
2900 def y(self): # numpydoc ignore=RT01
2901 """Return the Y coordinates of all points."""
2902 return self._reshape_point_array(self.points[:, 1])
2903
2904 @property
2905 def z(self): # numpydoc ignore=RT01
2906 """Return the Z coordinates of all points."""
2907 return self._reshape_point_array(self.points[:, 2])
2908
2909 @property
2910 def points_matrix(self): # numpydoc ignore=RT01
2911 """Points as a 4-D matrix, with x/y/z along the last dimension."""
2912 return self.points.reshape((*self.dimensions, 3), order='F')
2913
2914 def _get_attrs(self):
2915 """Return the representation methods (internal helper)."""
2916 attrs = PointGrid._get_attrs(self)
2917 attrs.append(('Dimensions', self.dimensions, '{:d}, {:d}, {:d}'))
2918 return attrs
2919
2920 def __getitem__(self, key):
2921 """Slice subsets of the StructuredGrid, or extract an array field."""
2922 # legacy behavior which looks for a point or cell array
2923 if not isinstance(key, tuple):
2924 return super().__getitem__(key)
2925
2926 # convert slice to VOI specification - only "basic indexing" is supported
2927 voi = [] # type: ignore[var-annotated]
2928 rate = []
2929 if len(key) != 3:
2930 msg = 'Slices must have exactly 3 dimensions.'
2931 raise RuntimeError(msg)
2932 for i, k in enumerate(key):
2933 if isinstance(k, Iterable):
2934 msg = 'Fancy indexing with iterable is not supported.'
2935 raise TypeError(msg)
2936 if isinstance(k, numbers.Integral):
2937 start = stop = k
2938 step = 1
2939 elif isinstance(k, slice):
2940 start = k.start if k.start is not None else 0 # type: ignore[assignment]
2941 stop = k.stop - 1 if k.stop is not None else self.dimensions[i]
2942 step = k.step if k.step is not None else 1
2943 voi.extend((start, stop))
2944 rate.append(step)
2945
2946 return self.extract_subset(voi, rate, boundary=False)
2947
2948 @_deprecate_positional_args(allowed=['ind'])
2949 def hide_cells(self, ind, inplace: bool = False) -> Self: # noqa: FBT001, FBT002
2950 """Hide cells without deleting them.
2951
2952 Hides cells by setting the ghost_cells array to ``HIDDEN_CELL``.
2953
2954 Parameters
2955 ----------
2956 ind : sequence[int]
2957 List or array of cell indices to be hidden. The array can
2958 also be a boolean array of the same size as the number of
2959 cells.
2960
2961 inplace : bool, default: False
2962 Updates mesh in-place.
2963
2964 Returns
2965 -------
2966 pyvista.StructuredGrid
2967 Structured grid with hidden cells.
2968
2969 Examples
2970 --------
2971 Hide part of the middle of a structured surface.
2972
2973 >>> import pyvista as pv
2974 >>> import numpy as np
2975 >>> x = np.arange(-10, 10, 0.25)
2976 >>> y = np.arange(-10, 10, 0.25)
2977 >>> z = 0
2978 >>> x, y, z = np.meshgrid(x, y, z)
2979 >>> grid = pv.StructuredGrid(x, y, z)
2980 >>> grid = grid.hide_cells(range(79 * 30, 79 * 50))
2981 >>> grid.plot(color=True, show_edges=True)
2982
2983 """
2984 if not inplace:
2985 return self.copy().hide_cells(ind, inplace=True)
2986 if isinstance(ind, np.ndarray):
2987 if ind.dtype == np.bool_ and ind.size != self.n_cells:
2988 msg = f'Boolean array size must match the number of cells ({self.n_cells})'
2989 raise ValueError(msg)
2990 ghost_cells = np.zeros(self.n_cells, np.uint8)
2991 ghost_cells[ind] = _vtk.vtkDataSetAttributes.HIDDENCELL
2992
2993 # NOTE: cells cannot be removed from a structured grid, only
2994 # hidden setting ghost_cells to a value besides
2995 # vtk.vtkDataSetAttributes.HIDDENCELL will not hide them
2996 # properly, additionally, calling self.RemoveGhostCells will
2997 # have no effect
2998
2999 # add but do not make active
3000 self.cell_data.set_array(ghost_cells, _vtk.vtkDataSetAttributes.GhostArrayName()) # type: ignore[arg-type]
3001 return self
3002
3003 def hide_points(self, ind: VectorLike[bool] | VectorLike[int]) -> None:
3004 """Hide points without deleting them.
3005
3006 Hides points by setting the ghost_points array to ``HIDDEN_CELL``.
3007
3008 Parameters
3009 ----------
3010 ind : VectorLike[bool] | VectorLike[int]
3011 Vector of point indices to be hidden. The vector can also be a
3012 boolean array of the same size as the number of points.
3013
3014 Examples
3015 --------
3016 Hide part of the middle of a structured surface.
3017
3018 >>> import pyvista as pv
3019 >>> import numpy as np
3020 >>> x = np.arange(-10, 10, 0.25)
3021 >>> y = np.arange(-10, 10, 0.25)
3022 >>> z = 0
3023 >>> x, y, z = np.meshgrid(x, y, z)
3024 >>> grid = pv.StructuredGrid(x, y, z)
3025 >>> grid.hide_points(range(80 * 30, 80 * 50))
3026 >>> grid.plot(color=True, show_edges=True)
3027
3028 """
3029 if isinstance(ind, np.ndarray):
3030 if ind.dtype == np.bool_ and ind.size != self.n_points:
3031 msg = f'Boolean array size must match the number of points ({self.n_points})'
3032 raise ValueError(msg)
3033 ghost_points = np.zeros(self.n_points, np.uint8)
3034 ghost_points[ind] = _vtk.vtkDataSetAttributes.HIDDENPOINT
3035
3036 # add but do not make active
3037 self.point_data.set_array(ghost_points, _vtk.vtkDataSetAttributes.GhostArrayName()) # type: ignore[arg-type]
3038
3039 def cast_to_explicit_structured_grid(self) -> ExplicitStructuredGrid:
3040 """Cast to an explicit structured grid.
3041
3042 Returns
3043 -------
3044 pyvista.ExplicitStructuredGrid
3045 An explicit structured grid.
3046
3047 Raises
3048 ------
3049 TypeError
3050 If the structured grid is not 3D (i.e., any dimension is 1).
3051
3052 """
3053 if any(n == 1 for n in self.dimensions):
3054 msg = 'Only 3D structured grid can be casted to an explicit structured grid.'
3055 raise TypeError(msg)
3056
3057 ni, nj, nk = self.dimensions
3058 grid = self.cast_to_unstructured_grid()
3059
3060 s1 = {'BLOCK_I', 'BLOCK_J', 'BLOCK_K'}
3061 if not s1.issubset(self.cell_data):
3062 i, j, k = np.unravel_index(
3063 np.arange(self.n_cells),
3064 shape=(ni - 1, nj - 1, nk - 1),
3065 order='F',
3066 )
3067 grid.cell_data['BLOCK_I'] = i
3068 grid.cell_data['BLOCK_J'] = j
3069 grid.cell_data['BLOCK_K'] = k
3070
3071 grid = grid.cast_to_explicit_structured_grid()
3072
3073 if not s1.issubset(self.cell_data):
3074 for key in s1:
3075 grid.cell_data.pop(key, None)
3076
3077 return grid
3078
3079 def _reshape_point_array(self, array: NumpyArray[float]) -> NumpyArray[float]:
3080 """Reshape point data to a 3-D matrix."""
3081 return array.reshape(self.dimensions, order='F')
3082
3083 def _reshape_cell_array(self, array: NumpyArray[float]) -> NumpyArray[float]:
3084 """Reshape cell data to a 3-D matrix."""
3085 cell_dims = np.array(self.dimensions) - 1
3086 cell_dims[cell_dims == 0] = 1
3087 return array.reshape(cell_dims, order='F')
3088
3089
3090 class ExplicitStructuredGrid(PointGrid, _vtk.vtkExplicitStructuredGrid):
3091 """Extend the functionality of the :vtk:`vtkExplicitStructuredGrid` class.
3092
3093 Can be initialized by the following:
3094
3095 - Creating an empty grid
3096 - From a :vtk:`vtkStructuredGrid`, :vtk:`vtkExplicitStructuredGrid` or
3097 :vtk:`vtkUnstructuredGrid` object
3098 - From a VTU or VTK file
3099 - From ``dims`` and ``corners`` arrays
3100 - From ``dims``, ``cells`` and ``points`` arrays
3101
3102 Parameters
3103 ----------
3104 args : :vtk:`vtkExplicitStructuredGrid`, :vtk:`vtkUnstructuredGrid`, str, Sequence
3105 See examples below.
3106
3107 deep : bool, default: False
3108 Whether to deep copy a :vtk:`vtkUnstructuredGrid` object.
3109
3110 validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False
3111 Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after
3112 initialization. Set this to ``True`` to validate all fields, or specify any
3113 combination of fields allowed by ``validate_mesh``.
3114
3115 .. versionadded:: 0.47
3116
3117 See Also
3118 --------
3119 :ref:`create_explicit_structured_grid_example`
3120
3121 Examples
3122 --------
3123 >>> import numpy as np
3124 >>> import pyvista as pv
3125 >>>
3126 >>> # grid size: ni*nj*nk cells; si, sj, sk steps
3127 >>> ni, nj, nk = 4, 5, 6
3128 >>> si, sj, sk = 20, 10, 1
3129 >>>
3130 >>> # create raw coordinate grid
3131 >>> grid_ijk = np.mgrid[
3132 ... : (ni + 1) * si : si,
3133 ... : (nj + 1) * sj : sj,
3134 ... : (nk + 1) * sk : sk,
3135 ... ]
3136 >>>
3137 >>> # repeat array along each Cartesian axis for connectivity
3138 >>> for axis in range(1, 4):
3139 ... grid_ijk = grid_ijk.repeat(2, axis=axis)
3140 >>>
3141 >>> # slice off unnecessarily doubled edge coordinates
3142 >>> grid_ijk = grid_ijk[:, 1:-1, 1:-1, 1:-1]
3143 >>>
3144 >>> # reorder and reshape to VTK order
3145 >>> corners = grid_ijk.transpose().reshape(-1, 3)
3146 >>>
3147 >>> dims = np.array([ni, nj, nk]) + 1
3148 >>> grid = pv.ExplicitStructuredGrid(dims, corners)
3149 >>> grid = grid.compute_connectivity()
3150 >>> grid.plot(show_edges=True)
3151
3152 """
3153
3154 _WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {
3155 '.vtu': XMLUnstructuredGridWriter,
3156 '.vtk': UnstructuredGridWriter,
3157 }
3158
3159 def __init__(
3160 self, *args, deep: bool = False, validate: bool | _NestedMeshValidationFields = False
3161 ):
3162 """Initialize the explicit structured grid."""
3163 super().__init__()
3164 n = len(args)
3165 if n > 3:
3166 msg = 'Too many args to create ExplicitStructuredGrid.'
3167 raise ValueError(msg)
3168 if n == 1:
3169 arg0 = args[0]
3170 if isinstance(arg0, _vtk.vtkExplicitStructuredGrid):
3171 if deep:
3172 self.deep_copy(arg0)
3173 else:
3174 self.shallow_copy(arg0) # type: ignore[arg-type]
3175 elif isinstance(arg0, (_vtk.vtkStructuredGrid, _vtk.vtkUnstructuredGrid)):
3176 grid = arg0.cast_to_explicit_structured_grid() # type: ignore[union-attr]
3177 self.shallow_copy(grid)
3178 elif isinstance(arg0, (str, Path)):
3179 grid = UnstructuredGrid(arg0)
3180 grid = grid.cast_to_explicit_structured_grid()
3181 self.shallow_copy(grid)
3182 elif n == 2:
3183 arg0, arg1 = args
3184 if isinstance(arg0, tuple):
3185 arg0 = np.asarray(arg0)
3186 if isinstance(arg1, list):
3187 arg1 = np.asarray(arg1)
3188 arg0_is_arr = isinstance(arg0, np.ndarray)
3189 arg1_is_arr = isinstance(arg1, np.ndarray)
3190 if all([arg0_is_arr, arg1_is_arr]):
3191 self._from_arrays(arg0, arg1)
3192 elif n == 3:
3193 arg0, arg1, arg2 = args
3194 arg0 = np.asarray(arg0)
3195 arg1 = np.asarray(arg1) if not isinstance(arg1, dict) else arg1
3196 arg2 = np.asarray(arg2)
3197 self._from_cells_points(arg0, arg1, arg2)
3198
3199 if validate:
3200 self._validate_mesh(validate)
3201
3202 def __repr__(self) -> str:
3203 """Return the standard representation."""
3204 return DataSet.__repr__(self)
3205
3206 def __str__(self) -> str:
3207 """Return the standard ``str`` representation."""
3208 return DataSet.__str__(self)
3209
3210 def _from_arrays(self, dims: VectorLike[int], corners: MatrixLike[float]) -> None:
3211 """Create a VTK explicit structured grid from NumPy arrays.
3212
3213 Parameters
3214 ----------
3215 dims : VectorLike[int]
3216 A sequence of integers with shape (3,) containing the
3217 topological dimensions of the grid.
3218
3219 corners : MatrixLike[float]
3220 A sequence of numbers with shape ``(number of corners, 3)``
3221 containing the coordinates of the corner points.
3222
3223 """
3224 if len(dims) != 3:
3225 msg = 'Expected dimensions to be length 3.'
3226 raise ValueError(msg)
3227
3228 ni, nj, nk = np.asanyarray(dims) - 1
3229 corners = np.reshape(corners, (2 * ni, 2 * nj, 2 * nk, 3), order='F')
3230 points = np.column_stack(
3231 [
3232 np.column_stack(
3233 (
3234 corners_[::2, ::2, ::2].ravel(order='F'),
3235 corners_[1::2, ::2, ::2].ravel(order='F'),
3236 corners_[1::2, 1::2, ::2].ravel(order='F'),
3237 corners_[::2, 1::2, ::2].ravel(order='F'),
3238 corners_[::2, ::2, 1::2].ravel(order='F'),
3239 corners_[1::2, ::2, 1::2].ravel(order='F'),
3240 corners_[1::2, 1::2, 1::2].ravel(order='F'),
3241 corners_[::2, 1::2, 1::2].ravel(order='F'),
3242 )
3243 ).ravel()
3244 for corners_ in corners.transpose((3, 0, 1, 2))
3245 ]
3246 )
3247 cells = np.arange(8 * ni * nj * nk).reshape((ni * nj * nk, 8))
3248 self._from_cells_points(dims, {CellType.HEXAHEDRON: cells}, points)
3249
3250 def _from_cells_points(
3251 self,
3252 dims: VectorLike[int],
3253 cells: VectorLike[int] | dict[int, MatrixLike[int]],
3254 points: MatrixLike[float],
3255 ) -> None:
3256 """Create a VTK explicit structured grid from cells and points arrays.
3257
3258 Parameters
3259 ----------
3260 dims : VectorLike[int]
3261 A sequence of integers with shape (3,) containing the
3262 topological dimensions of the grid.
3263
3264 cells : VectorLike[int] | dict[int, MatrixLike[int]]
3265 Array of cells. Each cell contains the number of points in the
3266 cell and the node numbers of the cell.
3267
3268 points : MatrixLike[float]
3269 Numpy array containing point locations.
3270
3271 """
3272 if len(dims) != 3:
3273 msg = 'Expected dimensions to be length 3.'
3274 raise ValueError(msg)
3275
3276 else:
3277 n_cells = np.prod([n - 1 for n in dims]) # type: ignore[arg-type]
3278
3279 if isinstance(cells, dict):
3280 celltypes = list(cells)
3281
3282 if not (len(celltypes) == 1 and celltypes[0] == CellType.HEXAHEDRON):
3283 msg = f'Expected cells to be a single cell of type {CellType.HEXAHEDRON}.'
3284 raise ValueError(msg)
3285
3286 cells = np.asarray(cells[celltypes[0]])
3287 if cells.shape != (n_cells, 8):
3288 msg = f'Expected cells to be of shape ({n_cells}, 8)'
3289 raise ValueError(msg)
3290
3291 cells = np.column_stack((np.full(n_cells, 8), cells)).flatten()
3292
3293 elif len(cells) != 9 * n_cells:
3294 msg = f'Expected cells to be length {9 * n_cells}'
3295 raise ValueError(msg)
3296
3297 self.SetDimensions(dims[0], dims[1], dims[2]) # type: ignore[arg-type]
3298 self.SetCells(CellArray(cells))
3299 self.SetPoints(vtk_points(points))
3300
3301 def cast_to_unstructured_grid(self) -> UnstructuredGrid:
3302 """Cast to an unstructured grid.
3303
3304 Returns
3305 -------
3306 UnstructuredGrid
3307 An unstructured grid. VTK adds the ``'BLOCK_I'``,
3308 ``'BLOCK_J'`` and ``'BLOCK_K'`` cell arrays. These arrays
3309 are required to restore the explicit structured grid.
3310
3311 See Also
3312 --------
3313 pyvista.DataSetFilters.extract_cells : Extract a subset of a dataset.
3314 pyvista.UnstructuredGrid.cast_to_explicit_structured_grid
3315 Cast an unstructured grid to an explicit structured grid.
3316
3317 Notes
3318 -----
3319 The ghost cell array is disabled before casting the
3320 unstructured grid in order to allow the original structure
3321 and attributes data of the explicit structured grid to be
3322 restored. If you don't need to restore the explicit
3323 structured grid later or want to extract an unstructured
3324 grid from the visible subgrid, use the ``extract_cells``
3325 filter and the cell indices where the ghost cell array is
3326 ``0``.
3327
3328 Examples
3329 --------
3330 >>> from pyvista import examples
3331 >>> grid = examples.load_explicit_structured()
3332 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3333
3334 >>> grid = grid.hide_cells(range(80, 120))
3335 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3336
3337 >>> grid = grid.cast_to_unstructured_grid()
3338 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3339
3340 >>> grid = grid.cast_to_explicit_structured_grid()
3341 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3342
3343 """
3344 grid = ExplicitStructuredGrid()
3345 grid.copy_structure(self)
3346 alg = _vtk.vtkExplicitStructuredGridToUnstructuredGrid()
3347 alg.SetInputDataObject(grid)
3348 alg.Update()
3349 ugrid = _get_output(alg)
3350 ugrid.cell_data.remove('vtkOriginalCellIds') # unrequired
3351 ugrid.copy_attributes(self) # copy ghost cell array and other arrays
3352 return ugrid
3353
3354 @_deprecate_positional_args
3355 def clean( # noqa: PLR0917
3356 self,
3357 tolerance=0,
3358 remove_unused_points: bool = True, # noqa: FBT001, FBT002
3359 produce_merge_map: bool = True, # noqa: FBT001, FBT002
3360 average_point_data: bool = True, # noqa: FBT001, FBT002
3361 merging_array_name=None,
3362 progress_bar: bool = False, # noqa: FBT001, FBT002
3363 ) -> ExplicitStructuredGrid:
3364 """Merge duplicate points and remove unused points in an ExplicitStructuredGrid.
3365
3366 This filter, merging coincident points as defined by a merging
3367 tolerance and optionally removes unused points. The filter does not
3368 modify the topology of the input dataset, nor change the types of
3369 cells. It may however, renumber the cell connectivity ids.
3370
3371 This filter casts the grid to an UnstructuredGrid to clean it, then
3372 casts the cleaned unstructured grid to an explicit structured grid.
3373
3374 Parameters
3375 ----------
3376 tolerance : float, default: 0.0
3377 The absolute point merging tolerance.
3378
3379 remove_unused_points : bool, default: True
3380 Indicate whether points unused by any cell are removed from the
3381 output. Note that when this is off, the filter can successfully
3382 process datasets with no cells (and just points). If on in this
3383 case, and there are no cells, the output will be empty.
3384
3385 produce_merge_map : bool, default: False
3386 Indicate whether a merge map should be produced on output.
3387 The merge map, if requested, maps each input point to its
3388 output point id, or provides a value of -1 if the input point
3389 is not used in the output. The merge map is associated with
3390 the filter's output field data and is named ``"PointMergeMap"``.
3391
3392 average_point_data : bool, default: True
3393 Indicate whether point coordinates and point data of merged points
3394 are averaged. When ``True``, the data coordinates and attribute
3395 values of all merged points are averaged. When ``False``, the point
3396 coordinate and data of the single remaining merged point is
3397 retained.
3398
3399 merging_array_name : str, optional
3400 If a ``merging_array_name`` is specified and exists in the
3401 ``point_data``, then point merging will switch into a mode where
3402 merged points must be both geometrically coincident and have
3403 matching point data. When set, ``tolerance`` has no effect.
3404
3405 progress_bar : bool, default: False
3406 Display a progress bar to indicate progress.
3407
3408 Returns
3409 -------
3410 ExplicitStructuredGrid
3411 Cleaned explicit structured grid.
3412
3413 """
3414 grid = (
3415 self.cast_to_unstructured_grid()
3416 .clean(
3417 tolerance=tolerance,
3418 remove_unused_points=remove_unused_points,
3419 produce_merge_map=produce_merge_map,
3420 average_point_data=average_point_data,
3421 merging_array_name=merging_array_name,
3422 progress_bar=progress_bar,
3423 )
3424 .cast_to_explicit_structured_grid()
3425 )
3426
3427 s1 = {'BLOCK_I', 'BLOCK_J', 'BLOCK_K'}
3428 if not s1.issubset(self.cell_data):
3429 for key in s1:
3430 grid.cell_data.pop(key, None)
3431
3432 return grid
3433
3434 @_deprecate_positional_args(allowed=['filename'])
3435 def save( # noqa: PLR0917
3436 self,
3437 filename: Path | str,
3438 binary: bool = True, # noqa: FBT001, FBT002
3439 texture: NumpyArray[np.uint8] | str | None = None,
3440 compression: _CompressionOptions = 'zlib',
3441 **writer_kwargs: Any,
3442 ) -> None:
3443 """Save this VTK object to file.
3444
3445 Parameters
3446 ----------
3447 filename : Path, str
3448 Output file name. VTU and VTK extensions are supported.
3449
3450 binary : bool, default: True
3451 If ``True``, write as binary, else ASCII.
3452
3453 texture : np.ndarray, str, None
3454 Ignored argument. Kept to maintain compatibility with supertype.
3455
3456 compression : str or None, default: 'zlib'
3457 The compression type to use when ``binary`` is ``True``
3458 and VTK writer is of type :vtk:`vtkXMLWriter`. This
3459 argument has no effect otherwise. Acceptable values are
3460 ``'zlib'``, ``'lz4'``, ``'lzma'``, and ``None``. ``None``
3461 indicates no compression.
3462
3463 .. versionadded:: 0.47
3464
3465 **writer_kwargs : dict, optional
3466 Additional keyword arguments forwarded verbatim to a custom
3467 writer registered via :func:`pyvista.register_writer`. When
3468 the target extension dispatches to a built-in VTK writer or
3469 to the pickle path, passing any extra keyword arguments
3470 raises :class:`TypeError`.
3471
3472 .. versionadded:: 0.48
3473
3474 Notes
3475 -----
3476 VTK adds the ``'BLOCK_I'``, ``'BLOCK_J'`` and ``'BLOCK_K'``
3477 cell arrays. These arrays are required to restore the explicit
3478 structured grid.
3479
3480 Examples
3481 --------
3482 >>> import pyvista as pv
3483 >>> from pyvista import examples
3484 >>> grid = examples.load_explicit_structured() # doctest:+SKIP
3485 >>> grid = grid.hide_cells(range(80, 120)) # doctest:+SKIP
3486 >>> grid.save('grid.vtu') # doctest:+SKIP
3487
3488 >>> grid = pv.ExplicitStructuredGrid('grid.vtu') # doctest:+SKIP
3489 >>> grid.plot(color='w', show_edges=True, show_bounds=True) # doctest:+SKIP
3490
3491 >>> grid.show_cells() # doctest:+SKIP
3492 >>> grid.plot(color='w', show_edges=True, show_bounds=True) # doctest:+SKIP
3493
3494 """
3495 if texture is not None:
3496 msg = 'Cannot save texture of a pointset.'
3497 raise ValueError(msg)
3498 grid = self.cast_to_unstructured_grid()
3499 grid.save(filename, binary=binary, compression=compression, **writer_kwargs)
3500
3501 @_deprecate_positional_args(allowed=['ind'])
3502 def hide_cells(self, ind: VectorLike[int], inplace: bool = False) -> Self: # noqa: FBT001, FBT002
3503 """Hide specific cells.
3504
3505 Hides cells by setting the ghost cell array to ``HIDDENCELL``.
3506
3507 Parameters
3508 ----------
3509 ind : sequence[int]
3510 Cell indices to be hidden. A boolean array of the same
3511 size as the number of cells also is acceptable.
3512
3513 inplace : bool, default: False
3514 This method is applied to this grid if ``True``
3515 or to a copy otherwise.
3516
3517 Returns
3518 -------
3519 output : ExplicitStructuredGrid | None
3520 A deep copy of this grid if ``inplace=False`` with the
3521 hidden cells, or this grid with the hidden cells if
3522 otherwise.
3523
3524 Examples
3525 --------
3526 >>> from pyvista import examples
3527 >>> grid = examples.load_explicit_structured()
3528 >>> grid = grid.hide_cells(range(80, 120))
3529 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3530
3531 """
3532 ind_arr = np.asanyarray(ind)
3533
3534 if inplace:
3535 array = np.zeros(self.n_cells, dtype=np.uint8)
3536 array[ind_arr] = _vtk.vtkDataSetAttributes.HIDDENCELL
3537 name = _vtk.vtkDataSetAttributes.GhostArrayName()
3538 self.cell_data[name] = array
3539 return self
3540
3541 grid = self.copy()
3542 grid.hide_cells(ind, inplace=True)
3543 return grid
3544
3545 @_deprecate_positional_args
3546 def show_cells(self, inplace: bool = False) -> Self: # noqa: FBT001, FBT002
3547 """Show hidden cells.
3548
3549 Shows hidden cells by setting the ghost cell array to ``0``
3550 where ``HIDDENCELL``.
3551
3552 Parameters
3553 ----------
3554 inplace : bool, default: False
3555 This method is applied to this grid if ``True``
3556 or to a copy otherwise.
3557
3558 Returns
3559 -------
3560 ExplicitStructuredGrid
3561 A deep copy of this grid if ``inplace=False`` with the
3562 hidden cells shown. Otherwise, this dataset with the
3563 shown cells.
3564
3565 Examples
3566 --------
3567 >>> from pyvista import examples
3568 >>> grid = examples.load_explicit_structured()
3569 >>> grid = grid.hide_cells(range(80, 120))
3570 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3571
3572 >>> grid = grid.show_cells()
3573 >>> grid.plot(color='w', show_edges=True, show_bounds=True)
3574
3575 """
3576 if inplace:
3577 name = _vtk.vtkDataSetAttributes.GhostArrayName()
3578 if name in self.cell_data.keys():
3579 array = self.cell_data[name]
3580 ind = np.argwhere(array == _vtk.vtkDataSetAttributes.HIDDENCELL)
3581 array[ind] = 0
3582 return self
3583 else:
3584 grid = self.copy()
3585 grid.show_cells(inplace=True)
3586 return grid
3587
3588 def _dimensions(self) -> tuple[int, int, int]:
3589 # This method is required to avoid conflict if a developer extends `ExplicitStructuredGrid`
3590 # and reimplements `dimensions` to return, for example, the number of cells in the I, J and
3591 dims = np.reshape(self.GetExtent(), (3, 2)) # K directions.
3592 dims = np.diff(dims, axis=1)
3593 dims = dims.flatten() + 1 # type: ignore[assignment]
3594 return int(dims[0]), int(dims[1]), int(dims[2])
3595
3596 @property
3597 def dimensions(self) -> tuple[int, int, int]: # numpydoc ignore=RT01
3598 """Return the topological dimensions of the grid.
3599
3600 Returns
3601 -------
3602 tuple[int, int, int]
3603 Number of sampling points in the I, J and Z directions respectively.
3604
3605 Examples
3606 --------
3607 >>> from pyvista import examples
3608 >>> grid = examples.load_explicit_structured()
3609 >>> grid.dimensions
3610 (5, 6, 7)
3611
3612 """
3613 return self._dimensions()
3614
3615 @property
3616 def visible_bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
3617 """Return the bounding box of the visible cells.
3618
3619 Different from `bounds`, which returns the bounding box of the
3620 complete grid, this method returns the bounding box of the
3621 visible cells, where the ghost cell array is not
3622 ``HIDDENCELL``.
3623
3624 Returns
3625 -------
3626 tuple[float, float, float]
3627 The limits of the visible grid in the X, Y and Z
3628 directions respectively.
3629
3630 Examples
3631 --------
3632 >>> from pyvista import examples
3633 >>> grid = examples.load_explicit_structured()
3634 >>> grid = grid.hide_cells(range(80, 120))
3635 >>> grid.bounds
3636 BoundsTuple(x_min = 0.0,
3637 x_max = 80.0,
3638 y_min = 0.0,
3639 y_max = 50.0,
3640 z_min = 0.0,
3641 z_max = 6.0)
3642
3643 >>> grid.visible_bounds
3644 BoundsTuple(x_min = 0.0,
3645 x_max = 80.0,
3646 y_min = 0.0,
3647 y_max = 50.0,
3648 z_min = 0.0,
3649 z_max = 4.0)
3650
3651 """
3652 name = _vtk.vtkDataSetAttributes.GhostArrayName()
3653 if name in self.cell_data:
3654 array = self.cell_data[name]
3655 grid = self.extract_cells(array == 0)
3656 return grid.bounds
3657 else:
3658 return self.bounds
3659
3660 def cell_id(self, coords: ArrayLike[int]) -> int | NumpyArray[int] | None:
3661 """Return the cell ID.
3662
3663 Parameters
3664 ----------
3665 coords : ArrayLike[int]
3666 Cell structured coordinates.
3667
3668 Returns
3669 -------
3670 output : int | numpy.ndarray | None
3671 Cell IDs. ``None`` if ``coords`` is outside the grid extent.
3672
3673 See Also
3674 --------
3675 pyvista.ExplicitStructuredGrid.cell_coords : Return the cell structured coordinates.
3676
3677 Examples
3678 --------
3679 >>> from pyvista import examples
3680 >>> grid = examples.load_explicit_structured()
3681 >>> grid.cell_id((3, 4, 0))
3682 np.int64(19)
3683
3684 >>> coords = [(3, 4, 0), (3, 2, 1), (1, 0, 2), (2, 3, 2)]
3685 >>> grid.cell_id(coords)
3686 array([19, 31, 41, 54])
3687
3688 """
3689 # `vtk.vtkExplicitStructuredGrid.ComputeCellId` is not used
3690 # here because this method returns invalid cell IDs when
3691 # `coords` is outside the grid extent.
3692 if isinstance(coords, Sequence):
3693 coords = np.asarray(coords)
3694
3695 if coords.ndim == 2:
3696 ncol = coords.shape[1]
3697 coords = [coords[:, c] for c in range(ncol)]
3698 coords = tuple(coords)
3699 dims = self._dimensions()
3700 try:
3701 ind = np.ravel_multi_index(coords, np.array(dims) - 1, order='F')
3702 except ValueError:
3703 return None
3704 else:
3705 return ind
3706
3707 def cell_coords(
3708 self,
3709 ind: int | VectorLike[int],
3710 ) -> None | MatrixLike[int]:
3711 """Return the cell structured coordinates.
3712
3713 Parameters
3714 ----------
3715 ind : int | VectorLike[int]
3716 Cell IDs.
3717
3718 Returns
3719 -------
3720 output : numpy.ndarray | None
3721 Cell structured coordinates. ``None`` if ``ind`` is
3722 outside the grid extent.
3723
3724 See Also
3725 --------
3726 pyvista.ExplicitStructuredGrid.cell_id : Return the cell ID.
3727
3728 Examples
3729 --------
3730 >>> from pyvista import examples
3731 >>> grid = examples.load_explicit_structured()
3732 >>> grid.cell_coords(19)
3733 array([3, 4, 0])
3734
3735 >>> grid.cell_coords((19, 31, 41, 54))
3736 array([[3, 4, 0],
3737 [3, 2, 1],
3738 [1, 0, 2],
3739 [2, 3, 2]])
3740
3741 """
3742 dims = self._dimensions()
3743 try:
3744 coords = np.unravel_index(ind, np.array(dims) - 1, order='F')
3745 except ValueError:
3746 return None
3747 else:
3748 if isinstance(coords[0], np.ndarray):
3749 return np.stack(coords, axis=1)
3750 return np.asanyarray(coords) # type: ignore[unreachable]
3751
3752 def neighbors(self, ind: int | VectorLike[int], rel: str = 'connectivity') -> list[int]:
3753 """Return the indices of neighboring cells.
3754
3755 Parameters
3756 ----------
3757 ind : int | VectorLike[int]
3758 Cell IDs.
3759
3760 rel : str, default: "connectivity"
3761 Defines the neighborhood relationship. If
3762 ``'topological'``, returns the ``(i-1, j, k)``, ``(i+1, j,
3763 k)``, ``(i, j-1, k)``, ``(i, j+1, k)``, ``(i, j, k-1)``
3764 and ``(i, j, k+1)`` cells. If ``'connectivity'``
3765 (default), returns only the topological neighbors
3766 considering faces connectivity. If ``'geometric'``,
3767 returns the cells in the ``(i-1, j)``, ``(i+1, j)``,
3768 ``(i,j-1)`` and ``(i, j+1)`` vertical cell groups whose
3769 faces intersect.
3770
3771 Returns
3772 -------
3773 list[int]
3774 Indices of neighboring cells.
3775
3776 Examples
3777 --------
3778 >>> import pyvista as pv
3779 >>> from pyvista import examples
3780 >>> grid = examples.load_explicit_structured()
3781 >>> cell = grid.extract_cells(31)
3782 >>> ind = grid.neighbors(31)
3783 >>> neighbors = grid.extract_cells(ind)
3784 >>> pl = pv.Plotter()
3785 >>> _ = pl.add_axes()
3786 >>> _ = pl.add_mesh(cell, color='r', show_edges=True)
3787 >>> _ = pl.add_mesh(neighbors, color='w', show_edges=True)
3788 >>> pl.show()
3789
3790 """
3791
3792 def connectivity(ind):
3793 indices = []
3794 cell_coords = self.cell_coords(ind)
3795 cell_points = self.get_cell(ind).points
3796 if cell_points.shape[0] == 8:
3797 faces = [
3798 [(-1, 0, 0), (0, 4, 7, 3), (1, 5, 6, 2)],
3799 [(+1, 0, 0), (1, 2, 6, 5), (0, 3, 7, 4)],
3800 [(0, -1, 0), (0, 1, 5, 4), (3, 2, 6, 7)],
3801 [(0, +1, 0), (3, 7, 6, 2), (0, 4, 5, 1)],
3802 [(0, 0, -1), (0, 3, 2, 1), (4, 7, 6, 5)],
3803 [(0, 0, +1), (4, 5, 6, 7), (0, 1, 2, 3)],
3804 ]
3805 for f in faces:
3806 coords = np.sum([cell_coords, f[0]], axis=0) # type: ignore[arg-type]
3807 ind = self.cell_id(coords)
3808 if ind:
3809 points = self.get_cell(ind).points
3810 if points.shape[0] == 8:
3811 a1 = cell_points[f[1], :]
3812 a2 = points[f[2], :]
3813 if np.array_equal(a1, a2):
3814 indices.append(ind)
3815 return indices
3816
3817 def topological(ind):
3818 indices = []
3819 cell_coords = self.cell_coords(ind)
3820 cell_neighbors = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)]
3821 for n in cell_neighbors:
3822 coords = np.sum([cell_coords, n], axis=0) # type: ignore[arg-type]
3823 ind = self.cell_id(coords)
3824 if ind:
3825 indices.append(ind)
3826 return indices
3827
3828 def geometric(ind):
3829 indices = []
3830 cell_coords = self.cell_coords(ind)
3831 cell_points = self.get_cell(ind).points
3832 if cell_points.shape[0] == 8:
3833 for k in [-1, 1]:
3834 coords = np.sum([cell_coords, (0, 0, k)], axis=0) # type: ignore[arg-type]
3835 ind = self.cell_id(coords)
3836 if ind:
3837 indices.append(ind)
3838 faces = [
3839 [(-1, 0, 0), (0, 4, 3, 7), (1, 5, 2, 6)],
3840 [(+1, 0, 0), (2, 6, 1, 5), (3, 7, 0, 4)],
3841 [(0, -1, 0), (1, 5, 0, 4), (2, 6, 3, 7)],
3842 [(0, +1, 0), (3, 7, 2, 6), (0, 4, 1, 5)],
3843 ]
3844 nk = self.dimensions[2]
3845 for f in faces:
3846 cell_z = cell_points[f[1], 2]
3847 cell_z = np.abs(cell_z)
3848 cell_z = cell_z.reshape((2, 2))
3849 cell_zmin = cell_z.min(axis=1)
3850 cell_zmax = cell_z.max(axis=1)
3851 coords = np.sum([cell_coords, f[0]], axis=0) # type: ignore[arg-type]
3852 for k in range(nk):
3853 coords[2] = k
3854 ind = self.cell_id(coords)
3855 if ind:
3856 points = self.get_cell(ind).points
3857 if points.shape[0] == 8:
3858 z = points[f[2], 2]
3859 z = np.abs(z)
3860 z = z.reshape((2, 2))
3861 zmin = z.min(axis=1)
3862 zmax = z.max(axis=1)
3863 if (
3864 (zmax[0] > cell_zmin[0] and zmin[0] < cell_zmax[0])
3865 or (zmax[1] > cell_zmin[1] and zmin[1] < cell_zmax[1])
3866 or (zmin[0] > cell_zmax[0] and zmax[1] < cell_zmin[1])
3867 or (zmin[1] > cell_zmax[1] and zmax[0] < cell_zmin[0])
3868 ):
3869 indices.append(ind)
3870 return indices
3871
3872 if isinstance(ind, int):
3873 ind = [ind]
3874
3875 rel_map = {
3876 'connectivity': connectivity,
3877 'geometric': geometric,
3878 'topological': topological,
3879 }
3880
3881 if rel not in rel_map:
3882 msg = (
3883 f'Invalid value for `rel` of {rel}. Should be one of the '
3884 f'following\n{rel_map.keys()}'
3885 )
3886 raise ValueError(msg)
3887 rel_func = rel_map[rel]
3888
3889 indices = set()
3890 for i in ind:
3891 indices.update(rel_func(i))
3892 return sorted(indices)
3893
3894 @_deprecate_positional_args
3895 def compute_connectivity(self, inplace: bool = False) -> Self: # noqa: FBT001, FBT002
3896 """Compute the faces connectivity flags array.
3897
3898 This method checks the faces connectivity of the cells with
3899 their topological neighbors. The result is stored in the
3900 array of integers ``'ConnectivityFlags'``. Each value in this
3901 array must be interpreted as a binary number, where the digits
3902 shows the faces connectivity of a cell with its topological
3903 neighbors -Z, +Z, -Y, +Y, -X and +X respectively. For example,
3904 a cell with ``'ConnectivityFlags'`` equal to ``27``
3905 (``011011``) indicates that this cell is connected by faces
3906 with their neighbors ``(0, 0, 1)``, ``(0, -1, 0)``,
3907 ``(-1, 0, 0)`` and ``(1, 0, 0)``.
3908
3909 Parameters
3910 ----------
3911 inplace : bool, default: False
3912 This method is applied to this grid if ``True``
3913 or to a copy otherwise.
3914
3915 Returns
3916 -------
3917 ExplicitStructuredGrid
3918 A deep copy of this grid if ``inplace=False``, or this
3919 DataSet if otherwise.
3920
3921 See Also
3922 --------
3923 ExplicitStructuredGrid.compute_connections
3924 Compute an array with the number of connected cell faces.
3925
3926 Examples
3927 --------
3928 >>> from pyvista import examples
3929 >>>
3930 >>> grid = examples.load_explicit_structured()
3931 >>> grid = grid.compute_connectivity()
3932 >>> grid.plot(show_edges=True)
3933
3934 """
3935 if inplace:
3936 self.ComputeFacesConnectivityFlagsArray()
3937 return self
3938 else:
3939 grid = self.copy()
3940 grid.compute_connectivity(inplace=True)
3941 return grid
3942
3943 @_deprecate_positional_args
3944 def compute_connections(self, inplace: bool = False) -> Self: # noqa: FBT001, FBT002
3945 """Compute an array with the number of connected cell faces.
3946
3947 This method calculates the number of topological cell
3948 neighbors connected by faces. The results are stored in the
3949 ``'number_of_connections'`` cell array.
3950
3951 Parameters
3952 ----------
3953 inplace : bool, default: False
3954 This method is applied to this grid if ``True`` or to a copy
3955 otherwise.
3956
3957 Returns
3958 -------
3959 ExplicitStructuredGrid
3960 A deep copy of this grid if ``inplace=False`` or this
3961 DataSet if otherwise.
3962
3963 See Also
3964 --------
3965 ExplicitStructuredGrid.compute_connectivity : Compute the faces connectivity flags array.
3966
3967 Examples
3968 --------
3969 >>> from pyvista import examples
3970 >>> grid = examples.load_explicit_structured()
3971 >>> grid = grid.compute_connections()
3972 >>> grid.plot(show_edges=True)
3973
3974 """
3975 if inplace:
3976 if 'ConnectivityFlags' in self.cell_data:
3977 array = self.cell_data['ConnectivityFlags']
3978 else:
3979 grid = self.compute_connectivity(inplace=False)
3980 array = grid.cell_data['ConnectivityFlags']
3981 array = array.reshape((-1, 1)) # type: ignore[assignment]
3982 array = array.astype(np.uint8) # type: ignore[assignment]
3983 array = np.unpackbits(array, axis=1) # type: ignore[assignment]
3984 array = array.sum(axis=1)
3985 self.cell_data['number_of_connections'] = array
3986 return self
3987 else:
3988 return self.copy().compute_connections(inplace=True)