| 1 |
"""Contains the pyvista.Cell class.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import TYPE_CHECKING |
| 6 |
from typing import cast |
| 7 |
|
| 8 |
import numpy as np |
| 9 |
|
| 10 |
import pyvista as pv |
| 11 |
from pyvista import _vtk |
| 12 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 13 |
from pyvista.core._vtk_utilities import DisableVtkSnakeCase |
| 14 |
from pyvista.core._vtk_utilities import vtkPyVistaOverride |
| 15 |
|
| 16 |
from ._typing_core import BoundsTuple |
| 17 |
from .celltype import CellType |
| 18 |
from .dataobject import DataObject |
| 19 |
from .errors import CellSizeError |
| 20 |
from .utilities.cells import numpy_to_idarr |
| 21 |
from .utilities.misc import _BoundsSizeMixin |
| 22 |
from .utilities.misc import _NoNewAttrMixin |
| 23 |
|
| 24 |
if TYPE_CHECKING: |
| 25 |
from typing import Any |
| 26 |
|
| 27 |
from typing_extensions import Self |
| 28 |
|
| 29 |
from pyvista import PolyData |
| 30 |
from pyvista import UnstructuredGrid |
| 31 |
|
| 32 |
from ._typing_core import CellsLike |
| 33 |
from ._typing_core import MatrixLike |
| 34 |
from ._typing_core import NumpyArray |
| 35 |
|
| 36 |
|
| 37 |
def _get_vtk_id_type() -> type[np.int32 | np.int64]: |
| 38 |
"""Return the numpy datatype responding to :vtk:`vtkIdTypeArray`.""" |
| 39 |
VTK_ID_TYPE_SIZE = _vtk.vtkIdTypeArray().GetDataTypeSize() |
| 40 |
if VTK_ID_TYPE_SIZE == 4: |
| 41 |
return np.int32 |
| 42 |
elif VTK_ID_TYPE_SIZE == 8: |
| 43 |
return np.int64 |
| 44 |
return np.int32 |
| 45 |
|
| 46 |
|
| 47 |
class Cell(_BoundsSizeMixin, DataObject, _vtk.vtkGenericCell): |
| 48 |
"""Wrapping of :vtk:`vtkCell`. |
| 49 |
|
| 50 |
This class provides the capability to access a given cell topology and can |
| 51 |
be useful when walking through a cell's individual faces or investigating |
| 52 |
cell properties. |
| 53 |
|
| 54 |
Parameters |
| 55 |
---------- |
| 56 |
vtk_cell : :vtk:`vtkCell`, optional |
| 57 |
The vtk object to wrap as Cell, that must be of :vtk:`vtkCell` type. |
| 58 |
|
| 59 |
cell_type : int, optional |
| 60 |
VTK cell type. Determined from ``vtk_cell`` if not input. |
| 61 |
|
| 62 |
deep : bool, default: False |
| 63 |
Perform a deep copy of the original cell. |
| 64 |
|
| 65 |
See Also |
| 66 |
-------- |
| 67 |
pyvista.CellType |
| 68 |
|
| 69 |
Notes |
| 70 |
----- |
| 71 |
Accessing individual cells from a :class:`pyvista.DataSet` using this class |
| 72 |
will be much slower than accessing bulk data from the |
| 73 |
:attr:`pyvista.PolyData.faces` or :attr:`pyvista.UnstructuredGrid.cells` attributes. |
| 74 |
|
| 75 |
Also note that the cell object is a deep copy of the original cell and |
| 76 |
is unassociated with the original cell. Changing any data of |
| 77 |
that cell (for example, :attr:`pyvista.Cell.points`) will not change the original dataset. |
| 78 |
|
| 79 |
Examples |
| 80 |
-------- |
| 81 |
Get the 0-th cell from a :class:`pyvista.PolyData`. |
| 82 |
|
| 83 |
>>> import pyvista as pv |
| 84 |
>>> mesh = pv.Sphere() |
| 85 |
>>> cell = mesh.get_cell(0) |
| 86 |
>>> cell # doctest: +SKIP |
| 87 |
Cell (0x7fa760075a10) |
| 88 |
Type: <CellType.TRIANGLE: 5> |
| 89 |
Linear: True |
| 90 |
Dimension: 2 |
| 91 |
N Points: 3 |
| 92 |
N Faces: 0 |
| 93 |
N Edges: 3 |
| 94 |
X Bounds: -5.406e-02, -5.551e-17 |
| 95 |
Y Bounds: 0.000e+00, 1.124e-02 |
| 96 |
Z Bounds: -5.000e-01, -4.971e-01 |
| 97 |
|
| 98 |
Get the 0-th cell from a :class:`pyvista.UnstructuredGrid`. |
| 99 |
|
| 100 |
>>> from pyvista import examples |
| 101 |
>>> mesh = examples.load_hexbeam() |
| 102 |
>>> cell = mesh.get_cell(0) |
| 103 |
>>> cell # doctest: +SKIP |
| 104 |
Cell (0x7fdc71a3c210) |
| 105 |
Type: <CellType.HEXAHEDRON: 12> |
| 106 |
Linear: True |
| 107 |
Dimension: 3 |
| 108 |
N Points: 8 |
| 109 |
N Faces: 6 |
| 110 |
N Edges: 12 |
| 111 |
X Bounds: 0.000e+00, 5.000e-01 |
| 112 |
Y Bounds: 0.000e+00, 5.000e-01 |
| 113 |
Z Bounds: 0.000e+00, 5.000e-01 |
| 114 |
|
| 115 |
""" |
| 116 |
|
| 117 |
@_deprecate_positional_args(allowed=['vtk_cell', 'cell_type']) |
| 118 |
def __init__( |
| 119 |
self: Self, |
| 120 |
vtk_cell: _vtk.vtkCell | None = None, |
| 121 |
cell_type: CellType | None = None, |
| 122 |
deep: bool = False, # noqa: FBT001, FBT002 |
| 123 |
) -> None: |
| 124 |
"""Initialize the cell.""" |
| 125 |
super().__init__() |
| 126 |
if vtk_cell is not None: |
| 127 |
if not isinstance(vtk_cell, _vtk.vtkCell): |
| 128 |
msg = f'`vtk_cell` must be a vtkCell, not {type(vtk_cell)}' # type: ignore[unreachable] |
| 129 |
raise TypeError(msg) |
| 130 |
# cell type must be set first before deep or shallow copy |
| 131 |
if cell_type is None: |
| 132 |
self.SetCellType(vtk_cell.GetCellType()) |
| 133 |
else: |
| 134 |
self.SetCellType(cell_type) |
| 135 |
|
| 136 |
if deep: |
| 137 |
self.DeepCopy(vtk_cell) |
| 138 |
else: |
| 139 |
self.ShallowCopy(vtk_cell) |
| 140 |
|
| 141 |
@property |
| 142 |
def type(self: Self) -> CellType: |
| 143 |
"""Get the cell type from the enum :class:`pyvista.CellType`. |
| 144 |
|
| 145 |
Returns |
| 146 |
------- |
| 147 |
pyvista.CellType |
| 148 |
Type of cell. |
| 149 |
|
| 150 |
Examples |
| 151 |
-------- |
| 152 |
>>> import pyvista as pv |
| 153 |
>>> mesh = pv.Sphere() |
| 154 |
>>> mesh.get_cell(0).type |
| 155 |
<CellType.TRIANGLE: 5> |
| 156 |
|
| 157 |
""" |
| 158 |
return CellType(self.GetCellType()) |
| 159 |
|
| 160 |
@property |
| 161 |
def is_linear(self: Self) -> bool: |
| 162 |
"""Return if the cell is linear. |
| 163 |
|
| 164 |
See Also |
| 165 |
-------- |
| 166 |
pyvista.CellType.is_linear |
| 167 |
|
| 168 |
Returns |
| 169 |
------- |
| 170 |
bool |
| 171 |
If the cell is linear. |
| 172 |
|
| 173 |
Examples |
| 174 |
-------- |
| 175 |
>>> import pyvista as pv |
| 176 |
>>> mesh = pv.Sphere() |
| 177 |
>>> mesh.get_cell(0).is_linear |
| 178 |
True |
| 179 |
|
| 180 |
""" |
| 181 |
return bool(self.IsLinear()) |
| 182 |
|
| 183 |
def plot(self: Self, **kwargs) -> None: |
| 184 |
"""Plot this cell. |
| 185 |
|
| 186 |
Parameters |
| 187 |
---------- |
| 188 |
**kwargs : dict, optional |
| 189 |
See :func:`pyvista.plot` for a description of the optional keyword |
| 190 |
arguments. |
| 191 |
|
| 192 |
Examples |
| 193 |
-------- |
| 194 |
>>> from pyvista import examples |
| 195 |
>>> mesh = examples.load_hexbeam() |
| 196 |
>>> cell = mesh.get_cell(0) |
| 197 |
>>> cell.plot() |
| 198 |
|
| 199 |
""" |
| 200 |
self.cast_to_unstructured_grid().plot(**kwargs) |
| 201 |
|
| 202 |
def cast_to_polydata(self: Self) -> PolyData: |
| 203 |
"""Cast this cell to PolyData. |
| 204 |
|
| 205 |
Can only be used for 0D, 1D, or 2D cells. |
| 206 |
|
| 207 |
Returns |
| 208 |
------- |
| 209 |
pyvista.PolyData |
| 210 |
This cell cast to a :class:`pyvista.PolyData`. |
| 211 |
|
| 212 |
Examples |
| 213 |
-------- |
| 214 |
>>> from pyvista import examples |
| 215 |
>>> mesh = examples.load_sphere() |
| 216 |
>>> cell = mesh.get_cell(0) |
| 217 |
>>> grid = cell.cast_to_polydata() |
| 218 |
>>> grid # doctest: +SKIP |
| 219 |
PolyData (0x7f09ae437b80) |
| 220 |
N Cells: 1 |
| 221 |
N Points: 3 |
| 222 |
N Strips: 0 |
| 223 |
X Bounds: 0.000e+00, 1.000e+01 |
| 224 |
Y Bounds: 0.000e+00, 2.500e+01 |
| 225 |
Z Bounds: -1.270e+02, -1.250e+02 |
| 226 |
N Arrays: 0 |
| 227 |
|
| 228 |
""" |
| 229 |
cells = [len(self.point_ids), *list(range(len(self.point_ids)))] |
| 230 |
if self.dimension == 0: |
| 231 |
return pv.PolyData(self.points.copy(), verts=cells) |
| 232 |
if self.dimension == 1: |
| 233 |
return pv.PolyData(self.points.copy(), lines=cells) |
| 234 |
if self.dimension == 2: |
| 235 |
if self.type == CellType.TRIANGLE_STRIP: |
| 236 |
return pv.PolyData(self.points.copy(), strips=cells) |
| 237 |
else: |
| 238 |
return pv.PolyData(self.points.copy(), faces=cells) |
| 239 |
else: |
| 240 |
msg = f'3D cells cannot be cast to PolyData: got cell type {self.type}' |
| 241 |
raise ValueError(msg) |
| 242 |
|
| 243 |
def cast_to_unstructured_grid(self: Self) -> UnstructuredGrid: |
| 244 |
"""Cast this cell to an unstructured grid. |
| 245 |
|
| 246 |
Returns |
| 247 |
------- |
| 248 |
pyvista.UnstructuredGrid |
| 249 |
This cell cast to a :class:`pyvista.UnstructuredGrid`. |
| 250 |
|
| 251 |
Examples |
| 252 |
-------- |
| 253 |
>>> from pyvista import examples |
| 254 |
>>> mesh = examples.load_hexbeam() |
| 255 |
>>> cell = mesh.get_cell(0) |
| 256 |
>>> grid = cell.cast_to_unstructured_grid() |
| 257 |
>>> grid # doctest: +SKIP |
| 258 |
UnstructuredGrid (0x7f9383619540) |
| 259 |
N Cells: 1 |
| 260 |
N Points: 8 |
| 261 |
X Bounds: 0.000e+00, 5.000e-01 |
| 262 |
Y Bounds: 0.000e+00, 5.000e-01 |
| 263 |
Z Bounds: 0.000e+00, 5.000e-01 |
| 264 |
N Arrays: 0 |
| 265 |
|
| 266 |
""" |
| 267 |
if self.type == CellType.POLYHEDRON: |
| 268 |
# construct from faces |
| 269 |
cell_ids = [self.n_faces] |
| 270 |
for face in self.faces: |
| 271 |
cell_ids.append(len(face.point_ids)) |
| 272 |
cell_ids.extend(self.point_ids.index(i) for i in face.point_ids) |
| 273 |
cell_ids.insert(0, len(cell_ids)) |
| 274 |
else: |
| 275 |
cell_ids = [len(self.point_ids), *list(range(len(self.point_ids)))] |
| 276 |
return pv.UnstructuredGrid( |
| 277 |
cell_ids, |
| 278 |
[int(self.type)], |
| 279 |
self.points.copy(), |
| 280 |
) |
| 281 |
|
| 282 |
@property |
| 283 |
def dimension(self: Self) -> int: |
| 284 |
"""Return the cell dimension. |
| 285 |
|
| 286 |
This returns the dimensionality of the cell. For example, 1 for an edge, |
| 287 |
2 for a triangle, and 3 for a tetrahedron. |
| 288 |
|
| 289 |
See Also |
| 290 |
-------- |
| 291 |
pyvista.CellType.dimension |
| 292 |
|
| 293 |
Returns |
| 294 |
------- |
| 295 |
int |
| 296 |
The cell dimension. |
| 297 |
|
| 298 |
Examples |
| 299 |
-------- |
| 300 |
>>> import pyvista as pv |
| 301 |
>>> mesh = pv.Sphere() |
| 302 |
>>> mesh.get_cell(0).dimension |
| 303 |
2 |
| 304 |
|
| 305 |
""" |
| 306 |
return self.GetCellDimension() |
| 307 |
|
| 308 |
@property |
| 309 |
def n_points(self: Self) -> int: |
| 310 |
"""Get the number of points composing the cell. |
| 311 |
|
| 312 |
See Also |
| 313 |
-------- |
| 314 |
pyvista.CellType.n_points |
| 315 |
|
| 316 |
Returns |
| 317 |
------- |
| 318 |
int |
| 319 |
The number of points. |
| 320 |
|
| 321 |
Examples |
| 322 |
-------- |
| 323 |
>>> import pyvista as pv |
| 324 |
>>> mesh = pv.Sphere() |
| 325 |
>>> mesh.get_cell(0).n_points |
| 326 |
3 |
| 327 |
|
| 328 |
""" |
| 329 |
return self.GetNumberOfPoints() |
| 330 |
|
| 331 |
@property |
| 332 |
def n_faces(self: Self) -> int: |
| 333 |
"""Get the number of faces composing the cell. |
| 334 |
|
| 335 |
See Also |
| 336 |
-------- |
| 337 |
pyvista.CellType.n_faces |
| 338 |
|
| 339 |
Returns |
| 340 |
------- |
| 341 |
int |
| 342 |
The number of faces. |
| 343 |
|
| 344 |
Examples |
| 345 |
-------- |
| 346 |
>>> from pyvista.examples.cells import Tetrahedron |
| 347 |
>>> mesh = Tetrahedron() |
| 348 |
>>> mesh.get_cell(0).n_faces |
| 349 |
4 |
| 350 |
|
| 351 |
""" |
| 352 |
return self.GetNumberOfFaces() |
| 353 |
|
| 354 |
@property |
| 355 |
def n_edges(self: Self) -> int: |
| 356 |
"""Get the number of edges composing the cell. |
| 357 |
|
| 358 |
See Also |
| 359 |
-------- |
| 360 |
pyvista.CellType.n_edges |
| 361 |
|
| 362 |
Returns |
| 363 |
------- |
| 364 |
int |
| 365 |
The number of edges composing the cell. |
| 366 |
|
| 367 |
Examples |
| 368 |
-------- |
| 369 |
>>> import pyvista as pv |
| 370 |
>>> mesh = pv.Sphere() |
| 371 |
>>> mesh.get_cell(0).n_edges |
| 372 |
3 |
| 373 |
|
| 374 |
""" |
| 375 |
return self.GetNumberOfEdges() |
| 376 |
|
| 377 |
@property |
| 378 |
def point_ids(self: Self) -> list[int]: |
| 379 |
"""Get the point IDs composing the cell. |
| 380 |
|
| 381 |
Returns |
| 382 |
------- |
| 383 |
list[int] |
| 384 |
The point IDs composing the cell. |
| 385 |
|
| 386 |
Examples |
| 387 |
-------- |
| 388 |
>>> import pyvista as pv |
| 389 |
>>> mesh = pv.Sphere() |
| 390 |
>>> mesh.get_cell(0).point_ids |
| 391 |
[2, 30, 0] |
| 392 |
|
| 393 |
""" |
| 394 |
point_ids = self.GetPointIds() |
| 395 |
return [point_ids.GetId(i) for i in range(point_ids.GetNumberOfIds())] |
| 396 |
|
| 397 |
@property |
| 398 |
def points(self: Self) -> NumpyArray[float]: |
| 399 |
"""Get the point coordinates of the cell. |
| 400 |
|
| 401 |
Returns |
| 402 |
------- |
| 403 |
np.ndarray |
| 404 |
The point coordinates of the cell. |
| 405 |
|
| 406 |
Examples |
| 407 |
-------- |
| 408 |
>>> import pyvista as pv |
| 409 |
>>> mesh = pv.Sphere() |
| 410 |
>>> mesh.get_cell(0).points |
| 411 |
array([[0.05405951, 0. , 0.49706897], |
| 412 |
[0.05287818, 0.0112396 , 0.49706897], |
| 413 |
[0. , 0. , 0.5 ]]) |
| 414 |
|
| 415 |
""" |
| 416 |
return _vtk.vtk_to_numpy(self.GetPoints().GetData()) |
| 417 |
|
| 418 |
def get_edge(self: Self, index: int) -> Cell: |
| 419 |
"""Get the i-th edge composing the cell. |
| 420 |
|
| 421 |
Parameters |
| 422 |
---------- |
| 423 |
index : int |
| 424 |
Edge ID. |
| 425 |
|
| 426 |
Returns |
| 427 |
------- |
| 428 |
pyvista.Cell |
| 429 |
Edge given by ``index``. |
| 430 |
|
| 431 |
Examples |
| 432 |
-------- |
| 433 |
Extract a single edge from a face and output the IDs of the edge |
| 434 |
points. |
| 435 |
|
| 436 |
>>> import pyvista as pv |
| 437 |
>>> mesh = pv.Sphere() |
| 438 |
>>> cell = mesh.get_cell(0) |
| 439 |
>>> edge = cell.get_edge(0) |
| 440 |
>>> edge.point_ids |
| 441 |
[2, 30] |
| 442 |
|
| 443 |
""" |
| 444 |
if index + 1 > self.n_edges: |
| 445 |
msg = f'Invalid index {index} for a cell with {self.n_edges} edges.' |
| 446 |
raise IndexError(msg) |
| 447 |
|
| 448 |
# must deep copy here as multiple sequental calls to GetEdge overwrite |
| 449 |
# the underlying pointer |
| 450 |
return Cell(self.GetEdge(index), deep=True) # type: ignore[abstract] |
| 451 |
|
| 452 |
@property |
| 453 |
def edges(self: Self) -> list[Cell]: |
| 454 |
"""Return a list of edges composing the cell. |
| 455 |
|
| 456 |
Returns |
| 457 |
------- |
| 458 |
list[Cell] |
| 459 |
A list of edges composing the cell. |
| 460 |
|
| 461 |
Examples |
| 462 |
-------- |
| 463 |
>>> from pyvista.examples.cells import Hexahedron |
| 464 |
>>> mesh = Hexahedron() |
| 465 |
>>> cell = mesh.get_cell(0) |
| 466 |
>>> edges = cell.edges |
| 467 |
>>> len(edges) |
| 468 |
12 |
| 469 |
|
| 470 |
""" |
| 471 |
return [self.get_edge(i) for i in range(self.n_edges)] |
| 472 |
|
| 473 |
@property |
| 474 |
def faces(self: Self) -> list[Cell]: |
| 475 |
"""Return a list of faces composing the cell. |
| 476 |
|
| 477 |
Returns |
| 478 |
------- |
| 479 |
list[Cell] |
| 480 |
A list of faces composing the cell. |
| 481 |
|
| 482 |
Examples |
| 483 |
-------- |
| 484 |
>>> from pyvista.examples.cells import Tetrahedron |
| 485 |
>>> mesh = Tetrahedron() |
| 486 |
>>> cell = mesh.get_cell(0) |
| 487 |
>>> faces = cell.faces |
| 488 |
>>> len(faces) |
| 489 |
4 |
| 490 |
|
| 491 |
""" |
| 492 |
return [self.get_face(i) for i in range(self.n_faces)] |
| 493 |
|
| 494 |
def get_face(self: Self, index: int) -> Cell: |
| 495 |
"""Get the i-th face composing the cell. |
| 496 |
|
| 497 |
Parameters |
| 498 |
---------- |
| 499 |
index : int |
| 500 |
Face ID. |
| 501 |
|
| 502 |
Returns |
| 503 |
------- |
| 504 |
pyvista.Cell |
| 505 |
Face given by ``index``. |
| 506 |
|
| 507 |
Examples |
| 508 |
-------- |
| 509 |
Return the face IDs composing the first face of an example tetrahedron. |
| 510 |
|
| 511 |
>>> from pyvista.examples.cells import Tetrahedron |
| 512 |
>>> mesh = Tetrahedron() |
| 513 |
>>> cell = mesh.get_cell(0) |
| 514 |
>>> face = cell.get_face(0) |
| 515 |
>>> face.point_ids |
| 516 |
[0, 1, 3] |
| 517 |
|
| 518 |
""" |
| 519 |
# must deep copy here as sequental calls overwrite the underlying pointer |
| 520 |
if index + 1 > self.n_faces: |
| 521 |
msg = f'Invalid index {index} for a cell with {self.n_faces} faces.' |
| 522 |
raise IndexError(msg) |
| 523 |
|
| 524 |
# must deep copy here as multiple sequental calls to GetFace overwrite |
| 525 |
# the underlying pointer |
| 526 |
cell = self.GetFace(index) |
| 527 |
return Cell(cell, deep=True, cell_type=cast('CellType', cell.GetCellType())) # type: ignore[abstract] |
| 528 |
|
| 529 |
@property |
| 530 |
def bounds(self: Self) -> BoundsTuple: |
| 531 |
"""Get the cell bounds in ``(x_min, x_max, y_min, y_max, z_min, z_max)``. |
| 532 |
|
| 533 |
Returns |
| 534 |
------- |
| 535 |
BoundsTuple |
| 536 |
The cell bounds in ``(x_min, x_max, y_min, y_max, z_min, z_max)``. |
| 537 |
|
| 538 |
Examples |
| 539 |
-------- |
| 540 |
>>> import pyvista as pv |
| 541 |
>>> mesh = pv.Sphere() |
| 542 |
>>> mesh.get_cell(0).bounds |
| 543 |
BoundsTuple(x_min = 0.0, |
| 544 |
x_max = 0.05405950918793678, |
| 545 |
y_min = 0.0, |
| 546 |
y_max = 0.011239604093134403, |
| 547 |
z_min = 0.49706897139549255, |
| 548 |
z_max = 0.5) |
| 549 |
|
| 550 |
""" |
| 551 |
return BoundsTuple(*self.GetBounds()) |
| 552 |
|
| 553 |
@property |
| 554 |
def center(self: Self) -> tuple[float, float, float]: |
| 555 |
"""Get the center of the cell. |
| 556 |
|
| 557 |
Uses parametric coordinate center to determine x-y-z center. |
| 558 |
|
| 559 |
Returns |
| 560 |
------- |
| 561 |
tuple[float, float, float] |
| 562 |
The center of the cell. |
| 563 |
|
| 564 |
Examples |
| 565 |
-------- |
| 566 |
>>> import pyvista as pv |
| 567 |
>>> mesh = pv.Sphere() |
| 568 |
>>> mesh.get_cell(0).center |
| 569 |
(0.03564589594801267, 0.0037465346977114677, 0.49804598093032837) |
| 570 |
|
| 571 |
""" |
| 572 |
para_center = [0.0, 0.0, 0.0] |
| 573 |
sub_id = self.GetParametricCenter(para_center) |
| 574 |
# EvaluateLocation requires mutable sub_id |
| 575 |
sub_id = _vtk.mutable(sub_id) # type: ignore[assignment] |
| 576 |
# center and weights are returned from EvaluateLocation |
| 577 |
center = [0.0, 0.0, 0.0] |
| 578 |
weights = [0.0] * self.n_points |
| 579 |
self.EvaluateLocation(sub_id, para_center, center, weights) |
| 580 |
return cast('tuple[float, float, float]', tuple(center)) |
| 581 |
|
| 582 |
def _get_attrs(self: Self) -> list[tuple[str, Any, str]]: |
| 583 |
"""Return the representation methods (internal helper).""" |
| 584 |
attrs = [] |
| 585 |
attrs.append(('Type', repr(self.type), '{}' * len(repr(self.type)))) |
| 586 |
attrs.append(('Linear', self.is_linear, '{}')) # type: ignore[arg-type] |
| 587 |
attrs.append(('Dimension', self.dimension, '{}')) # type: ignore[arg-type] |
| 588 |
attrs.append(('N Points', self.n_points, '{}')) # type: ignore[arg-type] |
| 589 |
attrs.append(('N Faces', self.n_faces, '{}')) # type: ignore[arg-type] |
| 590 |
attrs.append(('N Edges', self.n_edges, '{}')) # type: ignore[arg-type] |
| 591 |
bds = self.bounds |
| 592 |
fmt = f'{pv.FLOAT_FORMAT}, {pv.FLOAT_FORMAT}' |
| 593 |
attrs.append(('X Bounds', (bds[0], bds[1]), fmt)) # type: ignore[arg-type] |
| 594 |
attrs.append(('Y Bounds', (bds[2], bds[3]), fmt)) # type: ignore[arg-type] |
| 595 |
attrs.append(('Z Bounds', (bds[4], bds[5]), fmt)) # type: ignore[arg-type] |
| 596 |
|
| 597 |
return attrs |
| 598 |
|
| 599 |
def __repr__(self: Self) -> str: |
| 600 |
"""Return the object representation.""" |
| 601 |
return self.head(display=False, html=False) |
| 602 |
|
| 603 |
def __str__(self: Self) -> str: |
| 604 |
"""Return the object string representation.""" |
| 605 |
return self.head(display=False, html=False) |
| 606 |
|
| 607 |
@_deprecate_positional_args |
| 608 |
def copy(self: Self, deep: bool = True) -> Self: # noqa: FBT001, FBT002 |
| 609 |
"""Return a copy of the cell. |
| 610 |
|
| 611 |
Parameters |
| 612 |
---------- |
| 613 |
deep : bool, optional |
| 614 |
When ``True`` makes a full copy of the cell. When ``False``, |
| 615 |
performs a shallow copy where the new cell still references the |
| 616 |
original cell. |
| 617 |
|
| 618 |
Returns |
| 619 |
------- |
| 620 |
pyvista.Cell |
| 621 |
Deep or shallow copy of the cell. |
| 622 |
|
| 623 |
Examples |
| 624 |
-------- |
| 625 |
Create a deep copy of the cell and demonstrate it is deep. |
| 626 |
|
| 627 |
>>> from pyvista.examples.cells import Tetrahedron |
| 628 |
>>> mesh = Tetrahedron() |
| 629 |
>>> cell = mesh.get_cell(0) |
| 630 |
>>> deep_cell = cell.copy(deep=True) |
| 631 |
>>> deep_cell.points[:] = 0 |
| 632 |
>>> cell != deep_cell |
| 633 |
True |
| 634 |
|
| 635 |
Create a shallow copy of the cell and demonstrate it is shallow. |
| 636 |
|
| 637 |
>>> shallow_cell = cell.copy(deep=False) |
| 638 |
>>> shallow_cell.points[:] = 0 |
| 639 |
>>> cell == shallow_cell |
| 640 |
True |
| 641 |
|
| 642 |
""" |
| 643 |
return type(self)(self, deep=deep) |
| 644 |
|
| 645 |
|
| 646 |
class CellArray( |
| 647 |
_NoNewAttrMixin, |
| 648 |
DisableVtkSnakeCase, |
| 649 |
vtkPyVistaOverride, |
| 650 |
_vtk.vtkCellArray, |
| 651 |
): |
| 652 |
"""PyVista wrapping of :vtk:`vtkCellArray`. |
| 653 |
|
| 654 |
Provides convenience functions to simplify creating a CellArray from |
| 655 |
a numpy array or list. |
| 656 |
|
| 657 |
Parameters |
| 658 |
---------- |
| 659 |
cells : np.ndarray or list, optional |
| 660 |
Import an array of data with the legacy :vtk:`vtkCellArray` layout, e.g. |
| 661 |
``{ n0, p0_0, p0_1, ..., p0_n, n1, p1_0, p1_1, ..., p1_n, ... }`` |
| 662 |
Where n0 is the number of points in cell 0, and pX_Y is the Y'th |
| 663 |
point in cell X. |
| 664 |
|
| 665 |
Examples |
| 666 |
-------- |
| 667 |
Create a cell array containing two triangles from the traditional interleaved format |
| 668 |
|
| 669 |
>>> from pyvista.core.cell import CellArray |
| 670 |
>>> cellarr = CellArray([3, 0, 1, 2, 3, 3, 4, 5]) |
| 671 |
|
| 672 |
Create a cell array containing two triangles from separate offsets and connectivity arrays |
| 673 |
|
| 674 |
>>> from pyvista.core.cell import CellArray |
| 675 |
>>> offsets = [0, 3, 6] |
| 676 |
>>> connectivity = [0, 1, 2, 3, 4, 5] |
| 677 |
>>> cellarr = CellArray.from_arrays(offsets, connectivity) |
| 678 |
|
| 679 |
""" |
| 680 |
|
| 681 |
def __init__( |
| 682 |
self: Self, |
| 683 |
cells: CellsLike | None = None, |
| 684 |
) -> None: |
| 685 |
"""Initialize a :vtk:`vtkCellArray`.""" |
| 686 |
super().__init__() |
| 687 |
self.__offsets: _vtk.vtkIdTypeArray | None = None |
| 688 |
self.__connectivity: _vtk.vtkIdTypeArray | None = None |
| 689 |
if cells is not None: |
| 690 |
self.cells = cells |
| 691 |
|
| 692 |
@property |
| 693 |
def cells(self: Self) -> NumpyArray[int]: |
| 694 |
"""Return a numpy array of the cells. |
| 695 |
|
| 696 |
Returns |
| 697 |
------- |
| 698 |
np.ndarray |
| 699 |
A numpy array of the cells. |
| 700 |
|
| 701 |
""" |
| 702 |
cells = _vtk.vtkIdTypeArray() |
| 703 |
self.ExportLegacyFormat(cells) |
| 704 |
return _vtk.vtk_to_numpy(cells) |
| 705 |
|
| 706 |
@cells.setter |
| 707 |
def cells(self: Self, cells: CellsLike) -> None: |
| 708 |
cells = np.asarray(cells) |
| 709 |
vtk_idarr = numpy_to_idarr(cells, deep=False, return_ind=False) |
| 710 |
self.ImportLegacyFormat(vtk_idarr) |
| 711 |
|
| 712 |
self.ExportLegacyFormat(idarr := _vtk.vtkIdTypeArray()) |
| 713 |
imported_size = _vtk.vtk_to_numpy(idarr).size |
| 714 |
|
| 715 |
# https://github.com/pyvista/pyvista/pull/5404 |
| 716 |
if imported_size != cells.size: |
| 717 |
msg = ( |
| 718 |
f'Cell array size is invalid. Size ({cells.size}) does not' |
| 719 |
f' match expected size ({imported_size}). This is likely' |
| 720 |
' due to invalid connectivity array.' |
| 721 |
) |
| 722 |
raise CellSizeError(msg) |
| 723 |
self.__offsets = self.__connectivity = None |
| 724 |
|
| 725 |
@property |
| 726 |
def n_cells(self: Self) -> int: |
| 727 |
"""Return the number of cells. |
| 728 |
|
| 729 |
Returns |
| 730 |
------- |
| 731 |
int |
| 732 |
The number of cells. |
| 733 |
|
| 734 |
""" |
| 735 |
return self.GetNumberOfCells() |
| 736 |
|
| 737 |
@property |
| 738 |
def connectivity_array(self: Self) -> NumpyArray[int]: |
| 739 |
"""Return the array with the point ids that define the cells' connectivity. |
| 740 |
|
| 741 |
Returns |
| 742 |
------- |
| 743 |
np.ndarray |
| 744 |
Array with the point ids that define the cells' connectivity. |
| 745 |
|
| 746 |
""" |
| 747 |
return _get_connectivity_array(self) |
| 748 |
|
| 749 |
@property |
| 750 |
def offset_array(self: Self) -> NumpyArray[int]: |
| 751 |
"""Return the array used to store cell offsets. |
| 752 |
|
| 753 |
Returns |
| 754 |
------- |
| 755 |
np.ndarray |
| 756 |
Array used to store cell offsets. |
| 757 |
|
| 758 |
""" |
| 759 |
return _get_offset_array(self) |
| 760 |
|
| 761 |
def _set_data( |
| 762 |
self: Self, |
| 763 |
offsets: MatrixLike[int], |
| 764 |
connectivity: MatrixLike[int], |
| 765 |
*, |
| 766 |
deep: bool = False, |
| 767 |
) -> None: |
| 768 |
"""Set the offsets and connectivity arrays.""" |
| 769 |
vtk_offsets = numpy_to_idarr(offsets, deep=deep) |
| 770 |
vtk_connectivity = numpy_to_idarr(connectivity, deep=deep) |
| 771 |
self.SetData(vtk_offsets, vtk_connectivity) |
| 772 |
|
| 773 |
# Because vtkCellArray doesn't take ownership of the arrays, it's possible for them to get |
| 774 |
# garbage collected. Keep a reference to them for safety |
| 775 |
self.__offsets = vtk_offsets |
| 776 |
self.__connectivity = vtk_connectivity |
| 777 |
|
| 778 |
@staticmethod |
| 779 |
@_deprecate_positional_args(allowed=['offsets', 'connectivity']) |
| 780 |
def from_arrays( |
| 781 |
offsets: MatrixLike[int], |
| 782 |
connectivity: MatrixLike[int], |
| 783 |
deep: bool = False, # noqa: FBT001, FBT002 |
| 784 |
) -> CellArray: |
| 785 |
"""Construct a CellArray from offsets and connectivity arrays. |
| 786 |
|
| 787 |
Parameters |
| 788 |
---------- |
| 789 |
offsets : MatrixLike[int] |
| 790 |
Offsets array of length `n_cells + 1`. |
| 791 |
|
| 792 |
connectivity : MatrixLike[int] |
| 793 |
Connectivity array. |
| 794 |
|
| 795 |
deep : bool, default: False |
| 796 |
Whether to deep copy the array data into the vtk arrays. |
| 797 |
|
| 798 |
Returns |
| 799 |
------- |
| 800 |
CellArray |
| 801 |
Constructed CellArray. |
| 802 |
|
| 803 |
""" |
| 804 |
cellarr = CellArray() |
| 805 |
cellarr._set_data(offsets, connectivity, deep=deep) |
| 806 |
return cellarr |
| 807 |
|
| 808 |
@property |
| 809 |
def regular_cells(self: Self) -> NumpyArray[int]: |
| 810 |
"""Return a (n_cells, cell_size)-shaped array of point indices for equal-sized faces. |
| 811 |
|
| 812 |
Returns |
| 813 |
------- |
| 814 |
numpy.ndarray |
| 815 |
Array of face indices of shape (n_cells, cell_size). |
| 816 |
|
| 817 |
Notes |
| 818 |
----- |
| 819 |
This property does not validate that the cells are all |
| 820 |
actually the same size. If they're not, this property may either |
| 821 |
raise a `ValueError` or silently return an incorrect array. |
| 822 |
|
| 823 |
""" |
| 824 |
return _get_regular_cells(self) |
| 825 |
|
| 826 |
@classmethod |
| 827 |
@_deprecate_positional_args(allowed=['cells']) |
| 828 |
def from_regular_cells( |
| 829 |
cls: type[CellArray], |
| 830 |
cells: MatrixLike[int], |
| 831 |
deep: bool = False, # noqa: FBT001, FBT002 |
| 832 |
) -> CellArray: |
| 833 |
"""Construct a ``CellArray`` from a (n_cells, cell_size) array of cell indices. |
| 834 |
|
| 835 |
Parameters |
| 836 |
---------- |
| 837 |
cells : numpy.ndarray or list[list[int]] |
| 838 |
Cell array of shape (n_cells, cell_size) where all cells have the same `cell_size`. |
| 839 |
|
| 840 |
deep : bool, default: False |
| 841 |
Whether to deep copy the cell array data into the vtk connectivity array. |
| 842 |
|
| 843 |
Returns |
| 844 |
------- |
| 845 |
pyvista.CellArray |
| 846 |
Constructed ``CellArray``. |
| 847 |
|
| 848 |
""" |
| 849 |
cells = np.asarray(cells, dtype=pv.ID_TYPE) |
| 850 |
n_cells, cell_size = cells.shape |
| 851 |
offsets = cell_size * np.arange(n_cells + 1, dtype=pv.ID_TYPE) |
| 852 |
cellarr = cls() |
| 853 |
cellarr._set_data(offsets, cells, deep=deep) |
| 854 |
return cellarr |
| 855 |
|
| 856 |
@classmethod |
| 857 |
def from_irregular_cells(cls: type[CellArray], cells: MatrixLike[int]) -> CellArray: |
| 858 |
"""Construct a ``CellArray`` from a (n_cells, cell_size) array of cell indices. |
| 859 |
|
| 860 |
Parameters |
| 861 |
---------- |
| 862 |
cells : numpy.ndarray or list[list[int]] |
| 863 |
Cell array of shape (n_cells, cell_size) where all cells have the same `cell_size`. |
| 864 |
|
| 865 |
Returns |
| 866 |
------- |
| 867 |
pyvista.CellArray |
| 868 |
Constructed ``CellArray``. |
| 869 |
|
| 870 |
""" |
| 871 |
offsets = np.cumsum([len(c) for c in cells]) |
| 872 |
offsets = np.concatenate([[0], offsets], dtype=pv.ID_TYPE) |
| 873 |
connectivity = np.concatenate(cells, dtype=pv.ID_TYPE) |
| 874 |
return cls.from_arrays(offsets, connectivity) # type: ignore[arg-type] |
| 875 |
|
| 876 |
|
| 877 |
# The following methods would be much nicer bound to CellArray, |
| 878 |
# but then they wouldn't be available on bare vtkCellArrays. In the future, |
| 879 |
# consider using vtkCellArray.override decorator, so they're all automatically |
| 880 |
# returned as CellArrays |
| 881 |
|
| 882 |
|
| 883 |
def _get_connectivity_array(cellarr: _vtk.vtkCellArray) -> NumpyArray[int]: |
| 884 |
"""Return the array with the point ids that define the cells' connectivity.""" |
| 885 |
return _vtk.vtk_to_numpy(cellarr.GetConnectivityArray()) |
| 886 |
|
| 887 |
|
| 888 |
def _get_offset_array(cellarr: _vtk.vtkCellArray) -> NumpyArray[int]: |
| 889 |
"""Return the array used to store cell offsets.""" |
| 890 |
return _vtk.vtk_to_numpy(cellarr.GetOffsetsArray()) |
| 891 |
|
| 892 |
|
| 893 |
def _get_regular_cells(cellarr: _vtk.vtkCellArray) -> NumpyArray[int]: |
| 894 |
"""Return a (n_cells, cell_size)-shaped array of point indices for equal-sized faces.""" |
| 895 |
cells = _get_connectivity_array(cellarr) |
| 896 |
if len(cells) == 0: |
| 897 |
return cells |
| 898 |
|
| 899 |
offsets = _get_offset_array(cellarr) |
| 900 |
cell_size = offsets[1] - offsets[0] |
| 901 |
try: |
| 902 |
return cells.reshape(-1, cell_size) |
| 903 |
except ValueError: |
| 904 |
sizes = sorted(np.unique(np.diff(offsets)).tolist()) |
| 905 |
msg = ( |
| 906 |
f'Cell array does not have regular cells. ' |
| 907 |
f'Multiple cell sizes detected with different number of points: {sizes}' |
| 908 |
) |
| 909 |
raise ValueError(msg) |
| 910 |
|
| 911 |
|
| 912 |
def _get_irregular_cells(cellarr: _vtk.vtkCellArray) -> tuple[NumpyArray[int], ...]: |
| 913 |
"""Return a tuple of length n_cells of each cell's point indices.""" |
| 914 |
cells = _get_connectivity_array(cellarr) |
| 915 |
if len(cells) == 0: |
| 916 |
return () |
| 917 |
|
| 918 |
offsets = _get_offset_array(cellarr) |
| 919 |
return tuple(np.split(cells, offsets[1:-1])) |