| 1 |
"""Attributes common to PolyData and Grid Objects.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from abc import abstractmethod |
| 6 |
from collections import UserDict |
| 7 |
from collections import defaultdict |
| 8 |
import importlib.util |
| 9 |
from pathlib import Path |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
import numpy as np |
| 13 |
|
| 14 |
import pyvista as pv |
| 15 |
from pyvista import _vtk |
| 16 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 17 |
from pyvista.core._vtk_utilities import DisableVtkSnakeCase |
| 18 |
from pyvista.core._vtk_utilities import is_vtk_attribute |
| 19 |
from pyvista.core._vtk_utilities import vtkPyVistaOverride |
| 20 |
from pyvista.typing.mypy_plugin import promote_type |
| 21 |
|
| 22 |
from .datasetattributes import DataSetAttributes |
| 23 |
from .pyvista_ndarray import pyvista_ndarray |
| 24 |
from .utilities.arrays import FieldAssociation |
| 25 |
from .utilities.arrays import _JSONValueType |
| 26 |
from .utilities.arrays import _SerializedDictArray |
| 27 |
from .utilities.fileio import PICKLE_EXT |
| 28 |
from .utilities.fileio import _CompressionOptions |
| 29 |
from .utilities.fileio import get_ext |
| 30 |
from .utilities.fileio import read |
| 31 |
from .utilities.fileio import save_pickle |
| 32 |
from .utilities.helpers import wrap |
| 33 |
from .utilities.misc import _DataObjectMeta |
| 34 |
from .utilities.misc import _NoNewAttrMixin |
| 35 |
from .utilities.misc import abstract_class |
| 36 |
from .utilities.writer_registry import _get_ext_handler as _get_writer_ext_handler |
| 37 |
from .utilities.writer_registry import _list_custom_exts as _list_custom_writer_exts |
| 38 |
|
| 39 |
if TYPE_CHECKING: |
| 40 |
from types import FunctionType |
| 41 |
from typing import Any |
| 42 |
from typing import ClassVar |
| 43 |
|
| 44 |
from typing_extensions import Self |
| 45 |
|
| 46 |
from pyvista import MultiBlock |
| 47 |
|
| 48 |
from ._typing_core import NumpyArray |
| 49 |
from .utilities.writer import BaseWriter |
| 50 |
|
| 51 |
# vector array names |
| 52 |
DEFAULT_VECTOR_KEY = '_vectors' |
| 53 |
USER_DICT_KEY = '_PYVISTA_USER_DICT' |
| 54 |
|
| 55 |
|
| 56 |
def _raise_unexpected_writer_kwargs( |
| 57 |
writer_kwargs: dict[str, Any], |
| 58 |
file_ext: str, |
| 59 |
*, |
| 60 |
target: str, |
| 61 |
) -> None: |
| 62 |
"""Raise :class:`TypeError` for extras that would be silently dropped.""" |
| 63 |
names = sorted(writer_kwargs) |
| 64 |
msg = ( |
| 65 |
f'save() got unexpected keyword arguments {names} for ' |
| 66 |
f'{target} for extension {file_ext!r}. Extra keyword arguments ' |
| 67 |
f'are only forwarded to custom writers registered via ' |
| 68 |
f'pyvista.register_writer.' |
| 69 |
) |
| 70 |
raise TypeError(msg) |
| 71 |
|
| 72 |
|
| 73 |
@promote_type(_vtk.vtkDataObject) |
| 74 |
@abstract_class |
| 75 |
class DataObject( |
| 76 |
_NoNewAttrMixin, |
| 77 |
DisableVtkSnakeCase, |
| 78 |
vtkPyVistaOverride, |
| 79 |
metaclass=_DataObjectMeta, |
| 80 |
): |
| 81 |
"""Methods common to all wrapped data objects. |
| 82 |
|
| 83 |
Parameters |
| 84 |
---------- |
| 85 |
*args : |
| 86 |
Any extra args are passed as option to all wrapped data objects. |
| 87 |
|
| 88 |
**kwargs : |
| 89 |
Any extra keyword args are passed as option to all wrapped data objects. |
| 90 |
|
| 91 |
""" |
| 92 |
|
| 93 |
_WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {} |
| 94 |
|
| 95 |
def __init__(self: Self, *args, **kwargs) -> None: |
| 96 |
"""Initialize the data object.""" |
| 97 |
try: |
| 98 |
super().__init__(*args, **kwargs) |
| 99 |
except TypeError: |
| 100 |
# super() maps to object |
| 101 |
super().__init__() |
| 102 |
# Remember which arrays come from numpy.bool arrays, because there is no direct |
| 103 |
# conversion from bool to vtkBitArray, such arrays are stored as vtkCharArray. |
| 104 |
self._association_bitarray_names: defaultdict[Any, Any] = defaultdict(set) |
| 105 |
|
| 106 |
# view these arrays as complex128 as VTK doesn't support complex types |
| 107 |
self._association_complex_names: defaultdict[Any, Any] = defaultdict(set) |
| 108 |
|
| 109 |
def __getattr__(self: Self, item: str) -> Any: |
| 110 |
"""Get attribute from base class if not found. |
| 111 |
|
| 112 |
Before falling through to the VTK base class, check whether |
| 113 |
``item`` matches a pending ``pyvista.accessors`` entry point. |
| 114 |
A match triggers a one-shot plugin import, after which normal |
| 115 |
attribute resolution finds the newly-attached accessor |
| 116 |
descriptor. |
| 117 |
""" |
| 118 |
# Lazy import to avoid a circular dependency at module load time. |
| 119 |
from pyvista.core.utilities.accessor_registry import _resolve_pending_accessor |
| 120 |
|
| 121 |
if _resolve_pending_accessor(item): |
| 122 |
return object.__getattribute__(self, item) |
| 123 |
return super().__getattribute__(item) |
| 124 |
|
| 125 |
def __dir__(self: Self) -> list[str]: |
| 126 |
"""Include pending accessor names so tab completion surfaces them. |
| 127 |
|
| 128 |
Plugin-contributed accessors registered via the ``pyvista.accessors`` |
| 129 |
entry-point group are imported lazily on first attribute access. |
| 130 |
Listing their names alongside the normal attribute set lets IPython |
| 131 |
/ Jupyter / REPL tab completion surface them without paying the |
| 132 |
plugin import cost ahead of time. |
| 133 |
""" |
| 134 |
# Lazy import to avoid a circular dependency at module load time. |
| 135 |
from pyvista.core.utilities.accessor_registry import _pending_accessor_names |
| 136 |
|
| 137 |
return sorted({*super().__dir__(), *_pending_accessor_names()}) |
| 138 |
|
| 139 |
def shallow_copy(self: Self, to_copy: Self | _vtk.vtkDataObject) -> None: |
| 140 |
"""Shallow copy the given mesh to this mesh. |
| 141 |
|
| 142 |
Parameters |
| 143 |
---------- |
| 144 |
to_copy : DataObject | :vtk:`vtkDataObject` |
| 145 |
Data object to perform a shallow copy from. |
| 146 |
|
| 147 |
""" |
| 148 |
self.ShallowCopy(to_copy) |
| 149 |
|
| 150 |
def deep_copy(self: Self, to_copy: Self | _vtk.vtkDataObject) -> None: |
| 151 |
"""Overwrite this data object with another data object as a deep copy. |
| 152 |
|
| 153 |
Parameters |
| 154 |
---------- |
| 155 |
to_copy : DataObject | :vtk:`vtkDataObject` |
| 156 |
Data object to perform a deep copy from. |
| 157 |
|
| 158 |
""" |
| 159 |
self.DeepCopy(to_copy) |
| 160 |
|
| 161 |
def _from_file(self: Self, filename: str | Path, **kwargs) -> None: |
| 162 |
"""Read data objects from file.""" |
| 163 |
data = read(filename, **kwargs) |
| 164 |
if not isinstance(self, type(data)): |
| 165 |
msg = ( |
| 166 |
f'Reading file returned data of `{type(data).__name__}`, ' |
| 167 |
f'but `{type(self).__name__}` was expected.' |
| 168 |
) |
| 169 |
raise TypeError(msg) |
| 170 |
self.shallow_copy(data) |
| 171 |
self._post_file_load_processing() |
| 172 |
|
| 173 |
def _post_file_load_processing(self: Self) -> None: |
| 174 |
"""Execute after loading a dataset from file, to be optionally overridden by subclasses.""" |
| 175 |
|
| 176 |
@_deprecate_positional_args(allowed=['filename']) |
| 177 |
def save( # noqa: PLR0917 |
| 178 |
self: Self, |
| 179 |
filename: Path | str, |
| 180 |
binary: bool = True, # noqa: FBT001, FBT002 |
| 181 |
texture: NumpyArray[np.uint8] | str | None = None, |
| 182 |
compression: _CompressionOptions = 'zlib', |
| 183 |
**writer_kwargs: Any, |
| 184 |
) -> None: |
| 185 |
"""Save this vtk object to file. |
| 186 |
|
| 187 |
.. include:: /api/utilities/mesh_io.rst |
| 188 |
|
| 189 |
.. versionadded:: 0.45 |
| 190 |
|
| 191 |
Support saving pickled meshes |
| 192 |
|
| 193 |
See Also |
| 194 |
-------- |
| 195 |
pyvista.read |
| 196 |
|
| 197 |
Parameters |
| 198 |
---------- |
| 199 |
filename : str, pathlib.Path |
| 200 |
Filename of output file. Writer type is inferred from |
| 201 |
the extension of the filename. |
| 202 |
|
| 203 |
binary : bool, default: True |
| 204 |
If ``True``, write as binary. Otherwise, write as ASCII. |
| 205 |
|
| 206 |
texture : str, np.ndarray, optional |
| 207 |
Write a single texture array to file when using a PLY |
| 208 |
file. Texture array must be a 3 or 4 component array with |
| 209 |
the datatype ``np.uint8``. Array may be a cell array or a |
| 210 |
point array, and may also be a string if the array already |
| 211 |
exists in the PolyData. |
| 212 |
|
| 213 |
If a string is provided, the texture array will be saved |
| 214 |
to disk as that name. If an array is provided, the |
| 215 |
texture array will be saved as ``'RGBA'`` |
| 216 |
|
| 217 |
.. note:: |
| 218 |
This feature is only available when saving PLY files. |
| 219 |
|
| 220 |
compression : str or None, default: 'zlib' |
| 221 |
The compression type to use when ``binary`` is ``True`` |
| 222 |
and VTK writer is of type :vtk:`vtkXMLWriter`. This |
| 223 |
argument has no effect otherwise. Acceptable values are |
| 224 |
``'zlib'``, ``'lz4'``, ``'lzma'``, and ``None``. ``None`` |
| 225 |
indicates no compression. |
| 226 |
|
| 227 |
.. versionadded:: 0.47 |
| 228 |
|
| 229 |
**writer_kwargs : dict, optional |
| 230 |
Additional keyword arguments forwarded verbatim to a custom |
| 231 |
writer registered via :func:`pyvista.register_writer`. Use |
| 232 |
these to expose format-specific options such as compression |
| 233 |
level or thread count. When the target extension dispatches |
| 234 |
to a built-in VTK writer or to the pickle path, passing any |
| 235 |
extra keyword arguments raises :class:`TypeError` — PyVista |
| 236 |
never silently drops writer options. |
| 237 |
|
| 238 |
.. versionadded:: 0.48 |
| 239 |
|
| 240 |
Raises |
| 241 |
------ |
| 242 |
TypeError |
| 243 |
If ``**writer_kwargs`` are provided but the target extension |
| 244 |
does not dispatch to a registered custom writer. |
| 245 |
ValueError |
| 246 |
If ``file_ext`` is not a supported extension. |
| 247 |
|
| 248 |
Notes |
| 249 |
----- |
| 250 |
Binary files write much faster than ASCII and have a smaller |
| 251 |
file size. |
| 252 |
|
| 253 |
""" |
| 254 |
if self._WRITERS is None: |
| 255 |
msg = ( # type: ignore[unreachable] |
| 256 |
f'{self.__class__.__name__} writers are not specified,' |
| 257 |
' this should be a dict of (file extension: vtkWriter type)' |
| 258 |
) |
| 259 |
raise NotImplementedError(msg) |
| 260 |
|
| 261 |
file_path = Path(filename) |
| 262 |
file_path = file_path.expanduser() |
| 263 |
file_path = file_path.resolve() |
| 264 |
file_ext = get_ext(file_path) |
| 265 |
|
| 266 |
# Store complex and bitarray types as field data |
| 267 |
self._store_metadata() |
| 268 |
|
| 269 |
# Dispatch order mirrors :func:`pyvista.read`: custom writers |
| 270 |
# registered via :func:`pyvista.register_writer` win over |
| 271 |
# built-in writers, so ``override=True`` actually replaces a |
| 272 |
# built-in writer at save time. |
| 273 |
writer_exts = self._WRITERS.keys() |
| 274 |
if (custom_writer := _get_writer_ext_handler(file_ext)) is not None: |
| 275 |
if not file_path.parent.exists(): |
| 276 |
msg = f'Parent directory does not exist: {file_path.parent}' |
| 277 |
raise FileNotFoundError(msg) |
| 278 |
|
| 279 |
custom_writer(self, str(file_path), **writer_kwargs) |
| 280 |
|
| 281 |
if not file_path.exists(): |
| 282 |
msg = f'Custom writer failed to write file: {file_path}' |
| 283 |
raise OSError(msg) |
| 284 |
|
| 285 |
elif file_ext in writer_exts: |
| 286 |
if writer_kwargs: |
| 287 |
_raise_unexpected_writer_kwargs( |
| 288 |
writer_kwargs, |
| 289 |
file_ext, |
| 290 |
target='built-in VTK writer', |
| 291 |
) |
| 292 |
if file_ext == '.vtkhdf' and binary is False: |
| 293 |
msg = '.vtkhdf files can only be written in binary format.' |
| 294 |
raise ValueError(msg) |
| 295 |
|
| 296 |
# Save using the writer |
| 297 |
writer = self._WRITERS[file_ext](file_path, self) |
| 298 |
data_format = 'binary' if binary else 'ascii' |
| 299 |
writer._apply_kwargs_safely( |
| 300 |
texture=texture, data_format=data_format, compression=compression |
| 301 |
) |
| 302 |
|
| 303 |
if not file_path.parent.exists(): |
| 304 |
msg = f'Parent directory does not exist: {file_path.parent}' |
| 305 |
raise FileNotFoundError(msg) |
| 306 |
|
| 307 |
writer.write() |
| 308 |
|
| 309 |
if not file_path.exists(): |
| 310 |
msg = f'VTK writer failed to write file: {file_path}' |
| 311 |
raise OSError(msg) |
| 312 |
|
| 313 |
elif file_ext in PICKLE_EXT: |
| 314 |
if writer_kwargs: |
| 315 |
_raise_unexpected_writer_kwargs( |
| 316 |
writer_kwargs, |
| 317 |
file_ext, |
| 318 |
target='pickle format', |
| 319 |
) |
| 320 |
save_pickle(filename, self) |
| 321 |
else: |
| 322 |
msg = ( |
| 323 |
f'Invalid file extension {file_ext!r} for data type {type(self)}.\n' |
| 324 |
f'Must be one of: ' |
| 325 |
f'{list(writer_exts) + list(PICKLE_EXT) + _list_custom_writer_exts()}' |
| 326 |
) |
| 327 |
if file_ext == '.pv' and not importlib.util.find_spec( |
| 328 |
'pyvista-zstd' |
| 329 |
): # pragma: no cover |
| 330 |
msg += ( |
| 331 |
".\nThe '.pv' extension is supported by the `pyvista-zstd` package. " |
| 332 |
'It can be installed with `pyvista[io]`.' |
| 333 |
) |
| 334 |
raise ValueError(msg) |
| 335 |
|
| 336 |
def _store_metadata(self: Self) -> None: |
| 337 |
"""Store metadata as field data.""" |
| 338 |
fdata = self.field_data |
| 339 |
for assoc_name in ('bitarray', 'complex'): |
| 340 |
for assoc_type in ('POINT', 'CELL'): |
| 341 |
assoc_data = getattr(self, f'_association_{assoc_name}_names') |
| 342 |
array_names = assoc_data.get(assoc_type) |
| 343 |
if array_names: |
| 344 |
key = f'_PYVISTA_{assoc_name}_{assoc_type}_'.upper() |
| 345 |
fdata[key] = list(array_names) |
| 346 |
|
| 347 |
def _restore_metadata(self: Self) -> None: |
| 348 |
"""Restore PyVista metadata from field data. |
| 349 |
|
| 350 |
Metadata is stored using ``_store_metadata`` and contains entries in |
| 351 |
the format of f'_PYVISTA_{assoc_name}_{assoc_type}_'. These entries are |
| 352 |
removed when calling this method. |
| 353 |
|
| 354 |
""" |
| 355 |
fdata = self.field_data |
| 356 |
for assoc_name in ('bitarray', 'complex'): |
| 357 |
for assoc_type in ('POINT', 'CELL'): |
| 358 |
key = f'_PYVISTA_{assoc_name}_{assoc_type}_'.upper() |
| 359 |
if key in fdata: |
| 360 |
assoc_data = getattr(self, f'_association_{assoc_name}_names') |
| 361 |
assoc_data[assoc_type] = set(fdata[key]) |
| 362 |
del fdata[key] |
| 363 |
|
| 364 |
@abstractmethod |
| 365 |
def get_data_range( |
| 366 |
self: Self, name: str | None, preference: FieldAssociation | str |
| 367 |
) -> tuple[float, float]: # pragma: no cover |
| 368 |
"""Get the non-NaN min and max of a named array.""" |
| 369 |
msg = f'{type(self)} mesh type does not have a `get_data_range` method.' |
| 370 |
raise NotImplementedError(msg) |
| 371 |
|
| 372 |
def _get_attrs(self: Self) -> list[tuple[str, Any, str]]: # pragma: no cover |
| 373 |
"""Return the representation methods (internal helper).""" |
| 374 |
msg = 'Called only by the inherited class' |
| 375 |
raise NotImplementedError(msg) |
| 376 |
|
| 377 |
@_deprecate_positional_args |
| 378 |
def head(self: Self, display: bool = True, html: bool | None = None) -> str: # noqa: FBT001, FBT002 |
| 379 |
"""Return the header stats of this dataset. |
| 380 |
|
| 381 |
If in IPython, this will be formatted to HTML. Otherwise |
| 382 |
returns a console friendly string. |
| 383 |
|
| 384 |
Parameters |
| 385 |
---------- |
| 386 |
display : bool, default: True |
| 387 |
Display this header in iPython. |
| 388 |
|
| 389 |
html : bool, optional |
| 390 |
Generate the output as HTML. |
| 391 |
|
| 392 |
Returns |
| 393 |
------- |
| 394 |
str |
| 395 |
Header statistics. |
| 396 |
|
| 397 |
""" |
| 398 |
# Generate the output |
| 399 |
if html: |
| 400 |
fmt = '' |
| 401 |
# HTML version |
| 402 |
fmt += '\n' |
| 403 |
fmt += "<table style='width: 100%;'>\n" |
| 404 |
fmt += f'<tr><th>{type(self).__name__}</th><th>Information</th></tr>\n' |
| 405 |
row = '<tr><td>{}</td><td>{}</td></tr>\n' |
| 406 |
# now make a call on the object to get its attributes as a list of len 2 tuples |
| 407 |
for attr in self._get_attrs(): |
| 408 |
try: |
| 409 |
fmt += row.format(attr[0], attr[2].format(*attr[1])) |
| 410 |
except TypeError: |
| 411 |
fmt += row.format(attr[0], attr[2].format(attr[1])) |
| 412 |
if hasattr(self, 'n_arrays'): |
| 413 |
fmt += row.format('N Arrays', self.n_arrays) |
| 414 |
fmt += '</table>\n' |
| 415 |
fmt += '\n' |
| 416 |
if display: |
| 417 |
from IPython.display import HTML |
| 418 |
from IPython.display import display as _display |
| 419 |
|
| 420 |
_display(HTML(fmt)) |
| 421 |
return '' |
| 422 |
return fmt |
| 423 |
# Otherwise return a string that is Python console friendly |
| 424 |
fmt = f'{type(self).__name__} ({hex(id(self))})\n' |
| 425 |
# now make a call on the object to get its attributes as a list of len 2 tuples |
| 426 |
# get longest row header |
| 427 |
max_len = max(len(attr[0]) for attr in self._get_attrs()) + 4 |
| 428 |
|
| 429 |
# now make a call on the object to get its attributes as a list of len |
| 430 |
# 2 tuples |
| 431 |
row = f' {{:{max_len}s}}' + '{}\n' |
| 432 |
for attr in self._get_attrs(): |
| 433 |
try: |
| 434 |
fmt += row.format(attr[0] + ':', attr[2].format(*attr[1])) |
| 435 |
except TypeError: |
| 436 |
fmt += row.format(attr[0] + ':', attr[2].format(attr[1])) |
| 437 |
if hasattr(self, 'n_arrays'): |
| 438 |
fmt += row.format('N Arrays:', self.n_arrays) |
| 439 |
return fmt.strip() |
| 440 |
|
| 441 |
def _repr_html_(self: Self) -> str: # pragma: no cover |
| 442 |
"""Return a pretty representation for Jupyter notebooks. |
| 443 |
|
| 444 |
This includes header details and information about all arrays. |
| 445 |
|
| 446 |
""" |
| 447 |
msg = 'Called only by the inherited class' |
| 448 |
raise NotImplementedError(msg) |
| 449 |
|
| 450 |
def copy_meta_from(self: Self, *args, **kwargs) -> None: # pragma: no cover |
| 451 |
"""Copy pyvista meta data onto this object from another object. |
| 452 |
|
| 453 |
Intended to be overridden by subclasses. |
| 454 |
|
| 455 |
Parameters |
| 456 |
---------- |
| 457 |
*args : tuple |
| 458 |
Positional arguments. |
| 459 |
|
| 460 |
**kwargs : dict, optional |
| 461 |
Keyword arguments. |
| 462 |
|
| 463 |
""" |
| 464 |
# called only by the inherited class |
| 465 |
|
| 466 |
@_deprecate_positional_args |
| 467 |
def copy(self: Self, deep: bool = True) -> Self: # noqa: FBT001, FBT002 |
| 468 |
"""Return a copy of the object. |
| 469 |
|
| 470 |
Parameters |
| 471 |
---------- |
| 472 |
deep : bool, default: True |
| 473 |
When ``True`` makes a full copy of the object. When |
| 474 |
``False``, performs a shallow copy where the points, cell, |
| 475 |
and data arrays are references to the original object. |
| 476 |
|
| 477 |
Returns |
| 478 |
------- |
| 479 |
pyvista.DataSet |
| 480 |
Deep or shallow copy of the input. Type is identical to |
| 481 |
the input. |
| 482 |
|
| 483 |
Examples |
| 484 |
-------- |
| 485 |
Create and make a deep copy of a PolyData object. |
| 486 |
|
| 487 |
>>> import pyvista as pv |
| 488 |
>>> mesh_a = pv.Sphere() |
| 489 |
>>> mesh_b = mesh_a.copy() |
| 490 |
>>> mesh_a == mesh_b |
| 491 |
True |
| 492 |
|
| 493 |
""" |
| 494 |
thistype = type(self) |
| 495 |
newobject = thistype() |
| 496 |
|
| 497 |
if deep: |
| 498 |
newobject.deep_copy(self) |
| 499 |
else: |
| 500 |
newobject.shallow_copy(self) |
| 501 |
newobject.copy_meta_from(self, deep=deep) |
| 502 |
return newobject |
| 503 |
|
| 504 |
def __eq__(self: Self, other: object) -> bool: |
| 505 |
"""Test equivalency between data objects.""" |
| 506 |
if not isinstance(self, type(other)): |
| 507 |
return False |
| 508 |
|
| 509 |
if self is other: |
| 510 |
return True |
| 511 |
|
| 512 |
# these attrs use numpy.array_equal |
| 513 |
if isinstance(self, pv.ImageData): |
| 514 |
equal_attrs = ['extent', 'index_to_physical_matrix'] |
| 515 |
else: |
| 516 |
equal_attrs = ['points', 'cells'] |
| 517 |
if isinstance(self, pv.PolyData): |
| 518 |
equal_attrs.extend(['verts', 'lines', 'faces', 'strips']) |
| 519 |
elif isinstance(self, pv.UnstructuredGrid): |
| 520 |
equal_attrs.append('celltypes') |
| 521 |
equal_attrs.append('polyhedron_faces') |
| 522 |
equal_attrs.append('polyhedron_face_locations') |
| 523 |
|
| 524 |
for attr in equal_attrs: |
| 525 |
# Only check equality for attributes defined by PyVista |
| 526 |
# (i.e. ignore any default vtk snake_case attributes) |
| 527 |
if hasattr(self, attr) and not is_vtk_attribute(self, attr): |
| 528 |
if not np.array_equal(getattr(self, attr), getattr(other, attr), equal_nan=True): |
| 529 |
return False |
| 530 |
|
| 531 |
# these attrs can be directly compared |
| 532 |
attrs = ['field_data', 'point_data', 'cell_data'] |
| 533 |
for attr in attrs: |
| 534 |
if hasattr(self, attr): |
| 535 |
if getattr(self, attr) != getattr(other, attr): |
| 536 |
return False |
| 537 |
|
| 538 |
return True |
| 539 |
|
| 540 |
__hash__ = None # type: ignore[assignment] # https://github.com/pyvista/pyvista/pull/7671 |
| 541 |
|
| 542 |
@_deprecate_positional_args(allowed=['array', 'name']) |
| 543 |
def add_field_data(self: Self, array: NumpyArray[float], name: str, deep: bool = True) -> None: # noqa: FBT001, FBT002 |
| 544 |
"""Add field data. |
| 545 |
|
| 546 |
Use field data when size of the data you wish to associate |
| 547 |
with the dataset does not match the number of points or cells |
| 548 |
of the dataset. |
| 549 |
|
| 550 |
Parameters |
| 551 |
---------- |
| 552 |
array : sequence |
| 553 |
Array of data to add to the dataset as a field array. |
| 554 |
|
| 555 |
name : str |
| 556 |
Name to assign the field array. |
| 557 |
|
| 558 |
deep : bool, default: True |
| 559 |
Perform a deep copy of the data when adding it to the |
| 560 |
dataset. |
| 561 |
|
| 562 |
Examples |
| 563 |
-------- |
| 564 |
Add field data to a PolyData dataset. |
| 565 |
|
| 566 |
>>> import pyvista as pv |
| 567 |
>>> import numpy as np |
| 568 |
>>> mesh = pv.Sphere() |
| 569 |
>>> mesh.add_field_data(np.arange(10), 'my-field-data') |
| 570 |
>>> mesh['my-field-data'] |
| 571 |
pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) |
| 572 |
|
| 573 |
Add field data to a ImageData dataset. |
| 574 |
|
| 575 |
>>> mesh = pv.ImageData(dimensions=(2, 2, 1)) |
| 576 |
>>> mesh.add_field_data(['I could', 'write', 'notes', 'here'], 'my-field-data') |
| 577 |
>>> mesh['my-field-data'] |
| 578 |
pyvista_ndarray(['I could', 'write', 'notes', 'here'], dtype='<U7') |
| 579 |
|
| 580 |
Add field data to a MultiBlock dataset. |
| 581 |
|
| 582 |
>>> blocks = pv.MultiBlock() |
| 583 |
>>> blocks.append(pv.Sphere()) |
| 584 |
>>> blocks['cube'] = pv.Cube(center=(0, 0, -1)) |
| 585 |
>>> blocks.add_field_data([1, 2, 3], 'my-field-data') |
| 586 |
>>> blocks.field_data['my-field-data'] |
| 587 |
pyvista_ndarray([1, 2, 3]) |
| 588 |
|
| 589 |
""" |
| 590 |
if not hasattr(self, 'field_data'): |
| 591 |
msg = f'`{type(self)}` does not support field data' |
| 592 |
raise NotImplementedError(msg) |
| 593 |
|
| 594 |
self.field_data.set_array(array, name, deep_copy=deep) |
| 595 |
|
| 596 |
@property |
| 597 |
def field_data(self: Self) -> DataSetAttributes: |
| 598 |
"""Return FieldData as DataSetAttributes. |
| 599 |
|
| 600 |
Use field data when size of the data you wish to associate |
| 601 |
with the dataset does not match the number of points or cells |
| 602 |
of the dataset. |
| 603 |
|
| 604 |
Returns |
| 605 |
------- |
| 606 |
DataSetAttributes |
| 607 |
FieldData as DataSetAttributes. |
| 608 |
|
| 609 |
Examples |
| 610 |
-------- |
| 611 |
Add field data to a PolyData dataset and then return it. |
| 612 |
|
| 613 |
>>> import pyvista as pv |
| 614 |
>>> import numpy as np |
| 615 |
>>> mesh = pv.Sphere() |
| 616 |
>>> mesh.field_data['my-field-data'] = np.arange(10) |
| 617 |
>>> mesh.field_data['my-field-data'] |
| 618 |
pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) |
| 619 |
|
| 620 |
""" |
| 621 |
return DataSetAttributes( |
| 622 |
self.GetFieldData(), |
| 623 |
dataset=self, # type: ignore[arg-type] |
| 624 |
association=FieldAssociation.NONE, |
| 625 |
) |
| 626 |
|
| 627 |
def clear_field_data(self: Self) -> None: |
| 628 |
"""Remove all field data. |
| 629 |
|
| 630 |
Examples |
| 631 |
-------- |
| 632 |
Add field data to a PolyData dataset and then remove it. |
| 633 |
|
| 634 |
>>> import pyvista as pv |
| 635 |
>>> mesh = pv.Sphere() |
| 636 |
>>> mesh.field_data['my-field-data'] = range(10) |
| 637 |
>>> len(mesh.field_data) |
| 638 |
1 |
| 639 |
>>> mesh.clear_field_data() |
| 640 |
>>> len(mesh.field_data) |
| 641 |
0 |
| 642 |
|
| 643 |
""" |
| 644 |
if not hasattr(self, 'field_data'): |
| 645 |
msg = f'`{type(self)}` does not support field data' |
| 646 |
raise NotImplementedError(msg) |
| 647 |
|
| 648 |
self.field_data.clear() |
| 649 |
|
| 650 |
@property |
| 651 |
def user_dict(self: Self) -> _SerializedDictArray: |
| 652 |
"""Set or return a user-specified data dictionary. |
| 653 |
|
| 654 |
The dictionary is stored as a JSON-serialized string as part of the mesh's |
| 655 |
field data. Unlike regular field data, which requires values to be stored |
| 656 |
as an array, the user dict provides a mapping for scalar values. |
| 657 |
|
| 658 |
Since the user dict is stored as field data, it is automatically saved |
| 659 |
with the mesh when it is saved in a compatible file format (e.g. ``'.vtk'``). |
| 660 |
Any saved metadata is automatically de-serialized by PyVista whenever |
| 661 |
the user dict is accessed again. Since the data is stored as JSON, it |
| 662 |
may also be easily retrieved or read by other programs. |
| 663 |
|
| 664 |
Any JSON-serializable values are permitted by the user dict, i.e. values |
| 665 |
can have type ``dict``, ``list``, ``tuple``, ``str``, ``int``, ``float``, |
| 666 |
``bool``, or ``None``. Storing NumPy arrays is not directly supported, but |
| 667 |
these may be cast beforehand to a supported type, e.g. by calling ``tolist()`` |
| 668 |
on the array. |
| 669 |
|
| 670 |
To completely remove the user dict string from the dataset's field data, |
| 671 |
set its value to ``None``. |
| 672 |
|
| 673 |
.. note:: |
| 674 |
|
| 675 |
The user dict is a convenience property intended for metadata storage. |
| 676 |
Values are JSON-serialized on every mutation, so it is not a substitute |
| 677 |
for a regular field data array when storing bulk array data with many |
| 678 |
entries (use a regular field data array for that instead). |
| 679 |
|
| 680 |
.. warning:: |
| 681 |
|
| 682 |
Field data is typically passed-through by dataset filters, and therefore |
| 683 |
the user dict's items can generally be expected to persist and remain |
| 684 |
unchanged in the output of filtering methods. However, this behavior is |
| 685 |
not guaranteed, as it's possible that some filters may modify or clear |
| 686 |
field data. Use with caution. |
| 687 |
|
| 688 |
.. versionadded:: 0.44 |
| 689 |
|
| 690 |
Returns |
| 691 |
------- |
| 692 |
UserDict |
| 693 |
JSON-serialized dict-like object which is subclassed from |
| 694 |
:py:class:`collections.UserDict`. |
| 695 |
|
| 696 |
Examples |
| 697 |
-------- |
| 698 |
Load a mesh. |
| 699 |
|
| 700 |
>>> import pyvista as pv |
| 701 |
>>> from pyvista import examples |
| 702 |
>>> mesh = examples.load_ant() |
| 703 |
|
| 704 |
Add data to the user dict. The contents are serialized as JSON. |
| 705 |
|
| 706 |
>>> mesh.user_dict['name'] = 'ant' |
| 707 |
>>> mesh.user_dict |
| 708 |
{"name": "ant"} |
| 709 |
|
| 710 |
Alternatively, set the user dict from an existing dict. |
| 711 |
|
| 712 |
>>> mesh.user_dict = dict(name='ant') |
| 713 |
|
| 714 |
The user dict can be updated like a regular dict. |
| 715 |
|
| 716 |
>>> mesh.user_dict.update( |
| 717 |
... { |
| 718 |
... 'num_legs': 6, |
| 719 |
... 'body_parts': ['head', 'thorax', 'abdomen'], |
| 720 |
... } |
| 721 |
... ) |
| 722 |
>>> mesh.user_dict |
| 723 |
{"name": "ant", "num_legs": 6, "body_parts": ["head", "thorax", "abdomen"]} |
| 724 |
|
| 725 |
Data in the user dict is stored as field data. |
| 726 |
|
| 727 |
>>> mesh.field_data |
| 728 |
pyvista DataSetAttributes |
| 729 |
Association : NONE |
| 730 |
Contains arrays : |
| 731 |
_PYVISTA_USER_DICT str "{"name": "ant",..." |
| 732 |
|
| 733 |
Since it's field data, the user dict can be saved to file along with the |
| 734 |
mesh and retrieved later. |
| 735 |
|
| 736 |
>>> mesh.save('ant.vtk') |
| 737 |
>>> mesh_from_file = pv.read('ant.vtk') |
| 738 |
>>> mesh_from_file.user_dict |
| 739 |
{"name": "ant", "num_legs": 6, "body_parts": ["head", "thorax", "abdomen"]} |
| 740 |
|
| 741 |
""" |
| 742 |
self._config_user_dict() |
| 743 |
return self._user_dict |
| 744 |
|
| 745 |
@user_dict.setter |
| 746 |
def user_dict( |
| 747 |
self: Self, |
| 748 |
dict_: dict[str, _JSONValueType] | UserDict[str, _JSONValueType] | None, |
| 749 |
) -> None: |
| 750 |
# Setting None removes the field data array |
| 751 |
if dict_ is None: |
| 752 |
if hasattr(self, '_user_dict'): |
| 753 |
del self._user_dict |
| 754 |
if USER_DICT_KEY in self.field_data.keys(): |
| 755 |
del self.field_data[USER_DICT_KEY] |
| 756 |
return |
| 757 |
|
| 758 |
self._config_user_dict() |
| 759 |
if isinstance(dict_, dict): |
| 760 |
self._user_dict.data = dict_ |
| 761 |
elif isinstance(dict_, UserDict): |
| 762 |
self._user_dict.data = dict_.data |
| 763 |
else: |
| 764 |
msg = ( # type: ignore[unreachable] |
| 765 |
f'User dict can only be set with type {dict} or {UserDict}.\n' |
| 766 |
f'Got {type(dict_)} instead.' |
| 767 |
) |
| 768 |
raise TypeError(msg) |
| 769 |
|
| 770 |
def _config_user_dict(self: Self) -> None: |
| 771 |
"""Init serialized dict array and ensure it is added to field_data.""" |
| 772 |
field_data = self.field_data |
| 773 |
|
| 774 |
if not hasattr(self, '_user_dict'): |
| 775 |
# Init |
| 776 |
object.__setattr__(self, '_user_dict', _SerializedDictArray()) |
| 777 |
|
| 778 |
if USER_DICT_KEY in field_data.keys(): |
| 779 |
if isinstance(array := field_data[USER_DICT_KEY], pyvista_ndarray): |
| 780 |
# When loaded from file, field will be cast as pyvista ndarray |
| 781 |
# Convert to string and initialize new user dict object from it |
| 782 |
self._user_dict = _SerializedDictArray(''.join(array)) |
| 783 |
elif isinstance(array, str) and str(self._user_dict) != array: # type: ignore[unreachable] |
| 784 |
# Filters may update the field data block separately, e.g. |
| 785 |
# when copying field data, so we need to capture the new |
| 786 |
# string and re-init |
| 787 |
self._user_dict = _SerializedDictArray(array) |
| 788 |
else: |
| 789 |
# User dict is correctly configured, do nothing |
| 790 |
return |
| 791 |
|
| 792 |
# Set field data array directly instead of calling 'set_array' |
| 793 |
# This skips the call to '_prepare_array' which will otherwise |
| 794 |
# do all kinds of casting/conversions and mangle this array |
| 795 |
self._user_dict.SetName(USER_DICT_KEY) |
| 796 |
field_data.VTKObject.AddArray(self._user_dict) |
| 797 |
field_data.VTKObject.Modified() |
| 798 |
|
| 799 |
@property |
| 800 |
def memory_address(self: Self) -> str: |
| 801 |
"""Get address of the underlying VTK C++ object. |
| 802 |
|
| 803 |
Returns |
| 804 |
------- |
| 805 |
str |
| 806 |
Memory address formatted as ``'Addr=%p'``. |
| 807 |
|
| 808 |
Examples |
| 809 |
-------- |
| 810 |
>>> import pyvista as pv |
| 811 |
>>> mesh = pv.Sphere() |
| 812 |
>>> mesh.memory_address |
| 813 |
'Addr=...' |
| 814 |
|
| 815 |
""" |
| 816 |
return self.GetInformation().GetAddressAsString('') |
| 817 |
|
| 818 |
@property |
| 819 |
def actual_memory_size(self: Self) -> int: |
| 820 |
"""Return the actual size of the dataset object. |
| 821 |
|
| 822 |
Returns |
| 823 |
------- |
| 824 |
int |
| 825 |
The actual size of the dataset object in kibibytes (1024 |
| 826 |
bytes). |
| 827 |
|
| 828 |
Examples |
| 829 |
-------- |
| 830 |
>>> from pyvista import examples |
| 831 |
>>> mesh = examples.load_airplane() |
| 832 |
>>> mesh.actual_memory_size # doctest:+SKIP |
| 833 |
93 |
| 834 |
|
| 835 |
""" |
| 836 |
return self.GetActualMemorySize() |
| 837 |
|
| 838 |
def copy_structure(self: Self, dataset: Self) -> None: |
| 839 |
"""Copy the structure (geometry and topology) of the input dataset object. |
| 840 |
|
| 841 |
Parameters |
| 842 |
---------- |
| 843 |
dataset : :vtk:`vtkDataSet` |
| 844 |
Dataset to copy the geometry and topology from. |
| 845 |
|
| 846 |
Examples |
| 847 |
-------- |
| 848 |
>>> import pyvista as pv |
| 849 |
>>> source = pv.ImageData(dimensions=(10, 10, 5)) |
| 850 |
>>> target = pv.ImageData() |
| 851 |
>>> target.copy_structure(source) |
| 852 |
>>> target.plot(show_edges=True) |
| 853 |
|
| 854 |
""" |
| 855 |
self.CopyStructure(dataset) if dataset is not self else None |
| 856 |
|
| 857 |
def copy_attributes(self: Self, dataset: Self) -> None: |
| 858 |
"""Copy the data attributes of the input dataset object. |
| 859 |
|
| 860 |
Parameters |
| 861 |
---------- |
| 862 |
dataset : pyvista.DataSet |
| 863 |
Dataset to copy the data attributes from. |
| 864 |
|
| 865 |
Examples |
| 866 |
-------- |
| 867 |
>>> import pyvista as pv |
| 868 |
>>> source = pv.ImageData(dimensions=(10, 10, 5)) |
| 869 |
>>> source = source.compute_cell_sizes() |
| 870 |
>>> target = pv.ImageData(dimensions=(10, 10, 5)) |
| 871 |
>>> target.copy_attributes(source) |
| 872 |
>>> target.plot(scalars='Volume', show_edges=True) |
| 873 |
|
| 874 |
""" |
| 875 |
self.CopyAttributes(dataset) |
| 876 |
|
| 877 |
def __getstate__( # type: ignore[return] # noqa: RET503 |
| 878 |
self: Self, |
| 879 |
) -> tuple[FunctionType, tuple[dict[str, Any]]] | dict[str, Any]: |
| 880 |
"""Support pickle.""" |
| 881 |
pickle_format = pv.PICKLE_FORMAT |
| 882 |
if pickle_format == 'vtk': |
| 883 |
return self._serialize_vtk_pickle_format() |
| 884 |
elif pickle_format in ['xml', 'legacy']: |
| 885 |
return self._serialize_pyvista_pickle_format() |
| 886 |
# Invalid format, use the setter to raise an error |
| 887 |
pv.set_pickle_format(pickle_format) |
| 888 |
|
| 889 |
def _serialize_vtk_pickle_format( |
| 890 |
self: Self, |
| 891 |
) -> tuple[FunctionType, tuple[dict[str, Any]]]: |
| 892 |
# Note: The serialized state has format: ( function, (dict,) ) |
| 893 |
serialized = _vtk.serialize_VTK_data_object(self) |
| 894 |
|
| 895 |
# Add this object's data to the state dictionary |
| 896 |
state_dict = serialized[1][0] |
| 897 |
state_dict['_PYVISTA_STATE_DICT'] = self.__dict__.copy() |
| 898 |
|
| 899 |
# Unlike the PyVista formats, we do not return a dict. Instead, return |
| 900 |
# the same format returned by the vtk serializer. |
| 901 |
return serialized |
| 902 |
|
| 903 |
def _serialize_pyvista_pickle_format(self: Self) -> dict[str, Any]: |
| 904 |
"""Support pickle by serializing the VTK object data. |
| 905 |
|
| 906 |
The format of the serialized VTK object data depends on `pyvista.PICKLE_FORMAT` |
| 907 |
(case-insensitive). |
| 908 |
- If ``'xml'``, the data is serialized as an XML-formatted string. |
| 909 |
- If ``'legacy'``, the data is serialized to bytes in VTK's binary format. |
| 910 |
|
| 911 |
.. note:: |
| 912 |
|
| 913 |
These formats are custom PyVista legacy formats. The native 'vtk' format is |
| 914 |
preferred since it supports more objects (e.g. MultiBlock). |
| 915 |
|
| 916 |
""" |
| 917 |
if isinstance(self, pv.MultiBlock): |
| 918 |
msg = ( |
| 919 |
"MultiBlock is not supported with 'xml' or 'legacy' pickle formats." |
| 920 |
"\nUse `pyvista.PICKLE_FORMAT='vtk'`." |
| 921 |
) |
| 922 |
raise TypeError(msg) |
| 923 |
state = self.__dict__.copy() |
| 924 |
|
| 925 |
if pv.PICKLE_FORMAT.lower() == 'xml': |
| 926 |
# the generic VTK XML writer `vtkXMLDataSetWriter` currently has a bug where it does |
| 927 |
# not pass all settings down to the sub-writers. Until this is fixed, use the |
| 928 |
# dataset-specific writers |
| 929 |
# https://gitlab.kitware.com/vtk/vtk/-/issues/18661 |
| 930 |
writers = { |
| 931 |
_vtk.vtkImageData: _vtk.vtkXMLImageDataWriter, |
| 932 |
_vtk.vtkStructuredGrid: _vtk.vtkXMLStructuredGridWriter, |
| 933 |
_vtk.vtkRectilinearGrid: _vtk.vtkXMLRectilinearGridWriter, |
| 934 |
_vtk.vtkUnstructuredGrid: _vtk.vtkXMLUnstructuredGridWriter, |
| 935 |
_vtk.vtkPolyData: _vtk.vtkXMLPolyDataWriter, |
| 936 |
_vtk.vtkTable: _vtk.vtkXMLTableWriter, |
| 937 |
} |
| 938 |
|
| 939 |
for parent_type, writer_type in writers.items(): |
| 940 |
if isinstance(self, parent_type): |
| 941 |
writer = writer_type() # type: ignore[unreachable] |
| 942 |
break |
| 943 |
else: |
| 944 |
msg = f'Cannot pickle dataset of type {self.GetDataObjectType()}' |
| 945 |
raise TypeError(msg) |
| 946 |
|
| 947 |
writer.SetInputDataObject(self) # type: ignore[unreachable] |
| 948 |
writer.SetWriteToOutputString(True) |
| 949 |
writer.SetDataModeToBinary() |
| 950 |
writer.SetCompressorTypeToNone() |
| 951 |
writer.Write() |
| 952 |
to_serialize = writer.GetOutputString() |
| 953 |
|
| 954 |
elif pv.PICKLE_FORMAT.lower() == 'legacy': |
| 955 |
writer = _vtk.vtkDataSetWriter() |
| 956 |
writer.SetInputDataObject(self) |
| 957 |
writer.SetWriteToOutputString(True) |
| 958 |
writer.SetFileTypeToBinary() |
| 959 |
writer.Write() |
| 960 |
to_serialize = writer.GetOutputStdString() |
| 961 |
|
| 962 |
state['vtk_serialized'] = to_serialize |
| 963 |
|
| 964 |
# this needs to be here because in multiprocessing situations, `pyvista.PICKLE_FORMAT` |
| 965 |
# is not shared between processes |
| 966 |
state['PICKLE_FORMAT'] = pv.PICKLE_FORMAT |
| 967 |
return state |
| 968 |
|
| 969 |
def __setstate__(self: Self, state: Any) -> None: |
| 970 |
"""Support unpickle.""" |
| 971 |
|
| 972 |
def _is_vtk_format(state_: Any) -> bool: |
| 973 |
# Note: The vtk state has format ( function, (dict,) ) |
| 974 |
return ( |
| 975 |
isinstance(state_, tuple) |
| 976 |
and len(state_) == 2 |
| 977 |
and isinstance(state_[1], tuple) |
| 978 |
and len(state_[1]) == 1 |
| 979 |
and isinstance(state_[1][0], dict) |
| 980 |
) |
| 981 |
|
| 982 |
def _is_pyvista_format(state_: Any) -> bool: |
| 983 |
return isinstance(state_, dict) and 'vtk_serialized' in state_ |
| 984 |
|
| 985 |
if _is_vtk_format(state): |
| 986 |
self._unserialize_vtk_pickle_format(state) |
| 987 |
elif _is_pyvista_format(state): |
| 988 |
self._unserialize_pyvista_pickle_format(state) |
| 989 |
else: |
| 990 |
msg = f"Cannot unpickle '{self.__class__.__name__}'. Invalid pickle format." |
| 991 |
raise RuntimeError(msg) |
| 992 |
|
| 993 |
def _unserialize_vtk_pickle_format( |
| 994 |
self: Self, state: tuple[FunctionType, tuple[dict[str, Any]]] |
| 995 |
) -> None: |
| 996 |
"""Support unpickle of VTK's format.""" |
| 997 |
# The vtk state has format: ( function, (dict,) ) |
| 998 |
unserialize_func = state[0] |
| 999 |
state_dict = state[1][0] |
| 1000 |
self.__dict__.update(state_dict['_PYVISTA_STATE_DICT']) |
| 1001 |
obj = unserialize_func(state_dict) |
| 1002 |
self.deep_copy(obj) |
| 1003 |
|
| 1004 |
def _unserialize_pyvista_pickle_format(self: Self, state: dict[str, Any]) -> None: |
| 1005 |
"""Support unpickle of PyVista 'xml' and 'legacy' formats. |
| 1006 |
|
| 1007 |
.. note:: |
| 1008 |
|
| 1009 |
These formats are custom PyVista legacy formats. The native 'vtk' format is |
| 1010 |
preferred since it supports more objects (e.g. MultiBlock). |
| 1011 |
|
| 1012 |
""" |
| 1013 |
vtk_serialized = state.pop('vtk_serialized') |
| 1014 |
pickle_format = state.pop( |
| 1015 |
'PICKLE_FORMAT', |
| 1016 |
'legacy', # backwards compatibility - assume 'legacy' |
| 1017 |
) |
| 1018 |
self.__dict__.update(state) |
| 1019 |
|
| 1020 |
if pickle_format.lower() == 'xml': |
| 1021 |
# the generic VTK XML reader `vtkXMLGenericDataObjectReader` currently has a |
| 1022 |
# bug where it does not pass all settings down to the sub-readers. |
| 1023 |
# Until this is fixed, use the dataset-specific readers |
| 1024 |
# https://gitlab.kitware.com/vtk/vtk/-/issues/18661 |
| 1025 |
readers = { |
| 1026 |
_vtk.vtkImageData: _vtk.vtkXMLImageDataReader, |
| 1027 |
_vtk.vtkStructuredGrid: _vtk.vtkXMLStructuredGridReader, |
| 1028 |
_vtk.vtkRectilinearGrid: _vtk.vtkXMLRectilinearGridReader, |
| 1029 |
_vtk.vtkUnstructuredGrid: _vtk.vtkXMLUnstructuredGridReader, |
| 1030 |
_vtk.vtkPolyData: _vtk.vtkXMLPolyDataReader, |
| 1031 |
_vtk.vtkTable: _vtk.vtkXMLTableReader, |
| 1032 |
} |
| 1033 |
|
| 1034 |
for parent_type, reader_type in readers.items(): |
| 1035 |
if isinstance(self, parent_type): |
| 1036 |
reader = reader_type() # type: ignore[unreachable] |
| 1037 |
break |
| 1038 |
else: |
| 1039 |
msg = f'Cannot unpickle dataset of type {self.GetDataObjectType()}' |
| 1040 |
raise TypeError(msg) |
| 1041 |
|
| 1042 |
reader.ReadFromInputStringOn() # type: ignore[unreachable] |
| 1043 |
reader.SetInputString(vtk_serialized) |
| 1044 |
reader.Update() |
| 1045 |
|
| 1046 |
elif pickle_format.lower() == 'legacy': |
| 1047 |
reader = _vtk.vtkDataSetReader() |
| 1048 |
reader.ReadFromInputStringOn() |
| 1049 |
if isinstance(vtk_serialized, bytes): |
| 1050 |
reader.SetBinaryInputString(vtk_serialized, len(vtk_serialized)) # type: ignore[arg-type] |
| 1051 |
elif isinstance(vtk_serialized, str): |
| 1052 |
reader.SetInputString(vtk_serialized) |
| 1053 |
reader.Update() |
| 1054 |
|
| 1055 |
mesh = wrap(reader.GetOutput()) |
| 1056 |
|
| 1057 |
# copy data |
| 1058 |
self.copy_structure(mesh) # type: ignore[arg-type] |
| 1059 |
self.copy_attributes(mesh) # type: ignore[arg-type] |
| 1060 |
|
| 1061 |
@property |
| 1062 |
@abstractmethod |
| 1063 |
def is_empty(self) -> bool: |
| 1064 |
"""Return ``True`` if the object is empty.""" |
| 1065 |
|
| 1066 |
def cast_to_multiblock(self) -> MultiBlock: |
| 1067 |
"""Convert this :class:`DataObject` to a :class:`~pyvista.MultiBlock`. |
| 1068 |
|
| 1069 |
Uses :vtk:`vtkConvertToMultiBlockDataSet` internally. |
| 1070 |
|
| 1071 |
.. versionadded:: 0.47 |
| 1072 |
|
| 1073 |
Returns |
| 1074 |
------- |
| 1075 |
MultiBlock |
| 1076 |
Converted dataset. |
| 1077 |
|
| 1078 |
""" |
| 1079 |
alg = _vtk.vtkConvertToMultiBlockDataSet() |
| 1080 |
alg.SetInputDataObject(self) |
| 1081 |
alg.Update() |
| 1082 |
return wrap(alg.GetOutput()) # type:ignore[return-value] |