| 1 |
"""Sub-classes for :vtk:`vtkRectilinearGrid` and :vtk:`vtkImageData`.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections.abc import Sequence |
| 6 |
from functools import wraps |
| 7 |
from pathlib import Path |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
from typing import Any |
| 10 |
from typing import ClassVar |
| 11 |
from typing import Literal |
| 12 |
from typing import cast |
| 13 |
|
| 14 |
import numpy as np |
| 15 |
|
| 16 |
import pyvista as pv |
| 17 |
from pyvista import _vtk |
| 18 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 19 |
from pyvista.core import _validation |
| 20 |
from pyvista.core.utilities.writer import BaseWriter |
| 21 |
from pyvista.core.utilities.writer import BMPWriter |
| 22 |
from pyvista.core.utilities.writer import DataSetWriter |
| 23 |
from pyvista.core.utilities.writer import JPEGWriter |
| 24 |
from pyvista.core.utilities.writer import NIFTIImageWriter |
| 25 |
from pyvista.core.utilities.writer import PNGWriter |
| 26 |
from pyvista.core.utilities.writer import PNMWriter |
| 27 |
from pyvista.core.utilities.writer import RectilinearGridWriter |
| 28 |
from pyvista.core.utilities.writer import TIFFWriter |
| 29 |
from pyvista.core.utilities.writer import XMLImageDataWriter |
| 30 |
from pyvista.core.utilities.writer import XMLRectilinearGridWriter |
| 31 |
|
| 32 |
from .dataset import DataSet |
| 33 |
from .filters import ImageDataFilters |
| 34 |
from .filters import RectilinearGridFilters |
| 35 |
from .filters import _get_output |
| 36 |
from .utilities.arrays import array_from_vtkmatrix |
| 37 |
from .utilities.arrays import convert_array |
| 38 |
from .utilities.arrays import raise_has_duplicates |
| 39 |
from .utilities.arrays import vtkmatrix_from_array |
| 40 |
from .utilities.misc import abstract_class |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from typing_extensions import Self |
| 44 |
|
| 45 |
from pyvista import StructuredGrid |
| 46 |
from pyvista import UnstructuredGrid |
| 47 |
from pyvista import pyvista_ndarray |
| 48 |
from pyvista.core._typing_core import MatrixLike |
| 49 |
from pyvista.core._typing_core import NumpyArray |
| 50 |
from pyvista.core._typing_core import RotationLike |
| 51 |
from pyvista.core._typing_core import TransformLike |
| 52 |
from pyvista.core._typing_core import VectorLike |
| 53 |
|
| 54 |
from .filters.data_object import _NestedMeshValidationFields |
| 55 |
|
| 56 |
|
| 57 |
@abstract_class |
| 58 |
class Grid(DataSet): |
| 59 |
"""A class full of common methods for non-pointset grids.""" |
| 60 |
|
| 61 |
@property |
| 62 |
def dimensions(self: Self) -> tuple[int, int, int]: |
| 63 |
"""Return the grid's dimensions. |
| 64 |
|
| 65 |
These are effectively the number of points along each of the |
| 66 |
three dataset axes. |
| 67 |
|
| 68 |
Returns |
| 69 |
------- |
| 70 |
tuple[int] |
| 71 |
Dimensions of the grid. |
| 72 |
|
| 73 |
Examples |
| 74 |
-------- |
| 75 |
Create a uniform grid with dimensions ``(1, 2, 3)``. |
| 76 |
|
| 77 |
>>> import pyvista as pv |
| 78 |
>>> grid = pv.ImageData(dimensions=(2, 3, 4)) |
| 79 |
>>> grid.dimensions |
| 80 |
(2, 3, 4) |
| 81 |
>>> grid.plot(show_edges=True) |
| 82 |
|
| 83 |
Set the dimensions to ``(3, 4, 5)`` |
| 84 |
|
| 85 |
>>> grid.dimensions = (3, 4, 5) |
| 86 |
>>> grid.plot(show_edges=True) |
| 87 |
|
| 88 |
""" |
| 89 |
return self.GetDimensions() |
| 90 |
|
| 91 |
@dimensions.setter |
| 92 |
def dimensions(self: Self, dims: VectorLike[int]) -> None: |
| 93 |
self.SetDimensions(*dims) |
| 94 |
self.Modified() |
| 95 |
|
| 96 |
def to_hexahedra(self: Self) -> UnstructuredGrid: |
| 97 |
"""Convert voxels to hexahedra. |
| 98 |
|
| 99 |
Convert this mesh to :class:`~pyvista.UnstructuredGrid` with |
| 100 |
:attr:`~pyvista.CellType.HEXAHEDRON` cells. Equivalent to |
| 101 |
:meth:`~pyvista.DataSet.cast_to_unstructured_grid` except the output has |
| 102 |
hexahedra instead of :attr:`~pyvista.CellType.VOXEL` cells. |
| 103 |
|
| 104 |
.. versionadded:: 0.48 |
| 105 |
|
| 106 |
Returns |
| 107 |
------- |
| 108 |
pyvista.UnstructuredGrid |
| 109 |
Mesh with :attr:`~pyvista.CellType.HEXAHEDRON` cells. |
| 110 |
|
| 111 |
Raises |
| 112 |
------ |
| 113 |
ValueError |
| 114 |
If the input is not 3-dimensional. |
| 115 |
|
| 116 |
See Also |
| 117 |
-------- |
| 118 |
to_quads, to_tetrahedra |
| 119 |
pyvista.DataSet.cast_to_unstructured_grid |
| 120 |
|
| 121 |
Examples |
| 122 |
-------- |
| 123 |
Convert a 3D :class:`~pyvista.ImageData` to hexahedra. |
| 124 |
|
| 125 |
>>> import pyvista as pv |
| 126 |
>>> image = pv.ImageData(dimensions=(2, 2, 2)) |
| 127 |
>>> hexes = image.to_hexahedra() |
| 128 |
>>> hexes.distinct_cell_types == {pv.CellType.HEXAHEDRON} |
| 129 |
True |
| 130 |
|
| 131 |
""" |
| 132 |
if (dim := self.dimensionality) != 3: |
| 133 |
msg = f'Input must be 3-dimensional. Got {dim}-dimensional input instead.' |
| 134 |
if dim == 2: |
| 135 |
msg += '\nUse `to_quads` for 2D inputs.' |
| 136 |
raise ValueError(msg) |
| 137 |
return self.cast_to_structured_grid().cast_to_unstructured_grid() |
| 138 |
|
| 139 |
def to_quads(self: Self) -> UnstructuredGrid: |
| 140 |
"""Convert pixels to quads. |
| 141 |
|
| 142 |
Convert this mesh to :class:`~pyvista.UnstructuredGrid` with |
| 143 |
:attr:`~pyvista.CellType.QUAD` cells. Equivalent to |
| 144 |
:meth:`~pyvista.DataSet.cast_to_unstructured_grid` except the output has |
| 145 |
quads instead of :attr:`~pyvista.CellType.PIXEL` cells. |
| 146 |
|
| 147 |
.. versionadded:: 0.48 |
| 148 |
|
| 149 |
Returns |
| 150 |
------- |
| 151 |
pyvista.UnstructuredGrid |
| 152 |
Mesh with :attr:`~pyvista.CellType.QUAD` cells. |
| 153 |
|
| 154 |
Raises |
| 155 |
------ |
| 156 |
ValueError |
| 157 |
If the input is not 2-dimensional. |
| 158 |
|
| 159 |
See Also |
| 160 |
-------- |
| 161 |
to_hexahedra, to_tetrahedra |
| 162 |
pyvista.DataSet.cast_to_unstructured_grid |
| 163 |
|
| 164 |
Examples |
| 165 |
-------- |
| 166 |
Convert a 2D :class:`~pyvista.ImageData` to quads. |
| 167 |
|
| 168 |
>>> import pyvista as pv |
| 169 |
>>> image = pv.ImageData(dimensions=(3, 2, 1)) |
| 170 |
>>> quads = image.to_quads() |
| 171 |
>>> quads.distinct_cell_types == {pv.CellType.QUAD} |
| 172 |
True |
| 173 |
|
| 174 |
""" |
| 175 |
if (dim := self.dimensionality) != 2: |
| 176 |
msg = f'Input must be 2-dimensional. Got {dim}-dimensional input instead.' |
| 177 |
if dim == 3: |
| 178 |
msg += '\nUse `to_hexahedra` for 3D inputs.' |
| 179 |
raise ValueError(msg) |
| 180 |
return self.cast_to_structured_grid().cast_to_unstructured_grid() |
| 181 |
|
| 182 |
def _get_attrs(self: Self) -> list[tuple[str, Any, str]]: |
| 183 |
"""Return the representation methods (internal helper).""" |
| 184 |
attrs = DataSet._get_attrs(self) |
| 185 |
attrs.append(('Dimensions', self.dimensions, '{:d}, {:d}, {:d}')) |
| 186 |
return attrs |
| 187 |
|
| 188 |
|
| 189 |
class RectilinearGrid(Grid, RectilinearGridFilters, _vtk.vtkRectilinearGrid): |
| 190 |
"""Dataset with variable spacing in the three coordinate directions. |
| 191 |
|
| 192 |
Can be initialized in several ways: |
| 193 |
|
| 194 |
* Create empty grid |
| 195 |
* Initialize from a :vtk:`vtkRectilinearGrid` object |
| 196 |
* Initialize directly from the point arrays |
| 197 |
|
| 198 |
Parameters |
| 199 |
---------- |
| 200 |
uinput : str, pathlib.Path, :vtk:`vtkRectilinearGrid`, numpy.ndarray, optional |
| 201 |
Filename, dataset, or array to initialize the rectilinear grid from. If a |
| 202 |
filename is passed, pyvista will attempt to load it as a |
| 203 |
:class:`RectilinearGrid`. If passed a :vtk:`vtkRectilinearGrid`, it |
| 204 |
will be wrapped. If a :class:`numpy.ndarray` is passed, this will be |
| 205 |
loaded as the x range. |
| 206 |
|
| 207 |
y : numpy.ndarray, optional |
| 208 |
Coordinates of the points in y direction. If this is passed, ``uinput`` |
| 209 |
must be a :class:`numpy.ndarray`. |
| 210 |
|
| 211 |
z : numpy.ndarray, optional |
| 212 |
Coordinates of the points in z direction. If this is passed, ``uinput`` |
| 213 |
and ``y`` must be a :class:`numpy.ndarray`. |
| 214 |
|
| 215 |
check_duplicates : bool, optional |
| 216 |
Check for duplications in any arrays that are passed. Defaults to |
| 217 |
``False``. If ``True``, an error is raised if there are any duplicate |
| 218 |
values in any of the array-valued input arguments. |
| 219 |
|
| 220 |
deep : bool, optional |
| 221 |
Whether to deep copy a :vtk:`vtkRectilinearGrid` object. |
| 222 |
Default is ``False``. Keyword only. |
| 223 |
|
| 224 |
validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False |
| 225 |
Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after |
| 226 |
initialization. Set this to ``True`` to validate all fields, or specify any |
| 227 |
combination of fields allowed by ``validate_mesh``. |
| 228 |
|
| 229 |
.. versionadded:: 0.47 |
| 230 |
|
| 231 |
Examples |
| 232 |
-------- |
| 233 |
>>> import pyvista as pv |
| 234 |
>>> import vtk |
| 235 |
>>> import numpy as np |
| 236 |
|
| 237 |
Create an empty grid. |
| 238 |
|
| 239 |
>>> grid = pv.RectilinearGrid() |
| 240 |
|
| 241 |
Initialize from a :vtk:`vtkRectilinearGrid` object |
| 242 |
|
| 243 |
>>> vtkgrid = vtk.vtkRectilinearGrid() |
| 244 |
>>> grid = pv.RectilinearGrid(vtkgrid) |
| 245 |
|
| 246 |
Create from NumPy arrays. |
| 247 |
|
| 248 |
>>> xrng = np.arange(-10, 10, 2) |
| 249 |
>>> yrng = np.arange(-10, 10, 5) |
| 250 |
>>> zrng = np.arange(-10, 10, 1) |
| 251 |
>>> grid = pv.RectilinearGrid(xrng, yrng, zrng) |
| 252 |
>>> grid.plot(show_edges=True) |
| 253 |
|
| 254 |
""" |
| 255 |
|
| 256 |
_WRITERS: ClassVar[dict[str, type[BaseWriter]]] = { |
| 257 |
'.vtk': RectilinearGridWriter, |
| 258 |
'.vtr': XMLRectilinearGridWriter, |
| 259 |
} |
| 260 |
|
| 261 |
def __init__( |
| 262 |
self: Self, |
| 263 |
*args, |
| 264 |
check_duplicates: bool = False, |
| 265 |
deep: bool = False, |
| 266 |
validate: bool | _NestedMeshValidationFields = False, |
| 267 |
**kwargs, |
| 268 |
) -> None: # numpydoc ignore=PR01,RT01 |
| 269 |
"""Initialize the rectilinear grid.""" |
| 270 |
super().__init__(**kwargs) |
| 271 |
|
| 272 |
if len(args) == 1: |
| 273 |
if isinstance(args[0], _vtk.vtkRectilinearGrid): |
| 274 |
if deep: |
| 275 |
self.deep_copy(args[0]) |
| 276 |
else: |
| 277 |
self.shallow_copy(args[0]) |
| 278 |
elif isinstance(args[0], (str, Path)): |
| 279 |
self._from_file(args[0], **kwargs) |
| 280 |
elif isinstance(args[0], (np.ndarray, Sequence)): |
| 281 |
self._from_arrays( |
| 282 |
x=np.asanyarray(args[0]), |
| 283 |
y=None, # type: ignore[arg-type] |
| 284 |
z=None, # type: ignore[arg-type] |
| 285 |
check_duplicates=check_duplicates, |
| 286 |
) |
| 287 |
else: |
| 288 |
msg = f'Type ({type(args[0])}) not understood by `RectilinearGrid`' |
| 289 |
raise TypeError(msg) |
| 290 |
|
| 291 |
elif len(args) == 3 or len(args) == 2: |
| 292 |
arg0_is_arr = isinstance(args[0], (np.ndarray, Sequence)) |
| 293 |
arg1_is_arr = isinstance(args[1], (np.ndarray, Sequence)) |
| 294 |
arg2_is_arr = isinstance(args[2], (np.ndarray, Sequence)) if len(args) == 3 else False |
| 295 |
|
| 296 |
if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]): |
| 297 |
self._from_arrays( |
| 298 |
x=np.asanyarray(args[0]), |
| 299 |
y=np.asanyarray(args[1]), |
| 300 |
z=np.asanyarray(args[2]), # type: ignore[misc] |
| 301 |
check_duplicates=check_duplicates, |
| 302 |
) |
| 303 |
elif all([arg0_is_arr, arg1_is_arr]): |
| 304 |
self._from_arrays( |
| 305 |
x=np.asanyarray(args[0]), |
| 306 |
y=np.asanyarray(args[1]), |
| 307 |
z=None, # type: ignore[arg-type] |
| 308 |
check_duplicates=check_duplicates, |
| 309 |
) |
| 310 |
else: |
| 311 |
msg = 'Arguments not understood by `RectilinearGrid`.' |
| 312 |
raise TypeError(msg) |
| 313 |
|
| 314 |
if validate: |
| 315 |
self._validate_mesh(validate) |
| 316 |
|
| 317 |
def __repr__(self: Self) -> str: |
| 318 |
"""Return the default representation.""" |
| 319 |
return DataSet.__repr__(self) |
| 320 |
|
| 321 |
def __str__(self: Self) -> str: |
| 322 |
"""Return the str representation.""" |
| 323 |
return DataSet.__str__(self) |
| 324 |
|
| 325 |
def _update_dimensions(self: Self) -> None: |
| 326 |
"""Update the dimensions if coordinates have changed.""" |
| 327 |
self.SetDimensions(len(self.x), len(self.y), len(self.z)) |
| 328 |
|
| 329 |
def _from_arrays( |
| 330 |
self: Self, |
| 331 |
*, |
| 332 |
x: NumpyArray[float], |
| 333 |
y: NumpyArray[float], |
| 334 |
z: NumpyArray[float], |
| 335 |
check_duplicates: bool = False, |
| 336 |
) -> None: |
| 337 |
"""Create VTK rectilinear grid directly from numpy arrays. |
| 338 |
|
| 339 |
Each array gives the uniques coordinates of the mesh along each axial |
| 340 |
direction. To help ensure you are using this correctly, we take the unique |
| 341 |
values of each argument. |
| 342 |
|
| 343 |
Parameters |
| 344 |
---------- |
| 345 |
x : numpy.ndarray |
| 346 |
Coordinates of the points in x direction. |
| 347 |
|
| 348 |
y : numpy.ndarray |
| 349 |
Coordinates of the points in y direction. |
| 350 |
|
| 351 |
z : numpy.ndarray |
| 352 |
Coordinates of the points in z direction. |
| 353 |
|
| 354 |
check_duplicates : bool, optional |
| 355 |
Check for duplications in any arrays that are passed. |
| 356 |
|
| 357 |
""" |
| 358 |
# Set the coordinates along each axial direction |
| 359 |
# Must at least be an x array |
| 360 |
if check_duplicates: |
| 361 |
raise_has_duplicates(x) |
| 362 |
|
| 363 |
# edges are shown as triangles if x is not floating point |
| 364 |
if not np.issubdtype(x.dtype, np.floating): |
| 365 |
x = x.astype(float) |
| 366 |
self.SetXCoordinates(convert_array(x.ravel())) |
| 367 |
if y is not None: |
| 368 |
if check_duplicates: |
| 369 |
raise_has_duplicates(y) |
| 370 |
if not np.issubdtype(y.dtype, np.floating): |
| 371 |
y = y.astype(float) |
| 372 |
self.SetYCoordinates(convert_array(y.ravel())) |
| 373 |
if z is not None: |
| 374 |
if check_duplicates: |
| 375 |
raise_has_duplicates(z) |
| 376 |
if not np.issubdtype(z.dtype, np.floating): |
| 377 |
z = z.astype(float) |
| 378 |
self.SetZCoordinates(convert_array(z.ravel())) |
| 379 |
# Ensure dimensions are properly set |
| 380 |
self._update_dimensions() |
| 381 |
|
| 382 |
@property |
| 383 |
def meshgrid( |
| 384 |
self: Self, |
| 385 |
) -> tuple[NumpyArray[float], NumpyArray[float], NumpyArray[float]]: |
| 386 |
"""Return a meshgrid of numpy arrays for this mesh. |
| 387 |
|
| 388 |
This simply returns a :func:`numpy.meshgrid` of the |
| 389 |
coordinates for this mesh in ``ij`` indexing. These are a copy |
| 390 |
of the points of this mesh. |
| 391 |
|
| 392 |
Returns |
| 393 |
------- |
| 394 |
tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray] |
| 395 |
Tuple of numpy arrays representing the points of this mesh. |
| 396 |
|
| 397 |
""" |
| 398 |
# Converting to tuple needed to be consistent type across numpy version |
| 399 |
# Remove when support is dropped for numpy 1.x |
| 400 |
# We also know this is 3-length so make it so in typing |
| 401 |
out = tuple(np.meshgrid(self.x, self.y, self.z, indexing='ij')) |
| 402 |
# Python 3.8 does not allow subscripting tuple, but only used for type checking |
| 403 |
if TYPE_CHECKING: |
| 404 |
out = cast('tuple[NumpyArray[float], NumpyArray[float], NumpyArray[float]]', out) |
| 405 |
return out |
| 406 |
|
| 407 |
@property # type: ignore[override] |
| 408 |
def points(self: Self) -> NumpyArray[float]: |
| 409 |
"""Return a copy of the points as an ``(n, 3)`` numpy array. |
| 410 |
|
| 411 |
Returns |
| 412 |
------- |
| 413 |
numpy.ndarray |
| 414 |
Array of points. |
| 415 |
|
| 416 |
Notes |
| 417 |
----- |
| 418 |
Points of a :class:`pyvista.RectilinearGrid` cannot be |
| 419 |
set. Set point coordinates with :attr:`RectilinearGrid.x`, |
| 420 |
:attr:`RectilinearGrid.y`, or :attr:`RectilinearGrid.z`. |
| 421 |
|
| 422 |
Examples |
| 423 |
-------- |
| 424 |
>>> import numpy as np |
| 425 |
>>> import pyvista as pv |
| 426 |
>>> xrng = np.arange(-10, 10, 10, dtype=float) |
| 427 |
>>> yrng = np.arange(-10, 10, 10, dtype=float) |
| 428 |
>>> zrng = np.arange(-10, 10, 10, dtype=float) |
| 429 |
>>> grid = pv.RectilinearGrid(xrng, yrng, zrng) |
| 430 |
>>> grid.points |
| 431 |
array([[-10., -10., -10.], |
| 432 |
[ 0., -10., -10.], |
| 433 |
[-10., 0., -10.], |
| 434 |
[ 0., 0., -10.], |
| 435 |
[-10., -10., 0.], |
| 436 |
[ 0., -10., 0.], |
| 437 |
[-10., 0., 0.], |
| 438 |
[ 0., 0., 0.]]) |
| 439 |
|
| 440 |
""" |
| 441 |
if pv.vtk_version_info >= (9, 4, 0): |
| 442 |
return convert_array(self.GetPoints().GetData()) |
| 443 |
|
| 444 |
xx, yy, zz = self.meshgrid |
| 445 |
return np.c_[xx.ravel(order='F'), yy.ravel(order='F'), zz.ravel(order='F')] |
| 446 |
|
| 447 |
@points.setter |
| 448 |
def points( |
| 449 |
self: Self, |
| 450 |
points: MatrixLike[float] | _vtk.vtkPoints, # noqa: ARG002 |
| 451 |
) -> None: # numpydoc ignore=PR01 |
| 452 |
"""Raise an AttributeError. |
| 453 |
|
| 454 |
This setter overrides the base class's setter to ensure a user |
| 455 |
does not attempt to set them. |
| 456 |
""" |
| 457 |
msg = ( |
| 458 |
'The points cannot be set. The points of ' |
| 459 |
'`RectilinearGrid` are defined in each axial direction. Please ' |
| 460 |
'use the `x`, `y`, and `z` setters individually.' |
| 461 |
) |
| 462 |
raise AttributeError(msg) |
| 463 |
|
| 464 |
@property |
| 465 |
def x(self: Self) -> NumpyArray[float]: |
| 466 |
"""Return or set the coordinates along the X-direction. |
| 467 |
|
| 468 |
Returns |
| 469 |
------- |
| 470 |
numpy.ndarray |
| 471 |
Array of points along the X-direction. |
| 472 |
|
| 473 |
Examples |
| 474 |
-------- |
| 475 |
Return the x coordinates of a RectilinearGrid. |
| 476 |
|
| 477 |
>>> import numpy as np |
| 478 |
>>> import pyvista as pv |
| 479 |
>>> xrng = np.arange(-10, 10, 10, dtype=float) |
| 480 |
>>> yrng = np.arange(-10, 10, 10, dtype=float) |
| 481 |
>>> zrng = np.arange(-10, 10, 10, dtype=float) |
| 482 |
>>> grid = pv.RectilinearGrid(xrng, yrng, zrng) |
| 483 |
>>> grid.x |
| 484 |
array([-10., 0.]) |
| 485 |
|
| 486 |
Set the x coordinates of a RectilinearGrid. |
| 487 |
|
| 488 |
>>> grid.x = [-10.0, 0.0, 10.0] |
| 489 |
>>> grid.x |
| 490 |
array([-10., 0., 10.]) |
| 491 |
|
| 492 |
""" |
| 493 |
return convert_array(self.GetXCoordinates()) |
| 494 |
|
| 495 |
@x.setter |
| 496 |
def x(self: Self, coords: VectorLike[float]) -> None: |
| 497 |
self.SetXCoordinates(convert_array(coords)) |
| 498 |
self._update_dimensions() |
| 499 |
self.Modified() |
| 500 |
|
| 501 |
@property |
| 502 |
def y(self: Self) -> NumpyArray[float]: |
| 503 |
"""Return or set the coordinates along the Y-direction. |
| 504 |
|
| 505 |
Returns |
| 506 |
------- |
| 507 |
numpy.ndarray |
| 508 |
Array of points along the Y-direction. |
| 509 |
|
| 510 |
Examples |
| 511 |
-------- |
| 512 |
Return the y coordinates of a RectilinearGrid. |
| 513 |
|
| 514 |
>>> import numpy as np |
| 515 |
>>> import pyvista as pv |
| 516 |
>>> xrng = np.arange(-10, 10, 10, dtype=float) |
| 517 |
>>> yrng = np.arange(-10, 10, 10, dtype=float) |
| 518 |
>>> zrng = np.arange(-10, 10, 10, dtype=float) |
| 519 |
>>> grid = pv.RectilinearGrid(xrng, yrng, zrng) |
| 520 |
>>> grid.y |
| 521 |
array([-10., 0.]) |
| 522 |
|
| 523 |
Set the y coordinates of a RectilinearGrid. |
| 524 |
|
| 525 |
>>> grid.y = [-10.0, 0.0, 10.0] |
| 526 |
>>> grid.y |
| 527 |
array([-10., 0., 10.]) |
| 528 |
|
| 529 |
""" |
| 530 |
return convert_array(self.GetYCoordinates()) |
| 531 |
|
| 532 |
@y.setter |
| 533 |
def y(self: Self, coords: VectorLike[float]) -> None: |
| 534 |
self.SetYCoordinates(convert_array(coords)) |
| 535 |
self._update_dimensions() |
| 536 |
self.Modified() |
| 537 |
|
| 538 |
@property |
| 539 |
def z(self: Self) -> NumpyArray[float]: |
| 540 |
"""Return or set the coordinates along the Z-direction. |
| 541 |
|
| 542 |
Returns |
| 543 |
------- |
| 544 |
numpy.ndarray |
| 545 |
Array of points along the Z-direction. |
| 546 |
|
| 547 |
Examples |
| 548 |
-------- |
| 549 |
Return the z coordinates of a RectilinearGrid. |
| 550 |
|
| 551 |
>>> import numpy as np |
| 552 |
>>> import pyvista as pv |
| 553 |
>>> xrng = np.arange(-10, 10, 10, dtype=float) |
| 554 |
>>> yrng = np.arange(-10, 10, 10, dtype=float) |
| 555 |
>>> zrng = np.arange(-10, 10, 10, dtype=float) |
| 556 |
>>> grid = pv.RectilinearGrid(xrng, yrng, zrng) |
| 557 |
>>> grid.z |
| 558 |
array([-10., 0.]) |
| 559 |
|
| 560 |
Set the z coordinates of a RectilinearGrid. |
| 561 |
|
| 562 |
>>> grid.z = [-10.0, 0.0, 10.0] |
| 563 |
>>> grid.z |
| 564 |
array([-10., 0., 10.]) |
| 565 |
|
| 566 |
""" |
| 567 |
return convert_array(self.GetZCoordinates()) |
| 568 |
|
| 569 |
@z.setter |
| 570 |
def z(self: Self, coords: VectorLike[float]) -> None: |
| 571 |
self.SetZCoordinates(convert_array(coords)) |
| 572 |
self._update_dimensions() |
| 573 |
self.Modified() |
| 574 |
|
| 575 |
@Grid.dimensions.setter # type: ignore[attr-defined] |
| 576 |
def dimensions(self: Self, _dims: VectorLike[int]) -> None: |
| 577 |
"""Set Dimensions. |
| 578 |
|
| 579 |
Parameters |
| 580 |
---------- |
| 581 |
_dims : sequence |
| 582 |
Ignored dimensions. |
| 583 |
|
| 584 |
""" |
| 585 |
msg = ( |
| 586 |
'The dimensions of a `RectilinearGrid` are implicitly defined and thus cannot be set.' |
| 587 |
) |
| 588 |
raise AttributeError(msg) |
| 589 |
|
| 590 |
def cast_to_structured_grid(self: Self) -> StructuredGrid: |
| 591 |
"""Cast this rectilinear grid to a :class:`~pyvista.StructuredGrid`. |
| 592 |
|
| 593 |
.. note:: |
| 594 |
|
| 595 |
Casting converts :class:`~pyvista.CellType.PIXEL` cells to |
| 596 |
:class:`~pyvista.CellType.QUAD` cells for 2D inputs, and |
| 597 |
:class:`~pyvista.CellType.VOXEL` cells to :class:`~pyvista.CellType.HEXAHEDRON` cells |
| 598 |
for 3D inputs. To preserve cell type, use |
| 599 |
:meth:`~pyvista.DataSet.cast_to_unstructured_grid` instead. |
| 600 |
|
| 601 |
Returns |
| 602 |
------- |
| 603 |
pyvista.StructuredGrid |
| 604 |
This grid as a structured grid. |
| 605 |
|
| 606 |
""" |
| 607 |
alg = _vtk.vtkRectilinearGridToPointSet() |
| 608 |
alg.SetInputData(self) |
| 609 |
alg.Update() |
| 610 |
return _get_output(alg) |
| 611 |
|
| 612 |
|
| 613 |
class ImageData(Grid, ImageDataFilters, _vtk.vtkImageData): |
| 614 |
"""Models datasets with uniform spacing in the three coordinate directions. |
| 615 |
|
| 616 |
Can be initialized in one of several ways: |
| 617 |
|
| 618 |
- Create empty grid |
| 619 |
- Initialize from a :vtk:`vtkImageData` object |
| 620 |
- Initialize based on dimensions, cell spacing, and origin. |
| 621 |
|
| 622 |
.. versionchanged:: 0.33.0 |
| 623 |
First argument must now be either a path or |
| 624 |
:vtk:`vtkImageData`. Use keyword arguments to specify the |
| 625 |
dimensions, spacing, and origin of the uniform grid. |
| 626 |
|
| 627 |
.. versionchanged:: 0.37.0 |
| 628 |
The ``dims`` parameter has been renamed to ``dimensions``. |
| 629 |
|
| 630 |
Parameters |
| 631 |
---------- |
| 632 |
uinput : str | :vtk:`vtkImageData` | ImageData, optional |
| 633 |
Filename or dataset to initialize the uniform grid from. If |
| 634 |
set, remainder of arguments are ignored. |
| 635 |
|
| 636 |
dimensions : sequence[int], optional |
| 637 |
:attr:`dimensions` of the uniform grid. |
| 638 |
|
| 639 |
spacing : sequence[float], default: (1.0, 1.0, 1.0) |
| 640 |
:attr:`spacing` of the uniform grid in each dimension. Must be positive. |
| 641 |
|
| 642 |
origin : sequence[float], default: (0.0, 0.0, 0.0) |
| 643 |
:attr:`origin` of the uniform grid. |
| 644 |
|
| 645 |
deep : bool, default: False |
| 646 |
Whether to deep copy a :vtk:`vtkImageData` object. Keyword only. |
| 647 |
|
| 648 |
direction_matrix : RotationLike, optional |
| 649 |
The :attr:`direction_matrix` is a 3x3 matrix which controls the orientation of |
| 650 |
the image data. |
| 651 |
|
| 652 |
.. versionadded:: 0.45 |
| 653 |
|
| 654 |
offset : int | VectorLike[int], default: (0, 0, 0) |
| 655 |
The offset defines the minimum :attr:`extent` of the image. Offset values |
| 656 |
can be positive or negative. In physical space, the offset is relative |
| 657 |
to the image's :attr:`origin`. |
| 658 |
|
| 659 |
.. versionadded:: 0.45 |
| 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 |
:ref:`create_uniform_grid_example` |
| 671 |
|
| 672 |
Examples |
| 673 |
-------- |
| 674 |
Create an empty ImageData. |
| 675 |
|
| 676 |
>>> import pyvista as pv |
| 677 |
>>> grid = pv.ImageData() |
| 678 |
|
| 679 |
Initialize from a :vtk:`vtkImageData` object. |
| 680 |
|
| 681 |
>>> import vtk |
| 682 |
>>> vtkgrid = vtk.vtkImageData() |
| 683 |
>>> grid = pv.ImageData(vtkgrid) |
| 684 |
|
| 685 |
Initialize using just the grid dimensions and default |
| 686 |
spacing and origin. These must be keyword arguments. |
| 687 |
|
| 688 |
>>> grid = pv.ImageData(dimensions=(10, 10, 10)) |
| 689 |
|
| 690 |
Initialize using dimensions and spacing. |
| 691 |
|
| 692 |
>>> grid = pv.ImageData( |
| 693 |
... dimensions=(10, 10, 10), |
| 694 |
... spacing=(2, 1, 5), |
| 695 |
... ) |
| 696 |
|
| 697 |
Initialize using dimensions, spacing, and an origin. |
| 698 |
|
| 699 |
>>> grid = pv.ImageData( |
| 700 |
... dimensions=(10, 10, 10), |
| 701 |
... spacing=(2, 1, 5), |
| 702 |
... origin=(10, 35, 50), |
| 703 |
... ) |
| 704 |
|
| 705 |
Initialize from another ImageData. |
| 706 |
|
| 707 |
>>> grid = pv.ImageData( |
| 708 |
... dimensions=(10, 10, 10), |
| 709 |
... spacing=(2, 1, 5), |
| 710 |
... origin=(10, 35, 50), |
| 711 |
... ) |
| 712 |
>>> grid_from_grid = pv.ImageData(grid) |
| 713 |
>>> grid_from_grid == grid |
| 714 |
True |
| 715 |
|
| 716 |
""" |
| 717 |
|
| 718 |
_WRITERS: ClassVar[dict[str, type[BaseWriter]]] = { |
| 719 |
'.bmp': BMPWriter, |
| 720 |
'.jpeg': JPEGWriter, |
| 721 |
'.jpg': JPEGWriter, |
| 722 |
'.nii': NIFTIImageWriter, |
| 723 |
'.nii.gz': NIFTIImageWriter, |
| 724 |
'.png': PNGWriter, |
| 725 |
'.pnm': PNMWriter, |
| 726 |
'.tif': TIFFWriter, |
| 727 |
'.tiff': TIFFWriter, |
| 728 |
'.vtk': DataSetWriter, |
| 729 |
'.vti': XMLImageDataWriter, |
| 730 |
} |
| 731 |
|
| 732 |
@_deprecate_positional_args(allowed=['uinput']) |
| 733 |
def __init__( # noqa: PLR0917 |
| 734 |
self: Self, |
| 735 |
uinput: ImageData | str | Path | None = None, |
| 736 |
dimensions: VectorLike[int] | None = None, |
| 737 |
spacing: VectorLike[float] = (1.0, 1.0, 1.0), |
| 738 |
origin: VectorLike[float] = (0.0, 0.0, 0.0), |
| 739 |
deep: bool = False, # noqa: FBT001, FBT002 |
| 740 |
direction_matrix: RotationLike | None = None, |
| 741 |
offset: int | VectorLike[int] | None = None, |
| 742 |
*, |
| 743 |
validate: bool | _NestedMeshValidationFields = False, |
| 744 |
) -> None: |
| 745 |
"""Initialize the uniform grid.""" |
| 746 |
super().__init__() |
| 747 |
|
| 748 |
# first argument must be either vtkImageData or a path |
| 749 |
if uinput is not None: |
| 750 |
if isinstance(uinput, _vtk.vtkImageData): |
| 751 |
if deep: |
| 752 |
self.deep_copy(uinput) |
| 753 |
else: |
| 754 |
self.shallow_copy(uinput) |
| 755 |
elif isinstance(uinput, (str, Path)): |
| 756 |
self._from_file(uinput) |
| 757 |
else: |
| 758 |
msg = ( # type: ignore[unreachable] |
| 759 |
'First argument, ``uinput`` must be either ``vtkImageData`` ' |
| 760 |
f'or a path, not {type(uinput)}. Use keyword arguments to ' |
| 761 |
'specify dimensions, spacing, and origin. For example:\n\n' |
| 762 |
' >>> grid = pv.ImageData(\n' |
| 763 |
' ... dimensions=(10, 10, 10),\n' |
| 764 |
' ... spacing=(2, 1, 5),\n' |
| 765 |
' ... origin=(10, 35, 50),\n' |
| 766 |
' ... )\n' |
| 767 |
) |
| 768 |
raise TypeError(msg) |
| 769 |
else: |
| 770 |
if dimensions is not None: |
| 771 |
self.dimensions = dimensions |
| 772 |
self.origin = origin |
| 773 |
self.spacing = spacing |
| 774 |
if direction_matrix is not None: |
| 775 |
self.direction_matrix = direction_matrix |
| 776 |
if offset is not None: |
| 777 |
self.offset = offset |
| 778 |
|
| 779 |
if validate: |
| 780 |
self._validate_mesh(validate) |
| 781 |
|
| 782 |
def __repr__(self: Self) -> str: |
| 783 |
"""Return the default representation.""" |
| 784 |
return DataSet.__repr__(self) |
| 785 |
|
| 786 |
def __str__(self: Self) -> str: |
| 787 |
"""Return the default str representation.""" |
| 788 |
return DataSet.__str__(self) |
| 789 |
|
| 790 |
def __getitem__( # type: ignore[override] |
| 791 |
self, key: tuple[str, Literal['cell', 'point', 'field']] | str | tuple[int, int, int] |
| 792 |
) -> ImageData | pyvista_ndarray: |
| 793 |
"""Search for a data array or slice with IJK indexing.""" |
| 794 |
# Return point, cell, or field data |
| 795 |
if isinstance(key, str) or ( |
| 796 |
isinstance(key, tuple) and len(key) > 0 and isinstance(key[0], str) # type: ignore[redundant-expr] |
| 797 |
): |
| 798 |
return super().__getitem__(key) |
| 799 |
return self.extract_subset(self._compute_voi_from_index(key), rebase_coordinates=False) |
| 800 |
|
| 801 |
def _compute_voi_from_index( |
| 802 |
self, |
| 803 |
indices: tuple[ |
| 804 |
int | slice | tuple[int, int], |
| 805 |
int | slice | tuple[int, int], |
| 806 |
int | slice | tuple[int, int], |
| 807 |
], |
| 808 |
*, |
| 809 |
index_mode: Literal['extent', 'dimensions'] = 'dimensions', |
| 810 |
strict_index: bool = False, |
| 811 |
) -> NumpyArray[int]: |
| 812 |
"""Compute VOI extents from indexing values.""" |
| 813 |
_validation.check_contains( |
| 814 |
['extent', 'dimensions'], must_contain=index_mode, name='index_mode' |
| 815 |
) |
| 816 |
if not (isinstance(indices, tuple) and len(indices) == 3): # type: ignore[redundant-expr] |
| 817 |
msg = 'Exactly 3 slices must be specified, one for each IJK-coordinate axis.' # type: ignore[unreachable] |
| 818 |
raise IndexError(msg) |
| 819 |
|
| 820 |
dims = self.dimensions |
| 821 |
extent = self.extent |
| 822 |
voi = list(extent) |
| 823 |
|
| 824 |
for axis, slicer in enumerate(indices): |
| 825 |
_validation.check_instance(slicer, (int, tuple, list, slice), name='index') |
| 826 |
|
| 827 |
offset = extent[axis * 2] |
| 828 |
index_offset = 0 if index_mode == 'extent' else offset |
| 829 |
|
| 830 |
if isinstance(slicer, (list, tuple)): |
| 831 |
rng = _validation.validate_array( |
| 832 |
slicer, must_have_dtype=int, must_have_length=2, to_list=True |
| 833 |
) |
| 834 |
slicer = slice(*rng) # noqa: PLW2901 |
| 835 |
|
| 836 |
if isinstance(slicer, slice): |
| 837 |
start = slicer.start if slicer.start is not None else 0 |
| 838 |
stop = slicer.stop if slicer.stop is not None else dims[axis] |
| 839 |
step = slicer.step |
| 840 |
if step not in (None, 1): |
| 841 |
msg = 'Only contiguous slices with step=1 are supported.' |
| 842 |
raise ValueError(msg) |
| 843 |
|
| 844 |
# Handle negative indices |
| 845 |
if start < 0: |
| 846 |
start += dims[axis] |
| 847 |
if stop < 0: |
| 848 |
stop += dims[axis] |
| 849 |
|
| 850 |
else: # isinstance(slicer, int) |
| 851 |
min_allowed = offset - dims[axis] - index_offset |
| 852 |
max_allowed = min_allowed + dims[axis] * 2 - 1 |
| 853 |
if slicer < min_allowed or slicer > max_allowed: |
| 854 |
msg = ( |
| 855 |
f'index {slicer} is out of bounds for axis {axis} with size {dims[axis]}.' |
| 856 |
f'\nValid range of valid index values (inclusive) is ' |
| 857 |
f'[{min_allowed}, {max_allowed}].' |
| 858 |
) |
| 859 |
raise IndexError(msg) |
| 860 |
if slicer < 0: |
| 861 |
slicer += dims[axis] # noqa: PLW2901 |
| 862 |
start = slicer |
| 863 |
stop = start + 1 |
| 864 |
|
| 865 |
voi[axis * 2] = index_offset + start |
| 866 |
voi[axis * 2 + 1] = index_offset + stop - 1 |
| 867 |
|
| 868 |
clipped = pv.ImageDataFilters._clip_extent(voi, clip_to=self.extent) |
| 869 |
if strict_index and ( |
| 870 |
any(min_ < clp for min_, clp in zip(voi[::2], clipped[::2], strict=True)) |
| 871 |
or any(max_ > clp for max_, clp in zip(voi[1::2], clipped[1::2], strict=True)) |
| 872 |
): |
| 873 |
msg = ( |
| 874 |
f'The requested volume of interest {tuple(voi)} ' |
| 875 |
f"is outside the input's extent {extent}." |
| 876 |
) |
| 877 |
raise IndexError(msg) |
| 878 |
return clipped |
| 879 |
|
| 880 |
@property # type: ignore[override] |
| 881 |
def points(self: Self) -> NumpyArray[float]: |
| 882 |
"""Build a copy of the implicitly defined points as a numpy array. |
| 883 |
|
| 884 |
Returns |
| 885 |
------- |
| 886 |
numpy.ndarray |
| 887 |
Array of points representing the image data. |
| 888 |
|
| 889 |
Notes |
| 890 |
----- |
| 891 |
The ``points`` for a :class:`pyvista.ImageData` cannot be set. |
| 892 |
|
| 893 |
Examples |
| 894 |
-------- |
| 895 |
>>> import pyvista as pv |
| 896 |
>>> grid = pv.ImageData(dimensions=(2, 2, 2)) |
| 897 |
>>> grid.points |
| 898 |
array([[0., 0., 0.], |
| 899 |
[1., 0., 0.], |
| 900 |
[0., 1., 0.], |
| 901 |
[1., 1., 0.], |
| 902 |
[0., 0., 1.], |
| 903 |
[1., 0., 1.], |
| 904 |
[0., 1., 1.], |
| 905 |
[1., 1., 1.]]) |
| 906 |
|
| 907 |
""" |
| 908 |
if pv.vtk_version_info >= (9, 4, 0): |
| 909 |
return convert_array(self.GetPoints().GetData()) |
| 910 |
|
| 911 |
# Handle empty case |
| 912 |
if not all(self.dimensions): |
| 913 |
return np.zeros((0, 3)) |
| 914 |
|
| 915 |
# Get grid dimensions |
| 916 |
nx, ny, nz = self.dimensions |
| 917 |
nx -= 1 |
| 918 |
ny -= 1 |
| 919 |
nz -= 1 |
| 920 |
# get the points and convert to spacings |
| 921 |
dx, dy, dz = self.spacing |
| 922 |
# Now make the cell arrays |
| 923 |
ox, oy, oz = np.array(self.origin) + self.extent[::2] * np.array([dx, dy, dz]) |
| 924 |
x = np.insert(np.cumsum(np.full(nx, dx)), 0, 0.0) + ox |
| 925 |
y = np.insert(np.cumsum(np.full(ny, dy)), 0, 0.0) + oy |
| 926 |
z = np.insert(np.cumsum(np.full(nz, dz)), 0, 0.0) + oz |
| 927 |
xx, yy, zz = np.meshgrid(x, y, z, indexing='ij') |
| 928 |
points = np.c_[xx.ravel(order='F'), yy.ravel(order='F'), zz.ravel(order='F')] |
| 929 |
|
| 930 |
direction = self.direction_matrix |
| 931 |
if not np.array_equal(direction, np.eye(3)): |
| 932 |
return pv.Transform().rotate(direction, point=self.origin).apply(points, copy=False) |
| 933 |
return points |
| 934 |
|
| 935 |
@points.setter |
| 936 |
def points( |
| 937 |
self: Self, |
| 938 |
points: MatrixLike[float] | _vtk.vtkPoints, # noqa: ARG002 |
| 939 |
) -> None: # numpydoc ignore=PR01 |
| 940 |
"""Points cannot be set. |
| 941 |
|
| 942 |
This setter overrides the base class's setter to ensure a user does not |
| 943 |
attempt to set them. See https://github.com/pyvista/pyvista/issues/713. |
| 944 |
|
| 945 |
""" |
| 946 |
msg = ( |
| 947 |
'The points cannot be set. The points of ' |
| 948 |
'`ImageData`/`vtkImageData` are implicitly defined by the ' |
| 949 |
'`origin`, `spacing`, and `dimensions` of the grid.' |
| 950 |
) |
| 951 |
raise AttributeError(msg) |
| 952 |
|
| 953 |
@property |
| 954 |
def x(self: Self) -> NumpyArray[float]: # numpydoc ignore=RT01 |
| 955 |
"""Return all the X points. |
| 956 |
|
| 957 |
Examples |
| 958 |
-------- |
| 959 |
>>> import pyvista as pv |
| 960 |
>>> grid = pv.ImageData(dimensions=(2, 2, 2)) |
| 961 |
>>> grid.x |
| 962 |
array([0., 1., 0., 1., 0., 1., 0., 1.]) |
| 963 |
|
| 964 |
""" |
| 965 |
return self.points[:, 0] |
| 966 |
|
| 967 |
@property |
| 968 |
def y(self: Self) -> NumpyArray[float]: # numpydoc ignore=RT01 |
| 969 |
"""Return all the Y points. |
| 970 |
|
| 971 |
Examples |
| 972 |
-------- |
| 973 |
>>> import pyvista as pv |
| 974 |
>>> grid = pv.ImageData(dimensions=(2, 2, 2)) |
| 975 |
>>> grid.y |
| 976 |
array([0., 0., 1., 1., 0., 0., 1., 1.]) |
| 977 |
|
| 978 |
""" |
| 979 |
return self.points[:, 1] |
| 980 |
|
| 981 |
@property |
| 982 |
def z(self: Self) -> NumpyArray[float]: # numpydoc ignore=RT01 |
| 983 |
"""Return all the Z points. |
| 984 |
|
| 985 |
Examples |
| 986 |
-------- |
| 987 |
>>> import pyvista as pv |
| 988 |
>>> grid = pv.ImageData(dimensions=(2, 2, 2)) |
| 989 |
>>> grid.z |
| 990 |
array([0., 0., 0., 0., 1., 1., 1., 1.]) |
| 991 |
|
| 992 |
""" |
| 993 |
return self.points[:, 2] |
| 994 |
|
| 995 |
@property |
| 996 |
def origin(self: Self) -> tuple[float]: # numpydoc ignore=RT01 |
| 997 |
"""Return the origin of the grid (bottom southwest corner). |
| 998 |
|
| 999 |
Examples |
| 1000 |
-------- |
| 1001 |
>>> import pyvista as pv |
| 1002 |
>>> grid = pv.ImageData(dimensions=(5, 5, 5)) |
| 1003 |
>>> grid.origin |
| 1004 |
(0.0, 0.0, 0.0) |
| 1005 |
|
| 1006 |
Show how the origin is in the bottom "southwest" corner of the |
| 1007 |
ImageData. |
| 1008 |
|
| 1009 |
>>> pl = pv.Plotter() |
| 1010 |
>>> _ = pl.add_mesh(grid, show_edges=True) |
| 1011 |
>>> _ = pl.add_axes_at_origin(ylabel=None) |
| 1012 |
>>> pl.camera_position = 'xz' |
| 1013 |
>>> pl.show() |
| 1014 |
|
| 1015 |
Set the origin to ``(1, 1, 1)`` and show how this shifts the |
| 1016 |
ImageData. |
| 1017 |
|
| 1018 |
>>> grid.origin = (1, 1, 1) |
| 1019 |
>>> pl = pv.Plotter() |
| 1020 |
>>> _ = pl.add_mesh(grid, show_edges=True) |
| 1021 |
>>> _ = pl.add_axes_at_origin(ylabel=None) |
| 1022 |
>>> pl.camera_position = 'xz' |
| 1023 |
>>> pl.show() |
| 1024 |
|
| 1025 |
""" |
| 1026 |
return self.GetOrigin() # type: ignore[return-value] |
| 1027 |
|
| 1028 |
@origin.setter |
| 1029 |
def origin(self: Self, origin: VectorLike[float]) -> None: |
| 1030 |
self.SetOrigin(*origin) |
| 1031 |
self.Modified() |
| 1032 |
|
| 1033 |
@property |
| 1034 |
def spacing(self: Self) -> tuple[float, float, float]: # numpydoc ignore=RT01 |
| 1035 |
"""Return or set the spacing for each axial direction. |
| 1036 |
|
| 1037 |
Notes |
| 1038 |
----- |
| 1039 |
Spacing must be non-negative. While VTK accepts negative |
| 1040 |
spacing, this results in unexpected behavior. See: |
| 1041 |
https://github.com/pyvista/pyvista/issues/1967 |
| 1042 |
|
| 1043 |
Examples |
| 1044 |
-------- |
| 1045 |
Create a 5 x 5 x 5 uniform grid. |
| 1046 |
|
| 1047 |
>>> import pyvista as pv |
| 1048 |
>>> grid = pv.ImageData(dimensions=(5, 5, 5)) |
| 1049 |
>>> grid.spacing |
| 1050 |
(1.0, 1.0, 1.0) |
| 1051 |
>>> grid.plot(show_edges=True) |
| 1052 |
|
| 1053 |
Modify the spacing to ``(1, 2, 3)`` |
| 1054 |
|
| 1055 |
>>> grid.spacing = (1, 2, 3) |
| 1056 |
>>> grid.plot(show_edges=True) |
| 1057 |
|
| 1058 |
""" |
| 1059 |
return self.GetSpacing() |
| 1060 |
|
| 1061 |
@spacing.setter |
| 1062 |
def spacing(self: Self, spacing: VectorLike[float]) -> None: |
| 1063 |
spacing_ = _validation.validate_array3( |
| 1064 |
spacing, must_be_in_range=[0, float('inf')], name='spacing' |
| 1065 |
) |
| 1066 |
self.SetSpacing(*spacing_) |
| 1067 |
self.Modified() |
| 1068 |
|
| 1069 |
def _get_attrs(self: Self) -> list[tuple[str, Any, str]]: |
| 1070 |
"""Return the representation methods (internal helper).""" |
| 1071 |
attrs = Grid._get_attrs(self) |
| 1072 |
fmt = '{}, {}, {}'.format(*[pv.FLOAT_FORMAT] * 3) |
| 1073 |
attrs.append(('Spacing', self.spacing, fmt)) |
| 1074 |
return attrs |
| 1075 |
|
| 1076 |
def cast_to_structured_grid(self: Self) -> StructuredGrid: |
| 1077 |
"""Cast this image data to a :class:`~pyvista.StructuredGrid`. |
| 1078 |
|
| 1079 |
.. note:: |
| 1080 |
|
| 1081 |
Casting converts :class:`~pyvista.CellType.PIXEL` cells to |
| 1082 |
:class:`~pyvista.CellType.QUAD` cells for 2D inputs, and |
| 1083 |
:class:`~pyvista.CellType.VOXEL` cells to :class:`~pyvista.CellType.HEXAHEDRON` cells |
| 1084 |
for 3D inputs. To preserve cell type, use |
| 1085 |
:meth:`~pyvista.DataSet.cast_to_unstructured_grid` instead. |
| 1086 |
|
| 1087 |
Returns |
| 1088 |
------- |
| 1089 |
pyvista.StructuredGrid |
| 1090 |
This grid as a structured grid. |
| 1091 |
|
| 1092 |
""" |
| 1093 |
alg = _vtk.vtkImageToStructuredGrid() |
| 1094 |
alg.SetInputData(self) |
| 1095 |
alg.Update() |
| 1096 |
out = _get_output(alg) |
| 1097 |
out.set_active_scalars(self.active_scalars_name) |
| 1098 |
return out |
| 1099 |
|
| 1100 |
def cast_to_rectilinear_grid(self: Self) -> RectilinearGrid: |
| 1101 |
"""Cast this uniform grid to a rectilinear grid. |
| 1102 |
|
| 1103 |
Returns |
| 1104 |
------- |
| 1105 |
pyvista.RectilinearGrid |
| 1106 |
This uniform grid as a rectilinear grid. |
| 1107 |
|
| 1108 |
""" |
| 1109 |
rectilinear_coords = self._generate_rectilinear_coords() |
| 1110 |
grid = pv.RectilinearGrid(*rectilinear_coords) |
| 1111 |
grid.point_data.update(self.point_data) |
| 1112 |
grid.cell_data.update(self.cell_data) |
| 1113 |
grid.field_data.update(self.field_data) |
| 1114 |
grid.copy_meta_from(self, deep=True) |
| 1115 |
return grid |
| 1116 |
|
| 1117 |
def _generate_rectilinear_coords( |
| 1118 |
self: Self, |
| 1119 |
) -> list[NumpyArray[float]]: |
| 1120 |
"""Generate rectilinear coordinates (internal helper). |
| 1121 |
|
| 1122 |
Returns |
| 1123 |
------- |
| 1124 |
list[NumpyArray[float]] |
| 1125 |
Rectilinear coordinates over the three dimensions. |
| 1126 |
|
| 1127 |
""" |
| 1128 |
dims = self.dimensions |
| 1129 |
spacing = self.spacing |
| 1130 |
origin = self.origin |
| 1131 |
offset = self.offset |
| 1132 |
direction = self.direction_matrix |
| 1133 |
|
| 1134 |
# Off-axis rotation is not supported by RectilinearGrid |
| 1135 |
if np.allclose(np.abs(direction), np.eye(3)): |
| 1136 |
sign = np.diagonal(direction) |
| 1137 |
else: |
| 1138 |
msg = ( |
| 1139 |
'Rectilinear grid does not support off-axis rotations.\n' |
| 1140 |
'Consider removing off-axis rotations from the `direction_matrix`, ' |
| 1141 |
'or casting to StructuredGrid instead.' |
| 1142 |
) |
| 1143 |
raise ValueError(msg) |
| 1144 |
|
| 1145 |
# Use linspace to avoid rounding error accumulation |
| 1146 |
ijk = [np.linspace(offset[i], offset[i] + dims[i] - 1, dims[i]) for i in range(3)] |
| 1147 |
return [ijk[axis] * spacing[axis] * sign[axis] + origin[axis] for axis in range(3)] |
| 1148 |
|
| 1149 |
@property |
| 1150 |
def extent( |
| 1151 |
self: Self, |
| 1152 |
) -> tuple[int, int, int, int, int, int]: # numpydoc ignore=RT01 |
| 1153 |
"""Return or set the extent of the ImageData. |
| 1154 |
|
| 1155 |
The extent is simply the first and last indices for each of the three axes. |
| 1156 |
It encodes information about the image's :attr:`offset` and :attr:`dimensions`. |
| 1157 |
|
| 1158 |
Examples |
| 1159 |
-------- |
| 1160 |
Create a ``ImageData`` and show its extent. |
| 1161 |
|
| 1162 |
>>> import pyvista as pv |
| 1163 |
>>> grid = pv.ImageData(dimensions=(10, 10, 10)) |
| 1164 |
>>> grid.extent |
| 1165 |
(0, 9, 0, 9, 0, 9) |
| 1166 |
|
| 1167 |
>>> grid.extent = (2, 5, 2, 5, 2, 5) |
| 1168 |
>>> grid.extent |
| 1169 |
(2, 5, 2, 5, 2, 5) |
| 1170 |
|
| 1171 |
Note how this also modifies the grid's :attr:`offset`, :attr:`dimensions`, |
| 1172 |
and :attr:`bounds`. Since we use default spacing of 1 here, the bounds |
| 1173 |
match the extent exactly. |
| 1174 |
|
| 1175 |
>>> grid.offset |
| 1176 |
(2, 2, 2) |
| 1177 |
|
| 1178 |
>>> grid.dimensions |
| 1179 |
(4, 4, 4) |
| 1180 |
|
| 1181 |
>>> grid.bounds |
| 1182 |
BoundsTuple(x_min = 2.0, |
| 1183 |
x_max = 5.0, |
| 1184 |
y_min = 2.0, |
| 1185 |
y_max = 5.0, |
| 1186 |
z_min = 2.0, |
| 1187 |
z_max = 5.0) |
| 1188 |
|
| 1189 |
""" |
| 1190 |
return self.GetExtent() |
| 1191 |
|
| 1192 |
@extent.setter |
| 1193 |
def extent(self: Self, new_extent: VectorLike[int]) -> None: |
| 1194 |
new_extent_ = _validation.validate_arrayN( |
| 1195 |
new_extent, |
| 1196 |
must_be_integer=True, |
| 1197 |
must_have_length=6, |
| 1198 |
to_list=True, |
| 1199 |
dtype_out=int, |
| 1200 |
) |
| 1201 |
self.SetExtent(new_extent_) |
| 1202 |
|
| 1203 |
@property |
| 1204 |
def offset(self: Self) -> tuple[int, int, int]: # numpydoc ignore=RT01 |
| 1205 |
"""Return or set the index offset of the ImageData. |
| 1206 |
|
| 1207 |
The offset is simply the first indices for each of the three axes |
| 1208 |
and defines the minimum :attr:`extent` of the image. Offset values |
| 1209 |
can be positive or negative. In physical space, the offset is relative |
| 1210 |
to the image's :attr:`origin`. |
| 1211 |
|
| 1212 |
.. versionadded:: 0.45 |
| 1213 |
|
| 1214 |
Examples |
| 1215 |
-------- |
| 1216 |
Create a ``ImageData`` and show that the offset is zeros by default. |
| 1217 |
|
| 1218 |
>>> import pyvista as pv |
| 1219 |
>>> grid = pv.ImageData(dimensions=(10, 10, 10)) |
| 1220 |
>>> grid.offset |
| 1221 |
(0, 0, 0) |
| 1222 |
|
| 1223 |
The offset defines the minimum extent. |
| 1224 |
|
| 1225 |
>>> grid.extent |
| 1226 |
(0, 9, 0, 9, 0, 9) |
| 1227 |
|
| 1228 |
Set the offset to a new value for all axes. |
| 1229 |
|
| 1230 |
>>> grid.offset = 2 |
| 1231 |
>>> grid.offset |
| 1232 |
(2, 2, 2) |
| 1233 |
|
| 1234 |
Show the extent again. Note how all values have increased by the offset value. |
| 1235 |
|
| 1236 |
>>> grid.extent |
| 1237 |
(2, 11, 2, 11, 2, 11) |
| 1238 |
|
| 1239 |
Set the offset for each axis separately and show the extent again. |
| 1240 |
|
| 1241 |
>>> grid.offset = (-1, -2, -3) |
| 1242 |
>>> grid.extent |
| 1243 |
(-1, 8, -2, 7, -3, 6) |
| 1244 |
|
| 1245 |
""" |
| 1246 |
return self.extent[::2] |
| 1247 |
|
| 1248 |
@offset.setter |
| 1249 |
def offset(self: Self, offset: int | VectorLike[int]) -> None: |
| 1250 |
offset_ = _validation.validate_array3( |
| 1251 |
offset, broadcast=True, must_be_integer=True, dtype_out=int |
| 1252 |
) |
| 1253 |
dims = self.dimensions |
| 1254 |
self.extent = ( |
| 1255 |
offset_[0], |
| 1256 |
offset_[0] + dims[0] - 1, |
| 1257 |
offset_[1], |
| 1258 |
offset_[1] + dims[1] - 1, |
| 1259 |
offset_[2], |
| 1260 |
offset_[2] + dims[2] - 1, |
| 1261 |
) |
| 1262 |
|
| 1263 |
@wraps(RectilinearGridFilters.to_tetrahedra) |
| 1264 |
def to_tetrahedra( |
| 1265 |
self: Self, *args, **kwargs |
| 1266 |
) -> UnstructuredGrid: # numpydoc ignore=PR01,RT01 |
| 1267 |
"""Cast to a rectangular grid and then convert to tetrahedra.""" |
| 1268 |
return self.cast_to_rectilinear_grid().to_tetrahedra(*args, **kwargs) |
| 1269 |
|
| 1270 |
@property |
| 1271 |
def direction_matrix(self: Self) -> NumpyArray[float]: |
| 1272 |
"""Set or get the direction matrix. |
| 1273 |
|
| 1274 |
The direction matrix is a 3x3 matrix which controls the orientation of the |
| 1275 |
image data. |
| 1276 |
|
| 1277 |
.. versionadded:: 0.45 |
| 1278 |
|
| 1279 |
Returns |
| 1280 |
------- |
| 1281 |
np.ndarray |
| 1282 |
Direction matrix as a 3x3 NumPy array. |
| 1283 |
|
| 1284 |
""" |
| 1285 |
return array_from_vtkmatrix(self.GetDirectionMatrix()) |
| 1286 |
|
| 1287 |
@direction_matrix.setter |
| 1288 |
def direction_matrix(self: Self, matrix: RotationLike) -> None: |
| 1289 |
self.SetDirectionMatrix(vtkmatrix_from_array(_validation.validate_transform3x3(matrix))) |
| 1290 |
|
| 1291 |
@property |
| 1292 |
def index_to_physical_matrix(self: Self) -> NumpyArray[float]: |
| 1293 |
"""Return or set 4x4 matrix to transform index space (ijk) to physical space (xyz). |
| 1294 |
|
| 1295 |
.. note:: |
| 1296 |
Setting this property modifies the object's :class:`~pyvista.ImageData.origin`, |
| 1297 |
:class:`~pyvista.ImageData.spacing`, and :class:`~pyvista.ImageData.direction_matrix` |
| 1298 |
properties. |
| 1299 |
|
| 1300 |
.. versionadded:: 0.45 |
| 1301 |
|
| 1302 |
Returns |
| 1303 |
------- |
| 1304 |
np.ndarray |
| 1305 |
4x4 transformation matrix. |
| 1306 |
|
| 1307 |
""" |
| 1308 |
return array_from_vtkmatrix(self.GetIndexToPhysicalMatrix()) |
| 1309 |
|
| 1310 |
@index_to_physical_matrix.setter |
| 1311 |
def index_to_physical_matrix( |
| 1312 |
self: Self, matrix: TransformLike |
| 1313 |
) -> None: # numpydoc ignore=GL08 |
| 1314 |
T, R, N, S, K = pv.Transform(matrix).decompose() |
| 1315 |
if not np.allclose(K, np.eye(3)): |
| 1316 |
msg = ( |
| 1317 |
'The transformation has a shear component which is not supported by ImageData.\n' |
| 1318 |
'Cast to StructuredGrid first to fully support shear transformations, or use\n' |
| 1319 |
'`Transform.decompose()` to remove this component.' |
| 1320 |
) |
| 1321 |
raise ValueError(msg) |
| 1322 |
|
| 1323 |
self.origin = T |
| 1324 |
self.direction_matrix = R * N |
| 1325 |
self.spacing = S |
| 1326 |
|
| 1327 |
@property |
| 1328 |
def physical_to_index_matrix(self: Self) -> NumpyArray[float]: |
| 1329 |
"""Return or set 4x4 matrix to transform from physical space (xyz) to index space (ijk). |
| 1330 |
|
| 1331 |
.. note:: |
| 1332 |
Setting this property modifies the object's :class:`~pyvista.ImageData.origin`, |
| 1333 |
:class:`~pyvista.ImageData.spacing`, and :class:`~pyvista.ImageData.direction_matrix` |
| 1334 |
properties. |
| 1335 |
|
| 1336 |
.. versionadded:: 0.45 |
| 1337 |
|
| 1338 |
Returns |
| 1339 |
------- |
| 1340 |
np.ndarray |
| 1341 |
4x4 transformation matrix. |
| 1342 |
|
| 1343 |
""" |
| 1344 |
return array_from_vtkmatrix(self.GetPhysicalToIndexMatrix()) |
| 1345 |
|
| 1346 |
@physical_to_index_matrix.setter |
| 1347 |
def physical_to_index_matrix( |
| 1348 |
self: Self, matrix: TransformLike |
| 1349 |
) -> None: # numpydoc ignore=GL08 |
| 1350 |
self.index_to_physical_matrix = pv.Transform(matrix).inverse_matrix |