| 1 |
"""Container to mimic :vtk:`vtkMultiBlockDataSet` objects. |
| 2 |
|
| 3 |
These classes hold many VTK datasets in one object that can be passed |
| 4 |
to VTK algorithms and PyVista filtering/plotting routines. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
from collections.abc import Iterator |
| 10 |
from collections.abc import MutableSequence |
| 11 |
from collections.abc import Sequence |
| 12 |
import itertools |
| 13 |
import pathlib |
| 14 |
from typing import TYPE_CHECKING |
| 15 |
from typing import Any |
| 16 |
from typing import ClassVar |
| 17 |
from typing import Literal |
| 18 |
from typing import NoReturn |
| 19 |
from typing import Union |
| 20 |
from typing import cast |
| 21 |
from typing import overload |
| 22 |
|
| 23 |
import numpy as np |
| 24 |
from typing_extensions import Self |
| 25 |
from typing_extensions import TypedDict |
| 26 |
from typing_extensions import Unpack |
| 27 |
|
| 28 |
import pyvista as pv |
| 29 |
from pyvista import _vtk |
| 30 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 31 |
from pyvista.core import _validation |
| 32 |
from pyvista.core._vtk_utilities import vtk_version_info |
| 33 |
|
| 34 |
from ._typing_core import BoundsTuple |
| 35 |
from .dataobject import USER_DICT_KEY |
| 36 |
from .dataobject import DataObject |
| 37 |
from .dataset import DataSet |
| 38 |
from .filters.composite import CompositeFilters |
| 39 |
from .filters.composite import _format_nested_index |
| 40 |
from .formatting_html import _children_section |
| 41 |
from .formatting_html import _fmt_memory |
| 42 |
from .formatting_html import build_repr_html |
| 43 |
from .pyvista_ndarray import pyvista_ndarray |
| 44 |
from .utilities.arrays import CellLiteral |
| 45 |
from .utilities.arrays import FieldAssociation |
| 46 |
from .utilities.arrays import FieldLiteral |
| 47 |
from .utilities.arrays import PointLiteral |
| 48 |
from .utilities.arrays import parse_field_choice |
| 49 |
from .utilities.geometric_objects import Box |
| 50 |
from .utilities.helpers import is_pyvista_dataset |
| 51 |
from .utilities.helpers import wrap |
| 52 |
from .utilities.misc import _BoundsSizeMixin |
| 53 |
from .utilities.writer import HDFWriter |
| 54 |
from .utilities.writer import XMLMultiBlockDataWriter |
| 55 |
|
| 56 |
if TYPE_CHECKING: |
| 57 |
from collections.abc import Iterable |
| 58 |
|
| 59 |
from pyvista import PolyData |
| 60 |
from pyvista import VectorLike |
| 61 |
|
| 62 |
from ._typing_core import NumpyArray |
| 63 |
from .filters.data_object import _NestedMeshValidationFields |
| 64 |
from .utilities.writer import BaseWriter |
| 65 |
|
| 66 |
_TypeMultiBlockLeaf = Union['MultiBlock', DataSet, None] |
| 67 |
|
| 68 |
|
| 69 |
class MultiBlock( |
| 70 |
_BoundsSizeMixin, |
| 71 |
CompositeFilters, |
| 72 |
DataObject, |
| 73 |
MutableSequence, # type: ignore[type-arg] |
| 74 |
_vtk.vtkMultiBlockDataSet, |
| 75 |
): |
| 76 |
"""A composite class to hold many data sets which can be iterated over. |
| 77 |
|
| 78 |
This wraps/extends the :vtk:`vtkMultiBlockDataSet` class |
| 79 |
so that we can easily plot these data sets and use the composite in a |
| 80 |
Pythonic manner. |
| 81 |
|
| 82 |
You can think of ``MultiBlock`` like a list as we |
| 83 |
can iterate over this data structure by index. It has some dictionary |
| 84 |
features as we can also access blocks by their string name. |
| 85 |
|
| 86 |
.. versionchanged:: 0.36.0 |
| 87 |
``MultiBlock`` adheres more closely to being list like, and inherits |
| 88 |
from :class:`collections.abc.MutableSequence`. Multiple nonconforming |
| 89 |
behaviors were removed or modified. |
| 90 |
|
| 91 |
Parameters |
| 92 |
---------- |
| 93 |
*args : dict, optional |
| 94 |
Data object dictionary. |
| 95 |
|
| 96 |
validate : bool | MeshValidationFields | sequence[MeshValidationFields], default: False |
| 97 |
Validate the mesh using :meth:`~pyvista.DataObjectFilters.validate_mesh` after |
| 98 |
initialization. Set this to ``True`` to validate all fields, or specify any |
| 99 |
combination of fields allowed by ``validate_mesh``. |
| 100 |
|
| 101 |
.. versionadded:: 0.47 |
| 102 |
|
| 103 |
**kwargs : dict, optional |
| 104 |
See :func:`pyvista.read` for additional options. |
| 105 |
|
| 106 |
Examples |
| 107 |
-------- |
| 108 |
>>> import pyvista as pv |
| 109 |
|
| 110 |
Create an empty composite dataset. |
| 111 |
|
| 112 |
>>> blocks = pv.MultiBlock() |
| 113 |
|
| 114 |
Add a dataset to the collection. |
| 115 |
|
| 116 |
>>> sphere = pv.Sphere() |
| 117 |
>>> blocks.append(sphere) |
| 118 |
|
| 119 |
Add a named block. |
| 120 |
|
| 121 |
>>> blocks['cube'] = pv.Cube() |
| 122 |
|
| 123 |
Instantiate from a list of objects. |
| 124 |
|
| 125 |
>>> data = [ |
| 126 |
... pv.Sphere(center=(2, 0, 0)), |
| 127 |
... pv.Cube(center=(0, 2, 0)), |
| 128 |
... pv.Cone(), |
| 129 |
... ] |
| 130 |
>>> blocks = pv.MultiBlock(data) |
| 131 |
>>> blocks.plot() |
| 132 |
|
| 133 |
Instantiate from a dictionary. |
| 134 |
|
| 135 |
>>> data = { |
| 136 |
... 'cube': pv.Cube(), |
| 137 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 138 |
... } |
| 139 |
>>> blocks = pv.MultiBlock(data) |
| 140 |
>>> blocks.plot() |
| 141 |
|
| 142 |
Iterate over the collection. |
| 143 |
|
| 144 |
>>> for name in blocks.keys(): |
| 145 |
... block = blocks[name] |
| 146 |
|
| 147 |
>>> for block in blocks: |
| 148 |
... # Do something with each dataset |
| 149 |
... surf = block.extract_surface(algorithm=None) |
| 150 |
|
| 151 |
""" |
| 152 |
|
| 153 |
plot = pv._plot.plot |
| 154 |
|
| 155 |
_WRITERS: ClassVar[dict[str, type[BaseWriter]]] = dict.fromkeys( |
| 156 |
['.vtm', '.vtmb'], XMLMultiBlockDataWriter |
| 157 |
) |
| 158 |
if vtk_version_info >= (9, 4): |
| 159 |
_WRITERS['.vtkhdf'] = HDFWriter |
| 160 |
|
| 161 |
def __init__( |
| 162 |
self: MultiBlock, *args, validate: bool | _NestedMeshValidationFields = False, **kwargs |
| 163 |
) -> None: |
| 164 |
"""Initialize multi block.""" |
| 165 |
super().__init__() |
| 166 |
deep = kwargs.pop('deep', False) |
| 167 |
|
| 168 |
# keep a python reference to the dataset to avoid |
| 169 |
# unintentional garbage collections since python does not |
| 170 |
# add a reference to the dataset when it's added here in |
| 171 |
# MultiBlock. See https://github.com/pyvista/pyvista/pull/1805 |
| 172 |
self._refs: Any = {} |
| 173 |
|
| 174 |
if len(args) == 1: |
| 175 |
if isinstance(args[0], _vtk.vtkMultiBlockDataSet): |
| 176 |
if deep: |
| 177 |
self.deep_copy(args[0]) |
| 178 |
else: |
| 179 |
self.shallow_copy(args[0]) |
| 180 |
elif isinstance(args[0], (list, tuple)): |
| 181 |
for block in args[0]: |
| 182 |
self.append(block) |
| 183 |
elif isinstance(args[0], (str, pathlib.Path)): |
| 184 |
self._from_file(args[0], **kwargs) |
| 185 |
elif isinstance(args[0], dict): |
| 186 |
for key, block in args[0].items(): |
| 187 |
self.append(block, key) |
| 188 |
else: |
| 189 |
msg = f'Type {type(args[0])} is not supported by pyvista.MultiBlock' |
| 190 |
raise TypeError(msg) |
| 191 |
|
| 192 |
elif len(args) > 1: |
| 193 |
msg = 'Invalid number of arguments:\n``pyvista.MultiBlock``supports 0 or 1 arguments.' |
| 194 |
raise ValueError(msg) |
| 195 |
|
| 196 |
# Upon creation make sure all nested structures are wrapped |
| 197 |
self.wrap_nested() |
| 198 |
|
| 199 |
if validate: |
| 200 |
self._validate_mesh(validate) |
| 201 |
|
| 202 |
def wrap_nested(self: MultiBlock) -> None: |
| 203 |
"""Ensure that all nested data structures are wrapped as PyVista datasets. |
| 204 |
|
| 205 |
This is performed in place. |
| 206 |
|
| 207 |
""" |
| 208 |
for i in range(self.n_blocks): |
| 209 |
block = self.GetBlock(i) |
| 210 |
if not is_pyvista_dataset(block): |
| 211 |
self.SetBlock(i, wrap(block)) |
| 212 |
|
| 213 |
def _items(self) -> Iterable[tuple[str | None, _TypeMultiBlockLeaf]]: |
| 214 |
yield from zip(self.keys(), self, strict=True) |
| 215 |
|
| 216 |
_OrderLiteral = Literal['nested_first', 'nested_last'] |
| 217 |
|
| 218 |
class _RecursiveIteratorBasicKwargs(TypedDict, total=False): |
| 219 |
"""Define kwargs which have no impact on return type.""" |
| 220 |
|
| 221 |
skip_empty: bool |
| 222 |
prepend_names: bool |
| 223 |
separator: str |
| 224 |
|
| 225 |
@overload # 'ids', nested_ids=True |
| 226 |
def recursive_iterator( |
| 227 |
self: MultiBlock, |
| 228 |
contents: Literal['ids'], |
| 229 |
order: _OrderLiteral | None = ..., |
| 230 |
*, |
| 231 |
node_type: Literal['parent', 'child'] = ..., |
| 232 |
skip_none: bool = ..., |
| 233 |
nested_ids: Literal[True] | None = ..., |
| 234 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 235 |
) -> Iterator[tuple[int, ...]]: ... |
| 236 |
@overload # 'ids', nested_ids=False |
| 237 |
def recursive_iterator( |
| 238 |
self: MultiBlock, |
| 239 |
contents: Literal['ids'], |
| 240 |
order: _OrderLiteral | None = ..., |
| 241 |
*, |
| 242 |
node_type: Literal['parent', 'child'] = ..., |
| 243 |
skip_none: bool = ..., |
| 244 |
nested_ids: Literal[False], |
| 245 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 246 |
) -> Iterator[int]: ... |
| 247 |
@overload # 'names' |
| 248 |
def recursive_iterator( |
| 249 |
self: MultiBlock, |
| 250 |
contents: Literal['names'], |
| 251 |
order: _OrderLiteral | None = ..., |
| 252 |
*, |
| 253 |
node_type: Literal['parent', 'child'] = ..., |
| 254 |
skip_none: bool = ..., |
| 255 |
nested_ids: bool | None = ..., |
| 256 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 257 |
) -> Iterator[str]: ... |
| 258 |
@overload # 'items', node_type='child', skip_none=False |
| 259 |
def recursive_iterator( |
| 260 |
self: MultiBlock, |
| 261 |
contents: Literal['items'], |
| 262 |
order: _OrderLiteral | None = ..., |
| 263 |
*, |
| 264 |
node_type: Literal['child'] = ..., |
| 265 |
skip_none: Literal[False] = ..., |
| 266 |
nested_ids: bool | None = ..., |
| 267 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 268 |
) -> Iterator[tuple[str, DataSet | None]]: ... |
| 269 |
@overload # 'items', node_type='child', skip_none=True |
| 270 |
def recursive_iterator( |
| 271 |
self: MultiBlock, |
| 272 |
contents: Literal['items'], |
| 273 |
order: _OrderLiteral | None = ..., |
| 274 |
*, |
| 275 |
node_type: Literal['child'] = ..., |
| 276 |
skip_none: Literal[True], |
| 277 |
nested_ids: bool | None = ..., |
| 278 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 279 |
) -> Iterator[tuple[str, DataSet]]: ... |
| 280 |
@overload # 'blocks', node_type='child', skip_None=True |
| 281 |
def recursive_iterator( |
| 282 |
self: MultiBlock, |
| 283 |
contents: Literal['blocks'] = ..., |
| 284 |
order: _OrderLiteral | None = ..., |
| 285 |
*, |
| 286 |
node_type: Literal['child'] = ..., |
| 287 |
skip_none: Literal[True], |
| 288 |
nested_ids: bool | None = ..., |
| 289 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 290 |
) -> Iterator[DataSet]: ... |
| 291 |
@overload # 'blocks', node_type='child', skip_None=False |
| 292 |
def recursive_iterator( |
| 293 |
self: MultiBlock, |
| 294 |
contents: Literal['blocks'] = ..., |
| 295 |
order: _OrderLiteral | None = ..., |
| 296 |
*, |
| 297 |
node_type: Literal['child'] = ..., |
| 298 |
skip_none: Literal[False] = ..., |
| 299 |
nested_ids: bool | None = ..., |
| 300 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 301 |
) -> Iterator[DataSet | None]: ... |
| 302 |
@overload # 'all', node_type='child', skip_none=True, nested_ids=True |
| 303 |
def recursive_iterator( |
| 304 |
self: MultiBlock, |
| 305 |
contents: Literal['all'], |
| 306 |
order: _OrderLiteral | None = ..., |
| 307 |
*, |
| 308 |
node_type: Literal['child'] = ..., |
| 309 |
skip_none: Literal[True], |
| 310 |
nested_ids: Literal[True] | None = ..., |
| 311 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 312 |
) -> Iterator[tuple[tuple[int, ...], str, DataSet]]: ... |
| 313 |
@overload # 'all', node_type='child', skip_none=False, nested_ids=True |
| 314 |
def recursive_iterator( |
| 315 |
self: MultiBlock, |
| 316 |
contents: Literal['all'], |
| 317 |
order: _OrderLiteral | None = ..., |
| 318 |
*, |
| 319 |
node_type: Literal['child'] = ..., |
| 320 |
skip_none: Literal[False] = ..., |
| 321 |
nested_ids: Literal[True] | None = ..., |
| 322 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 323 |
) -> Iterator[tuple[tuple[int, ...], str, DataSet | None]]: ... |
| 324 |
@overload # 'all', node_type='child', skip_none=True, nested_ids=False |
| 325 |
def recursive_iterator( |
| 326 |
self: MultiBlock, |
| 327 |
contents: Literal['all'], |
| 328 |
order: _OrderLiteral | None = ..., |
| 329 |
*, |
| 330 |
node_type: Literal['child'] = ..., |
| 331 |
skip_none: Literal[True], |
| 332 |
nested_ids: Literal[False], |
| 333 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 334 |
) -> Iterator[tuple[int, str, DataSet]]: ... |
| 335 |
@overload # 'all', node_type='child', skip_none=False, nested_ids=False |
| 336 |
def recursive_iterator( |
| 337 |
self: MultiBlock, |
| 338 |
contents: Literal['all'], |
| 339 |
order: _OrderLiteral | None = ..., |
| 340 |
*, |
| 341 |
node_type: Literal['child'] = ..., |
| 342 |
skip_none: Literal[False] = ..., |
| 343 |
nested_ids: Literal[False], |
| 344 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 345 |
) -> Iterator[tuple[int, str, DataSet | None]]: ... |
| 346 |
@overload # 'items', node_type='parent' |
| 347 |
def recursive_iterator( |
| 348 |
self: MultiBlock, |
| 349 |
contents: Literal['items'], |
| 350 |
order: _OrderLiteral | None = ..., |
| 351 |
*, |
| 352 |
node_type: Literal['parent'], |
| 353 |
skip_none: bool = ..., |
| 354 |
nested_ids: bool | None = ..., |
| 355 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 356 |
) -> Iterator[tuple[str, MultiBlock]]: ... |
| 357 |
@overload # 'blocks', node_type='parent' |
| 358 |
def recursive_iterator( |
| 359 |
self: MultiBlock, |
| 360 |
contents: Literal['blocks'] = ..., |
| 361 |
order: _OrderLiteral | None = ..., |
| 362 |
*, |
| 363 |
node_type: Literal['parent'], |
| 364 |
skip_none: Literal[False] = ..., |
| 365 |
nested_ids: bool | None = ..., |
| 366 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 367 |
) -> Iterator[MultiBlock]: ... |
| 368 |
@overload # 'all', node_type='parent', nested_ids=True |
| 369 |
def recursive_iterator( |
| 370 |
self: MultiBlock, |
| 371 |
contents: Literal['all'], |
| 372 |
order: _OrderLiteral | None = ..., |
| 373 |
*, |
| 374 |
node_type: Literal['parent'], |
| 375 |
skip_none: Literal[False] = ..., |
| 376 |
nested_ids: Literal[True] | None = ..., |
| 377 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 378 |
) -> Iterator[tuple[tuple[int, ...], str, MultiBlock]]: ... |
| 379 |
@overload # 'all', node_type='parent', nested_ids=False |
| 380 |
def recursive_iterator( |
| 381 |
self: MultiBlock, |
| 382 |
contents: Literal['all'], |
| 383 |
order: _OrderLiteral | None = ..., |
| 384 |
*, |
| 385 |
node_type: Literal['parent'], |
| 386 |
skip_none: Literal[False] = ..., |
| 387 |
nested_ids: Literal[False], |
| 388 |
**kwargs: Unpack[_RecursiveIteratorBasicKwargs], |
| 389 |
) -> Iterator[tuple[int, str, MultiBlock]]: ... |
| 390 |
@overload # general case |
| 391 |
def recursive_iterator( |
| 392 |
self: MultiBlock, |
| 393 |
contents: Literal['ids', 'names', 'blocks', 'items', 'all'] = ..., |
| 394 |
order: _OrderLiteral | None = ..., |
| 395 |
*, |
| 396 |
node_type: Literal['parent', 'child'] = ..., |
| 397 |
skip_none: bool = ..., |
| 398 |
skip_empty: bool = ..., |
| 399 |
nested_ids: bool | None = ..., |
| 400 |
prepend_names: bool = ..., |
| 401 |
separator: str = ..., |
| 402 |
) -> ( |
| 403 |
Iterator[int | tuple[int, ...] | str | _TypeMultiBlockLeaf] |
| 404 |
| Iterator[tuple[str, _TypeMultiBlockLeaf]] |
| 405 |
| Iterator[tuple[int | tuple[int, ...], str, _TypeMultiBlockLeaf]] |
| 406 |
): ... |
| 407 |
def recursive_iterator( |
| 408 |
self: MultiBlock, |
| 409 |
contents: Literal['ids', 'names', 'blocks', 'items', 'all'] = 'blocks', |
| 410 |
order: Literal['nested_first', 'nested_last'] | None = None, |
| 411 |
*, |
| 412 |
node_type: Literal['parent', 'child'] = 'child', |
| 413 |
skip_none: bool = False, |
| 414 |
skip_empty: bool = False, |
| 415 |
nested_ids: bool | None = None, |
| 416 |
prepend_names: bool = False, |
| 417 |
separator: str = '::', |
| 418 |
) -> ( |
| 419 |
Iterator[int | tuple[int, ...] | str | _TypeMultiBlockLeaf] |
| 420 |
| Iterator[tuple[str, _TypeMultiBlockLeaf]] |
| 421 |
| Iterator[tuple[int | tuple[int, ...], str, _TypeMultiBlockLeaf]] |
| 422 |
): |
| 423 |
"""Iterate over all nested blocks recursively. |
| 424 |
|
| 425 |
.. versionadded:: 0.45 |
| 426 |
|
| 427 |
Parameters |
| 428 |
---------- |
| 429 |
contents : 'ids' | 'names' | 'blocks' | 'items', default: 'blocks' |
| 430 |
Values to include in the iterator. |
| 431 |
|
| 432 |
- ``'ids'``: Return an iterator with nested block indices. |
| 433 |
- ``'names'``: Return an iterator with nested block names (i.e. :meth:`keys`). |
| 434 |
- ``'blocks'``: Return an iterator with nested blocks. |
| 435 |
- ``'items'``: Return an iterator with nested ``(name, block)`` pairs. |
| 436 |
- ``'all'``: Return an iterator with nested ``(index, name, block)`` triplets. |
| 437 |
|
| 438 |
.. note:: |
| 439 |
|
| 440 |
Use the ``nested_ids`` and ``prepend_names`` options to modify how |
| 441 |
the block ids and names are represented, respectively. |
| 442 |
|
| 443 |
order : 'nested_first', 'nested_last', optional |
| 444 |
Order in which to iterate through nested blocks. |
| 445 |
|
| 446 |
- ``'nested_first'``: Iterate through nested ``MultiBlock`` blocks first. |
| 447 |
- ``'nested_last'``: Iterate through nested ``MultiBlock`` blocks last. |
| 448 |
|
| 449 |
By default, the ``MultiBlock`` is iterated recursively as-is without |
| 450 |
changing the order. This option only applies when ``node_type`` is ``'child'``. |
| 451 |
|
| 452 |
node_type : 'parent' | 'child', default: 'child' |
| 453 |
Type of node blocks to generate ``contents`` from. If ``'parent'``, the |
| 454 |
contents are generated from :class:`MultiBlock` nodes. If ``'child'``, the |
| 455 |
contents are generated from :class:`~pyvista.DataSet` and ``None`` nodes. |
| 456 |
|
| 457 |
skip_none : bool, default: False |
| 458 |
If ``True``, do not include ``None`` blocks in the iterator. This option |
| 459 |
only applies when ``node_type`` is ``'child'``. |
| 460 |
|
| 461 |
skip_empty : bool, default: False |
| 462 |
If ``True``, do not include empty meshes in the iterator. If ``node_type`` |
| 463 |
is ``'parent'``, any :class:`MultiBlock` block with length ``0`` is skipped. |
| 464 |
If ``node_type`` is ``'child'``, any :class:`~pyvista.DataSet` block with |
| 465 |
``0`` points is skipped. |
| 466 |
|
| 467 |
nested_ids : bool, default: True |
| 468 |
Prepend parent block indices to the child block indices. If ``True``, a |
| 469 |
tuple of indices is returned for each block. If ``False``, a single integer |
| 470 |
index is returned for each block. This option only applies when ``contents`` |
| 471 |
is ``'ids'`` or ``'all'``. |
| 472 |
|
| 473 |
prepend_names : bool, default: False |
| 474 |
Prepend any parent block names to the child block names. This option |
| 475 |
only applies when ``contents`` is ``'names'``, ``'items'``, or ``'all'``. |
| 476 |
|
| 477 |
separator : str, default: '::' |
| 478 |
String separator to use when ``prepend_names`` is enabled. The separator |
| 479 |
is inserted between parent and child block names. |
| 480 |
|
| 481 |
Returns |
| 482 |
------- |
| 483 |
Iterator |
| 484 |
Iterator of ids, names, blocks, or name-block pairs depending on ``contents``. |
| 485 |
|
| 486 |
See Also |
| 487 |
-------- |
| 488 |
flatten |
| 489 |
Uses the iterator internally to flatten a :class:`MultiBlock`. |
| 490 |
pyvista.CompositeFilters.generic_filter |
| 491 |
Uses the iterator internally to apply filters to all blocks. |
| 492 |
clean |
| 493 |
Remove ``None`` and/or empty mesh blocks. |
| 494 |
|
| 495 |
Examples |
| 496 |
-------- |
| 497 |
Load a :class:`MultiBlock` with nested datasets. |
| 498 |
|
| 499 |
>>> import pyvista as pv |
| 500 |
>>> from pyvista import examples |
| 501 |
>>> multi = examples.download_exodus() |
| 502 |
|
| 503 |
The dataset has eight :class:`MultiBlock` blocks. |
| 504 |
|
| 505 |
>>> multi.n_blocks |
| 506 |
8 |
| 507 |
|
| 508 |
>>> all(isinstance(block, pv.MultiBlock) for block in multi) |
| 509 |
True |
| 510 |
|
| 511 |
Get the iterator and show the count of all recursively nested blocks. |
| 512 |
|
| 513 |
>>> iterator = multi.recursive_iterator() |
| 514 |
>>> iterator |
| 515 |
<generator object MultiBlock._recursive_iterator at ...> |
| 516 |
|
| 517 |
>>> len(list(iterator)) |
| 518 |
11 |
| 519 |
|
| 520 |
Check if all blocks are :class:`~pyvista.DataSet` objects. Note that ``None`` |
| 521 |
blocks are included by default, so this may not be ``True`` in all cases. |
| 522 |
|
| 523 |
>>> all(isinstance(item, pv.DataSet) for item in multi.recursive_iterator()) |
| 524 |
True |
| 525 |
|
| 526 |
Use the iterator to apply a filter inplace to all recursively nested datasets. |
| 527 |
|
| 528 |
>>> _ = [ |
| 529 |
... dataset.connectivity(inplace=True) |
| 530 |
... for dataset in multi.recursive_iterator() |
| 531 |
... ] |
| 532 |
|
| 533 |
Iterate through nested block names. |
| 534 |
|
| 535 |
>>> iterator = multi.recursive_iterator('names') |
| 536 |
>>> next(iterator) |
| 537 |
'Unnamed block ID: 1' |
| 538 |
|
| 539 |
Prepend parent block names. |
| 540 |
|
| 541 |
>>> iterator = multi.recursive_iterator('names', prepend_names=True) |
| 542 |
>>> next(iterator) |
| 543 |
'Element Blocks::Unnamed block ID: 1' |
| 544 |
|
| 545 |
Iterate through name-block pairs. Prepend parent block names again using a |
| 546 |
custom separator. |
| 547 |
|
| 548 |
>>> iterator = multi.recursive_iterator( |
| 549 |
... 'items', prepend_names=True, separator='->' |
| 550 |
... ) |
| 551 |
>>> next(iterator) |
| 552 |
('Element Blocks->Unnamed block ID: 1', UnstructuredGrid (...) |
| 553 |
N Cells: 336 |
| 554 |
N Points: 400 |
| 555 |
X Bounds: 0.000e+00, 1.200e+01 |
| 556 |
Y Bounds: 0.000e+00, 3.500e+00 |
| 557 |
Z Bounds: 0.000e+00, 3.399e+00 |
| 558 |
N Arrays: 6) |
| 559 |
|
| 560 |
Iterate through ids. The ids are returned as a tuple by default. |
| 561 |
|
| 562 |
>>> iterator = multi.recursive_iterator('ids') |
| 563 |
>>> next(iterator) |
| 564 |
(0, 0) |
| 565 |
|
| 566 |
Use :meth:`get_block` and get the next block indicated by the nested ids. |
| 567 |
|
| 568 |
>>> multi.get_block(next(iterator)) |
| 569 |
UnstructuredGrid ... |
| 570 |
|
| 571 |
Use the iterator to :attr:`replace` all blocks with new blocks. Similar to a previous |
| 572 |
example, we use a filter but this time the operation is not performed in place. |
| 573 |
|
| 574 |
>>> iterator = multi.recursive_iterator('all', nested_ids=True) |
| 575 |
>>> for ids, _, block in iterator: |
| 576 |
... multi.replace(ids, block.connectivity()) |
| 577 |
|
| 578 |
Use ``node_type='parent'`` to get information about :class:`MultiBlock` nodes. |
| 579 |
|
| 580 |
>>> iterator = multi.recursive_iterator(node_type='parent') |
| 581 |
|
| 582 |
The iterator has ``8`` items. In this case this matches the number of blocks |
| 583 |
in the root block. |
| 584 |
|
| 585 |
>>> len(list(iterator)) |
| 586 |
8 |
| 587 |
|
| 588 |
Use ``skip_empty`` to skip :class:`MultiBlock` nodes which have length ``0`` |
| 589 |
and return their block ids. |
| 590 |
|
| 591 |
>>> iterator = multi.recursive_iterator( |
| 592 |
... 'ids', node_type='parent', skip_empty=True |
| 593 |
... ) |
| 594 |
>>> ids = list(iterator) |
| 595 |
|
| 596 |
There are two non-empty blocks at index ``0`` and ``4``. |
| 597 |
|
| 598 |
>>> len(ids) |
| 599 |
2 |
| 600 |
>>> ids |
| 601 |
[(0,), (4,)] |
| 602 |
|
| 603 |
""" |
| 604 |
_validation.check_contains( |
| 605 |
['ids', 'names', 'blocks', 'items', 'all'], |
| 606 |
must_contain=contents, |
| 607 |
name='contents', |
| 608 |
) |
| 609 |
_validation.check_contains( |
| 610 |
['nested_first', 'nested_last', None], must_contain=order, name='order' |
| 611 |
) |
| 612 |
nested_ids = contents in ['ids', 'all'] if nested_ids is None else nested_ids |
| 613 |
if nested_ids and contents not in ['ids', 'all']: |
| 614 |
msg = 'Nested ids option only applies when ids are returned.' |
| 615 |
raise ValueError(msg) |
| 616 |
if prepend_names and contents not in ['names', 'items', 'all']: |
| 617 |
msg = 'Prepend names option only applies when names are returned.' |
| 618 |
raise ValueError(msg) |
| 619 |
if node_type == 'parent': |
| 620 |
if skip_none: |
| 621 |
msg = "Cannot skip None blocks when the node type is 'parent'." |
| 622 |
raise ValueError(msg) |
| 623 |
if order is not None: |
| 624 |
msg = "Cannot set order when the node type is 'parent'." |
| 625 |
raise TypeError(msg) |
| 626 |
_validation.check_instance(separator, str, name='separator') |
| 627 |
if not separator: |
| 628 |
msg = 'String separator cannot be empty.' |
| 629 |
raise ValueError(msg) |
| 630 |
|
| 631 |
return self._recursive_iterator( |
| 632 |
ids=[[i] for i in range(self.n_blocks)], |
| 633 |
names=self.keys(), |
| 634 |
contents=contents, |
| 635 |
order=order, |
| 636 |
node_type=node_type, |
| 637 |
skip_none=skip_none, |
| 638 |
skip_empty=skip_empty, |
| 639 |
nested_ids=nested_ids, |
| 640 |
prepend_names=prepend_names, |
| 641 |
separator=separator, |
| 642 |
) |
| 643 |
|
| 644 |
def _recursive_iterator( |
| 645 |
self, |
| 646 |
*, |
| 647 |
ids: Iterable[list[int]], |
| 648 |
names: Iterable[str], |
| 649 |
contents: Literal['ids', 'names', 'blocks', 'items', 'all'], |
| 650 |
order: Literal['nested_first', 'nested_last'] | None = None, |
| 651 |
node_type: Literal['parent', 'child'] = 'child', |
| 652 |
skip_none: bool, |
| 653 |
skip_empty: bool, |
| 654 |
nested_ids: bool, |
| 655 |
prepend_names: bool, |
| 656 |
separator: str, |
| 657 |
) -> ( |
| 658 |
Iterator[int | tuple[int, ...] | str | _TypeMultiBlockLeaf] |
| 659 |
| Iterator[tuple[str, _TypeMultiBlockLeaf]] |
| 660 |
| Iterator[tuple[int | tuple[int, ...], str, _TypeMultiBlockLeaf]] |
| 661 |
): |
| 662 |
# Determine ordering of blocks and names to iterate through |
| 663 |
if order is None: |
| 664 |
blocks: Sequence[_TypeMultiBlockLeaf] = self |
| 665 |
else: |
| 666 |
# Need to reorder blocks |
| 667 |
multi_ids = [] |
| 668 |
multi_names = [] |
| 669 |
multi_blocks = [] |
| 670 |
other_ids = [] |
| 671 |
other_names = [] |
| 672 |
other_blocks = [] |
| 673 |
for id_, name, block in zip(ids, names, self, strict=True): |
| 674 |
if isinstance(block, MultiBlock): |
| 675 |
multi_ids.append(id_) |
| 676 |
multi_names.append(name) |
| 677 |
multi_blocks.append(block) |
| 678 |
else: |
| 679 |
other_ids.append(id_) |
| 680 |
other_names.append(name) |
| 681 |
other_blocks.append(block) |
| 682 |
if order == 'nested_last': |
| 683 |
ids = [*other_ids, *multi_ids] |
| 684 |
names = [*other_names, *multi_names] |
| 685 |
blocks = [*other_blocks, *multi_blocks] |
| 686 |
else: |
| 687 |
ids = [*multi_ids, *other_ids] |
| 688 |
names = [*multi_names, *other_names] |
| 689 |
blocks = [*multi_blocks, *other_blocks] |
| 690 |
|
| 691 |
# Iterate through ids, names, blocks |
| 692 |
for id_, name, block in zip(ids, names, blocks, strict=True): |
| 693 |
if (skip_none and block is None) or ( |
| 694 |
skip_empty and (block is not None and block.is_empty) |
| 695 |
): |
| 696 |
continue |
| 697 |
elif isinstance(block, MultiBlock): |
| 698 |
if skip_empty and len(block) == 0: |
| 699 |
continue |
| 700 |
|
| 701 |
# Process names |
| 702 |
names = block.keys() |
| 703 |
if prepend_names: |
| 704 |
# Include parent name with the block names |
| 705 |
names = [f'{name}{separator}{block_name}' for block_name in names] |
| 706 |
|
| 707 |
# Process ids |
| 708 |
if nested_ids: |
| 709 |
# Include parent id with the block ids |
| 710 |
ids = [[*id_, i] for i in range(block.n_blocks)] |
| 711 |
else: |
| 712 |
ids = [[i] for i in range(block.n_blocks)] |
| 713 |
|
| 714 |
# Yield from multiblock but fall-through in some cases for 'parent' nodes |
| 715 |
if node_type == 'child' or block.is_nested: |
| 716 |
yield from block._recursive_iterator( |
| 717 |
ids=ids, |
| 718 |
names=names, |
| 719 |
contents=contents, |
| 720 |
order=order, |
| 721 |
node_type=node_type, |
| 722 |
skip_none=skip_none, |
| 723 |
skip_empty=skip_empty, |
| 724 |
nested_ids=nested_ids, |
| 725 |
prepend_names=prepend_names, |
| 726 |
separator=separator, |
| 727 |
) |
| 728 |
if node_type == 'child': |
| 729 |
continue |
| 730 |
elif node_type == 'parent': |
| 731 |
continue |
| 732 |
|
| 733 |
if contents == 'ids': |
| 734 |
yield tuple(id_) if nested_ids else id_[0] |
| 735 |
elif contents == 'names': |
| 736 |
yield name |
| 737 |
elif contents == 'blocks': |
| 738 |
yield block |
| 739 |
elif contents == 'items': |
| 740 |
yield name, block |
| 741 |
elif contents == 'all': |
| 742 |
id_out = tuple(id_) if nested_ids else id_[0] |
| 743 |
yield id_out, name, block |
| 744 |
else: # pragma: no cover |
| 745 |
msg = f"Unexpected contents '{contents}'." # type: ignore[unreachable] |
| 746 |
raise RuntimeError(msg) |
| 747 |
|
| 748 |
def move_nested_field_data_to_root( |
| 749 |
self, |
| 750 |
*, |
| 751 |
copy: bool | None = None, |
| 752 |
field_data_mode: Literal['preserve', 'prepend'] = 'preserve', |
| 753 |
user_dict_mode: Literal['preserve', 'prepend', 'flat', 'nested'] = 'preserve', |
| 754 |
separator: str = '::', |
| 755 |
check_duplicate_keys: bool = True, |
| 756 |
) -> None: |
| 757 |
"""Move or copy field data from all nested :class:`MultiBlock` blocks. |
| 758 |
|
| 759 |
Any nested :class:`MultiBlock` blocks will have its :attr:`~pyvista.DataObject.field_data` |
| 760 |
contents moved to the root block, (i.e. `this` ``MultiBock``). By default, this |
| 761 |
data will be cleared from the nested block(s) but a copy may be made instead. |
| 762 |
|
| 763 |
If any nested :class:`MultiBlock` blocks define a :attr:`~pyvista.DataObject.user_dict`, |
| 764 |
the root user-dict is also updated to include the nested block's user-dict |
| 765 |
data. |
| 766 |
|
| 767 |
All field data and user-dict keys are directly updated from the nested blocks |
| 768 |
by default. Optionally, different modes are provided to control the key names |
| 769 |
and/or how the data is moved. The move is done safely such that no key values |
| 770 |
will be overwritten and no data is lost. If any nested keys are duplicates |
| 771 |
of the root keys, an error is raised. |
| 772 |
|
| 773 |
.. note:: |
| 774 |
This operation only applies to nested :class:`MultiBlock` blocks. Field data |
| 775 |
associated with :class:`~pyvista.DataSet` blocks is `not` affected. |
| 776 |
|
| 777 |
.. versionadded:: 0.45 |
| 778 |
|
| 779 |
Parameters |
| 780 |
---------- |
| 781 |
copy : bool, optional |
| 782 |
Set this value to copy the data. If ``True``, deep-copy the data from nested |
| 783 |
``MultiBlock`` blocks to the root block. Both the root and nested blocks |
| 784 |
will share the same keys and refer to separate copies of the data. If |
| 785 |
``False``, both the root and nested blocks will share the same keys but |
| 786 |
refer to the same data. By default, no copy is made; the nested field data |
| 787 |
is moved to the root block and cleared from the nested ``MultiBlock`` blocks. |
| 788 |
|
| 789 |
.. note:: |
| 790 |
|
| 791 |
This option does not apply to any nested :attr:`~pyvista.DataObject.user_dict` |
| 792 |
data. User-dict data is always deep-copied. |
| 793 |
|
| 794 |
field_data_mode : 'preserve' | 'prepend', default: 'preserve' |
| 795 |
Mode for naming the root field data keys when moving nested field data. |
| 796 |
|
| 797 |
- ``'preserve'``: The array names of nested field data are preserved. |
| 798 |
- ``'prepend'``: Preserve the array names and prepend the parent names. |
| 799 |
|
| 800 |
user_dict_mode : 'preserve' | 'prepend' | 'flat' | 'nested', default: 'preserve' |
| 801 |
Mode for naming the root :attr:`~pyvista.DataObject.user_dict` keys when |
| 802 |
nested :class:`MultiBlock` blocks define a user-dict. |
| 803 |
|
| 804 |
- ``'preserve'``: Update the root user dict directly with the items of any |
| 805 |
nested user-dict. |
| 806 |
- ``'nested'``: Create nested keys in the root user-dict which match the |
| 807 |
nested hierarchy of any nested ``MultiBlock`` blocks. |
| 808 |
- ``'flat'``: Create a new key in the root user dict for each nested |
| 809 |
``MultiBlock`` that has a user-dict. |
| 810 |
- ``'prepend'``: Similar to ``'flat'`` except the key names are prepended |
| 811 |
with the parent block names. |
| 812 |
|
| 813 |
.. note:: |
| 814 |
If there is only a single level of nesting the ``'flat'``, ``'nested'`` |
| 815 |
and ``'prepend'`` modes are all equivalent. They only differ when there |
| 816 |
is at least two levels of nesting. |
| 817 |
|
| 818 |
separator : str, default: '::' |
| 819 |
String separator to use when ``'prepend'`` mode is enabled for either field |
| 820 |
data or for the user-dict. The separator is inserted between parent and child |
| 821 |
block names. |
| 822 |
|
| 823 |
check_duplicate_keys : bool, default: True |
| 824 |
Update the root data safely without overwriting existing data. If ``True``, |
| 825 |
an error is raised if any nested keys match the root block's keys. If |
| 826 |
``False``, nested data is moved without checking if a key already exists, |
| 827 |
and data may be overwritten. |
| 828 |
|
| 829 |
Raises |
| 830 |
------ |
| 831 |
ValueError |
| 832 |
If any field data keys in nested :class:`MultiBlock` blocks are duplicated |
| 833 |
in the root block and ``check_duplicate_keys`` is ``True``. |
| 834 |
|
| 835 |
See Also |
| 836 |
-------- |
| 837 |
flatten |
| 838 |
|
| 839 |
Examples |
| 840 |
-------- |
| 841 |
Create a :class:`MultiBlock` with field data. |
| 842 |
|
| 843 |
>>> import pyvista as pv |
| 844 |
>>> multi = pv.MultiBlock() |
| 845 |
>>> multi.field_data['data'] = [1, 2, 3] |
| 846 |
|
| 847 |
Nest the dataset inside another ``MultiBlock``. |
| 848 |
|
| 849 |
>>> root = pv.MultiBlock([multi]) |
| 850 |
|
| 851 |
Show that the root block does not have any field data. |
| 852 |
|
| 853 |
>>> root.field_data.keys() |
| 854 |
[] |
| 855 |
|
| 856 |
Move the nested field data to the root. |
| 857 |
|
| 858 |
>>> root.move_nested_field_data_to_root() |
| 859 |
|
| 860 |
The field data is now at the root. |
| 861 |
|
| 862 |
>>> root.field_data.keys() |
| 863 |
['data'] |
| 864 |
|
| 865 |
And no longer exists in the nested ``MultiBlock``. |
| 866 |
|
| 867 |
>>> multi.field_data.keys() |
| 868 |
[] |
| 869 |
|
| 870 |
Add more field data to the nested block. |
| 871 |
|
| 872 |
>>> multi.field_data['more_data'] = [4, 5, 6] |
| 873 |
|
| 874 |
Move it to the root again, but this time prepend the name of the block the data |
| 875 |
came from. |
| 876 |
|
| 877 |
>>> root.move_nested_field_data_to_root(field_data_mode='prepend') |
| 878 |
>>> root.field_data.keys() |
| 879 |
['data', 'Block-00::more_data'] |
| 880 |
|
| 881 |
The :attr:`~pyvista.DataObject.user_dict` is also field data which is moved to |
| 882 |
the root block's user-dict. |
| 883 |
|
| 884 |
Add sample data to the nested block and move it to the root. |
| 885 |
|
| 886 |
>>> data = dict(foo='bar') |
| 887 |
>>> multi.user_dict = data |
| 888 |
>>> root.move_nested_field_data_to_root() |
| 889 |
|
| 890 |
Check the root's user-dict. By default, the key names are preserved and the root |
| 891 |
dict is updated with the nested dict. |
| 892 |
|
| 893 |
>>> root.user_dict |
| 894 |
{"foo": "bar"} |
| 895 |
|
| 896 |
Clear the field data and re-add data to the nested user-dict. |
| 897 |
|
| 898 |
>>> root.clear_field_data() |
| 899 |
>>> multi.user_dict = data |
| 900 |
|
| 901 |
Move the data again but use the ``'flat'`` mode. This time, a new key is added |
| 902 |
which matches the nested block's name. |
| 903 |
|
| 904 |
>>> root.move_nested_field_data_to_root(user_dict_mode='flat') |
| 905 |
>>> root.user_dict |
| 906 |
{"Block-00": {"foo": "bar"}} |
| 907 |
|
| 908 |
""" |
| 909 |
_validation.check_contains( |
| 910 |
['prepend', 'preserve'], |
| 911 |
must_contain=field_data_mode, |
| 912 |
name='field_data_mode', |
| 913 |
) |
| 914 |
_validation.check_contains( |
| 915 |
['prepend', 'preserve', 'flat', 'nested'], |
| 916 |
must_contain=user_dict_mode, |
| 917 |
name='user_dict_mode', |
| 918 |
) |
| 919 |
|
| 920 |
root_field_data = self.field_data |
| 921 |
prepend_names = field_data_mode == 'prepend' |
| 922 |
|
| 923 |
iterator = self.recursive_iterator( |
| 924 |
'all', node_type='parent', prepend_names=True, separator=separator |
| 925 |
) |
| 926 |
for index, block_name, nested_multi in iterator: |
| 927 |
# Get nested field data to be moved |
| 928 |
nested_field_data = nested_multi.field_data |
| 929 |
if prepend_names: |
| 930 |
# Add the field data to a temp mesh so we can rename the arrays |
| 931 |
temp_mesh = pv.ImageData() |
| 932 |
temp_field_data = temp_mesh.field_data |
| 933 |
for old_name in nested_field_data: |
| 934 |
new_name = f'{block_name}{separator}{old_name}' |
| 935 |
temp_field_data[new_name] = nested_field_data[old_name] |
| 936 |
field_data_to_copy = temp_field_data |
| 937 |
else: |
| 938 |
field_data_to_copy = nested_field_data |
| 939 |
|
| 940 |
for array_name in field_data_to_copy: |
| 941 |
# Check for nested user-dict data |
| 942 |
if array_name.endswith(USER_DICT_KEY): |
| 943 |
root_user_dict = self.user_dict |
| 944 |
|
| 945 |
def raise_key_error( |
| 946 |
duplicate_key: str, block_name_: str, index_: tuple[int, ...] |
| 947 |
) -> NoReturn: |
| 948 |
index_fmt = _format_nested_index(index_) |
| 949 |
msg = ( |
| 950 |
f'The root user dict cannot be updated with data from nested ' |
| 951 |
f"MultiBlock at index {index_fmt} with name '{block_name_}'.\n" |
| 952 |
f"The key '{duplicate_key}' already exists in the root user dict " |
| 953 |
f'and would be overwritten.' |
| 954 |
) |
| 955 |
raise ValueError(msg) |
| 956 |
|
| 957 |
if user_dict_mode == 'preserve': |
| 958 |
if check_duplicate_keys: |
| 959 |
# Check if the keys already exist before updating |
| 960 |
root_user_dict_keys = root_user_dict.keys() |
| 961 |
for nested_key in nested_multi.user_dict.keys(): |
| 962 |
if nested_key in root_user_dict_keys: |
| 963 |
raise_key_error(nested_key, block_name, index) |
| 964 |
root_user_dict.update(nested_multi.user_dict) |
| 965 |
else: |
| 966 |
# Remove prepended names |
| 967 |
new_key = ( |
| 968 |
block_name |
| 969 |
if user_dict_mode == 'prepend' |
| 970 |
else block_name.split(separator)[-1] |
| 971 |
) |
| 972 |
# Update the parent keys instead of the root keys if 'nested' |
| 973 |
if user_dict_mode == 'nested': |
| 974 |
parent, _ = self._navigate_to_parent(index) |
| 975 |
dict_to_update = parent.user_dict |
| 976 |
else: |
| 977 |
dict_to_update = root_user_dict |
| 978 |
|
| 979 |
if check_duplicate_keys: |
| 980 |
# Check if the keys already exist before updating |
| 981 |
if new_key in dict_to_update: |
| 982 |
raise_key_error(new_key, block_name, index) |
| 983 |
dict_to_update[new_key] = dict(nested_multi.user_dict) |
| 984 |
|
| 985 |
elif check_duplicate_keys and array_name in root_field_data: |
| 986 |
# Duplicate keys - raise error |
| 987 |
index_fmt = _format_nested_index(index) |
| 988 |
msg = ( |
| 989 |
f"The field data array '{array_name}' from nested MultiBlock " |
| 990 |
f"at index {index_fmt} with name '{block_name}'\n" |
| 991 |
f"also exists in the root MultiBlock's field data and cannot be moved." |
| 992 |
) |
| 993 |
if not prepend_names: |
| 994 |
msg += "\nUse `field_data_mode='prepend'` to make the array names unique." |
| 995 |
raise ValueError(msg) |
| 996 |
|
| 997 |
else: |
| 998 |
# Copy the field data |
| 999 |
array = field_data_to_copy[array_name] |
| 1000 |
# Remove prepended names |
| 1001 |
short_array_name = ( |
| 1002 |
array_name.split(separator)[-1] |
| 1003 |
if field_data_mode != 'prepend' |
| 1004 |
else array_name |
| 1005 |
) |
| 1006 |
root_field_data._update_array( |
| 1007 |
name=short_array_name, array=array, copy=bool(copy) |
| 1008 |
) |
| 1009 |
|
| 1010 |
if copy is None: |
| 1011 |
nested_field_data.clear() |
| 1012 |
|
| 1013 |
def flatten( |
| 1014 |
self, |
| 1015 |
*, |
| 1016 |
order: Literal['nested_first', 'nested_last'] | None = None, |
| 1017 |
name_mode: Literal['preserve', 'prepend', 'reset'] = 'preserve', |
| 1018 |
field_data_mode: Literal['preserve', 'prepend'] = 'preserve', |
| 1019 |
user_dict_mode: Literal['preserve', 'prepend', 'flat', 'nested'] = 'preserve', |
| 1020 |
separator: str = '::', |
| 1021 |
check_duplicate_keys: bool = True, |
| 1022 |
copy: bool = True, |
| 1023 |
) -> MultiBlock: |
| 1024 |
"""Flatten this :class:`MultiBlock`. |
| 1025 |
|
| 1026 |
Recursively iterate through all blocks and store them in a single |
| 1027 |
:class:`MultiBlock` instance. All nested :class:`~pyvista.DataSet` and ``None`` |
| 1028 |
blocks are preserved, and any nested ``MultiBlock`` container blocks are removed. |
| 1029 |
Field data from any nested ``MultiBlock`` containers is preserved, however, and |
| 1030 |
is also flattened. |
| 1031 |
|
| 1032 |
The flattening operation is "safe" by default in the sense that duplicate keys |
| 1033 |
for block names and field data are not allowed and no data will be overwritten. |
| 1034 |
|
| 1035 |
.. versionadded:: 0.45 |
| 1036 |
|
| 1037 |
Parameters |
| 1038 |
---------- |
| 1039 |
order : 'nested_last', 'nested_first', optional |
| 1040 |
Order in which to flatten the contents. |
| 1041 |
|
| 1042 |
- ``'nested_first'``: Flatten nested ``MultiBlock`` blocks first. |
| 1043 |
- ``'nested_last'``: Flatten nested ``MultiBlock`` blocks last. |
| 1044 |
|
| 1045 |
By default, the ``MultiBlock`` is flattened recursively as-is without |
| 1046 |
changing the order. |
| 1047 |
|
| 1048 |
name_mode : 'preserve' | 'prepend' | 'reset', default: 'preserve' |
| 1049 |
Mode for naming blocks in the flattened output. |
| 1050 |
|
| 1051 |
- ``'preserve'``: The names of all blocks are preserved. |
| 1052 |
- ``'prepend'``: Preserve the block names and prepend the parent names. |
| 1053 |
- ``'reset'``: Reset the block names to default values. |
| 1054 |
|
| 1055 |
field_data_mode : 'preserve' | 'prepend', default: 'preserve' |
| 1056 |
Mode for naming the root field data keys when flattening nested field data. |
| 1057 |
|
| 1058 |
- ``'preserve'``: The array names of nested field data are preserved. |
| 1059 |
- ``'prepend'``: Preserve the array names and prepend the parent names. |
| 1060 |
|
| 1061 |
user_dict_mode : 'preserve' | 'prepend' | 'flat' | 'nested', default: 'preserve' |
| 1062 |
Mode for naming the flattened :attr:`~pyvista.DataObject.user_dict` keys when |
| 1063 |
nested :class:`MultiBlock` blocks define a user-dict. |
| 1064 |
|
| 1065 |
- ``'preserve'``: Update the flattened user dict directly with the items of |
| 1066 |
any nested user-dict. |
| 1067 |
- ``'nested'``: Create nested keys in the flattened user-dict which match |
| 1068 |
the nested hierarchy of any nested ``MultiBlock`` blocks. |
| 1069 |
- ``'flat'``: Create a new key in the flattened user dict for each nested |
| 1070 |
``MultiBlock`` that has a user-dict. |
| 1071 |
- ``'prepend'``: Similar to ``'flat'`` except the key names are prepended |
| 1072 |
with the parent block names. |
| 1073 |
|
| 1074 |
.. note:: |
| 1075 |
If there is only a single level of nesting the ``'flat'``, ``'nested'`` |
| 1076 |
and ``'prepend'`` modes are all equivalent. They only differ when there |
| 1077 |
is at least two levels of nesting. |
| 1078 |
|
| 1079 |
separator : str, default: '::' |
| 1080 |
String separator to use when ``'prepend'`` mode is used. The separator |
| 1081 |
is inserted between parent and child block name or field data array names. |
| 1082 |
|
| 1083 |
check_duplicate_keys : bool, default: True |
| 1084 |
Flatten the MultiBlock data safely without overwriting any data or |
| 1085 |
duplicating block names. If ``True``, an error is raised if any duplicate, |
| 1086 |
non-unique field data keys or block names are identified. If ``False``, |
| 1087 |
nested field data is flattened without checking for duplicate keys and data |
| 1088 |
may be overwritten; the flattened MultiBlock may also have duplicate block |
| 1089 |
names. |
| 1090 |
|
| 1091 |
copy : bool, default: True |
| 1092 |
Return a deep copy of all nested blocks in the flattened ``MultiBlock``. |
| 1093 |
If ``False``, shallow copies are returned. |
| 1094 |
|
| 1095 |
Returns |
| 1096 |
------- |
| 1097 |
MultiBlock |
| 1098 |
Flattened ``MultiBlock``. |
| 1099 |
|
| 1100 |
See Also |
| 1101 |
-------- |
| 1102 |
recursive_iterator |
| 1103 |
move_nested_field_data_to_root |
| 1104 |
pyvista.CompositeFilters.generic_filter |
| 1105 |
clean |
| 1106 |
|
| 1107 |
Examples |
| 1108 |
-------- |
| 1109 |
Create a nested :class:`MultiBlock` with three levels of nesting and |
| 1110 |
three end nodes. |
| 1111 |
|
| 1112 |
>>> import pyvista as pv |
| 1113 |
>>> nested = pv.MultiBlock( |
| 1114 |
... { |
| 1115 |
... 'nested1': pv.MultiBlock( |
| 1116 |
... { |
| 1117 |
... 'nested2': pv.MultiBlock({'poly': pv.PolyData()}), |
| 1118 |
... 'image': pv.ImageData(), |
| 1119 |
... } |
| 1120 |
... ), |
| 1121 |
... 'none': None, |
| 1122 |
... } |
| 1123 |
... ) |
| 1124 |
|
| 1125 |
The root ``MultiBlock`` has two blocks. |
| 1126 |
|
| 1127 |
>>> nested.n_blocks |
| 1128 |
2 |
| 1129 |
|
| 1130 |
>>> type(nested[0]), type(nested[1]) |
| 1131 |
(<class 'pyvista.core.composite.MultiBlock'>, <class 'NoneType'>) |
| 1132 |
|
| 1133 |
Flatten the ``MultiBlock``. The nested ``MultiBlock`` containers are removed |
| 1134 |
and only their contents are returned (i.e. the three end nodes). |
| 1135 |
|
| 1136 |
>>> flat = nested.flatten() |
| 1137 |
>>> flat.n_blocks |
| 1138 |
3 |
| 1139 |
|
| 1140 |
>>> ( |
| 1141 |
... type(flat[0]), |
| 1142 |
... type(flat[1]), |
| 1143 |
... type(flat[2]), |
| 1144 |
... ) # doctest: +NORMALIZE_WHITESPACE |
| 1145 |
(<class 'pyvista.core.pointset.PolyData'>, |
| 1146 |
<class 'pyvista.core.grid.ImageData'>, |
| 1147 |
<class 'NoneType'>) |
| 1148 |
|
| 1149 |
By default, the block names are preserved. |
| 1150 |
|
| 1151 |
>>> flat.keys() |
| 1152 |
['poly', 'image', 'none'] |
| 1153 |
|
| 1154 |
Prepend the names of parent blocks to the names instead. |
| 1155 |
|
| 1156 |
>>> flat = nested.flatten(name_mode='prepend') |
| 1157 |
>>> flat.keys() |
| 1158 |
['nested1::nested2::poly', 'nested1::image', 'none'] |
| 1159 |
|
| 1160 |
Reset the names to default values instead. |
| 1161 |
|
| 1162 |
>>> flat = nested.flatten(name_mode='reset') |
| 1163 |
>>> flat.keys() |
| 1164 |
['Block-00', 'Block-01', 'Block-02'] |
| 1165 |
|
| 1166 |
Flatten the ``MultiBlock`` with nested multi-blocks flattened last. Note the difference |
| 1167 |
between this ordering of blocks and the default ordering returned earlier. |
| 1168 |
|
| 1169 |
>>> flat = nested.flatten(order='nested_last') |
| 1170 |
>>> ( |
| 1171 |
... type(flat[0]), |
| 1172 |
... type(flat[1]), |
| 1173 |
... type(flat[2]), |
| 1174 |
... ) # doctest: +NORMALIZE_WHITESPACE |
| 1175 |
(<class 'NoneType'>, |
| 1176 |
<class 'pyvista.core.grid.ImageData'>, |
| 1177 |
<class 'pyvista.core.pointset.PolyData'>) |
| 1178 |
|
| 1179 |
""" |
| 1180 |
_validation.check_contains( |
| 1181 |
['preserve', 'prepend', 'reset'], must_contain=name_mode, name='name_mode' |
| 1182 |
) |
| 1183 |
prepend_names = name_mode == 'prepend' |
| 1184 |
|
| 1185 |
if copy: |
| 1186 |
input_multi = self.copy() |
| 1187 |
else: |
| 1188 |
# Shallow copy nested multiblocks to avoid mutating input field data |
| 1189 |
input_multi = MultiBlock() |
| 1190 |
input_multi.shallow_copy(self, recursive=True) |
| 1191 |
|
| 1192 |
# Move field data to output |
| 1193 |
output_multi = MultiBlock() |
| 1194 |
input_multi.move_nested_field_data_to_root( |
| 1195 |
field_data_mode=field_data_mode, |
| 1196 |
user_dict_mode=user_dict_mode, |
| 1197 |
check_duplicate_keys=check_duplicate_keys, |
| 1198 |
separator=separator, |
| 1199 |
) |
| 1200 |
output_multi.field_data.update(input_multi.field_data, copy=copy) |
| 1201 |
|
| 1202 |
# Create iterator |
| 1203 |
iterator = input_multi.recursive_iterator( |
| 1204 |
contents='all', |
| 1205 |
order=order, |
| 1206 |
skip_none=False, |
| 1207 |
skip_empty=False, |
| 1208 |
prepend_names=prepend_names, |
| 1209 |
separator=separator, |
| 1210 |
) |
| 1211 |
|
| 1212 |
# Append blocks to output |
| 1213 |
reset_name = name_mode == 'reset' |
| 1214 |
for index, name, block in iterator: |
| 1215 |
if not reset_name and check_duplicate_keys: |
| 1216 |
if name in output_multi.keys(): |
| 1217 |
# Duplicate block name - raise error |
| 1218 |
index_fmt = _format_nested_index(index) |
| 1219 |
msg = ( |
| 1220 |
f"Block at index {index_fmt} with name '{name}' " |
| 1221 |
f'cannot be flattened. Another block \n' |
| 1222 |
'with the same name already exists. ' |
| 1223 |
"Use `name_mode='reset'` or `check_duplicate_keys=False`." |
| 1224 |
) |
| 1225 |
raise ValueError(msg) |
| 1226 |
output_multi.append(block, None if reset_name else name) |
| 1227 |
return output_multi |
| 1228 |
|
| 1229 |
@property |
| 1230 |
def is_nested(self) -> bool: # numpydoc ignore=RT01 |
| 1231 |
"""Return ``True`` if any blocks are a :class:`MultiBlock`. |
| 1232 |
|
| 1233 |
.. versionadded:: 0.45 |
| 1234 |
|
| 1235 |
Examples |
| 1236 |
-------- |
| 1237 |
Create a simple :class:`MultiBlock`: |
| 1238 |
|
| 1239 |
>>> import pyvista as pv |
| 1240 |
>>> multi = pv.MultiBlock([pv.Sphere()]) |
| 1241 |
|
| 1242 |
It only contains a :class:`~pyvista.DataSet`, so it is not nested. |
| 1243 |
|
| 1244 |
>>> multi.is_nested |
| 1245 |
False |
| 1246 |
|
| 1247 |
Nest it inside another MultiBlock. |
| 1248 |
|
| 1249 |
>>> nested = pv.MultiBlock([multi]) |
| 1250 |
>>> nested.is_nested |
| 1251 |
True |
| 1252 |
|
| 1253 |
""" |
| 1254 |
return any(isinstance(block, pv.MultiBlock) for block in self) |
| 1255 |
|
| 1256 |
@property |
| 1257 |
def is_empty(self) -> bool: # numpydoc ignore=RT01 |
| 1258 |
"""Return ``True`` if there are no blocks. |
| 1259 |
|
| 1260 |
.. versionadded:: 0.45 |
| 1261 |
|
| 1262 |
Examples |
| 1263 |
-------- |
| 1264 |
>>> import pyvista as pv |
| 1265 |
>>> mesh = pv.MultiBlock() |
| 1266 |
>>> mesh.is_empty |
| 1267 |
True |
| 1268 |
|
| 1269 |
>>> mesh.append(pv.Sphere()) |
| 1270 |
>>> mesh.is_empty |
| 1271 |
False |
| 1272 |
|
| 1273 |
""" |
| 1274 |
return self.n_blocks == 0 |
| 1275 |
|
| 1276 |
@property |
| 1277 |
def bounds(self: MultiBlock) -> BoundsTuple: |
| 1278 |
"""Find min/max for bounds across blocks. |
| 1279 |
|
| 1280 |
Returns |
| 1281 |
------- |
| 1282 |
tuple[float, float, float, float, float, float] |
| 1283 |
Length 6 tuple of floats containing min/max along each axis. |
| 1284 |
|
| 1285 |
Examples |
| 1286 |
-------- |
| 1287 |
Return the bounds across blocks. |
| 1288 |
|
| 1289 |
>>> import pyvista as pv |
| 1290 |
>>> data = [ |
| 1291 |
... pv.Sphere(center=(2, 0, 0)), |
| 1292 |
... pv.Cube(center=(0, 2, 0)), |
| 1293 |
... pv.Cone(), |
| 1294 |
... ] |
| 1295 |
>>> blocks = pv.MultiBlock(data) |
| 1296 |
>>> blocks.bounds |
| 1297 |
BoundsTuple(x_min = -0.5, |
| 1298 |
x_max = 2.5, |
| 1299 |
y_min = -0.5, |
| 1300 |
y_max = 2.5, |
| 1301 |
z_min = -0.5, |
| 1302 |
z_max = 0.5) |
| 1303 |
|
| 1304 |
""" |
| 1305 |
# apply reduction of min and max over each block |
| 1306 |
# (typing.cast necessary to make mypy happy with ufunc.reduce() later) |
| 1307 |
all_bounds = [cast('list[float]', block.bounds) for block in self if block] |
| 1308 |
# edge case where block has no bounds |
| 1309 |
if not all_bounds: # pragma: no cover |
| 1310 |
minima = (0.0, 0.0, 0.0) |
| 1311 |
maxima = (0.0, 0.0, 0.0) |
| 1312 |
else: |
| 1313 |
minima = np.minimum.reduce(all_bounds)[::2].tolist() |
| 1314 |
maxima = np.maximum.reduce(all_bounds)[1::2].tolist() |
| 1315 |
|
| 1316 |
# interleave minima and maxima for bounds |
| 1317 |
return BoundsTuple(minima[0], maxima[0], minima[1], maxima[1], minima[2], maxima[2]) |
| 1318 |
|
| 1319 |
@property |
| 1320 |
def center(self: MultiBlock) -> tuple[float, float, float]: |
| 1321 |
"""Set or return the center of the bounding box. |
| 1322 |
|
| 1323 |
.. versionchanged:: 0.47 |
| 1324 |
Center can now be set. |
| 1325 |
|
| 1326 |
Returns |
| 1327 |
------- |
| 1328 |
tuple[float, float, float] |
| 1329 |
Center of the bounding box. |
| 1330 |
|
| 1331 |
Examples |
| 1332 |
-------- |
| 1333 |
>>> import pyvista as pv |
| 1334 |
>>> data = [ |
| 1335 |
... pv.Sphere(center=(2, 0, 0)), |
| 1336 |
... pv.Cube(center=(0, 2, 0)), |
| 1337 |
... pv.Cone(), |
| 1338 |
... ] |
| 1339 |
>>> blocks = pv.MultiBlock(data) |
| 1340 |
>>> blocks.center # doctest:+SKIP |
| 1341 |
array([1., 1., 0.]) |
| 1342 |
|
| 1343 |
""" |
| 1344 |
return tuple(np.reshape(self.bounds, (3, 2)).mean(axis=1).tolist()) |
| 1345 |
|
| 1346 |
@center.setter |
| 1347 |
def center(self, center: VectorLike[float]) -> None: |
| 1348 |
valid_center = _validation.validate_array3(center, name='center') |
| 1349 |
self.translate(valid_center - self.center, inplace=True) |
| 1350 |
|
| 1351 |
@property |
| 1352 |
def length(self: MultiBlock) -> float: |
| 1353 |
"""Return the length of the diagonal of the bounding box. |
| 1354 |
|
| 1355 |
Returns |
| 1356 |
------- |
| 1357 |
float |
| 1358 |
Length of the diagonal of the bounding box. |
| 1359 |
|
| 1360 |
Examples |
| 1361 |
-------- |
| 1362 |
>>> import pyvista as pv |
| 1363 |
>>> data = [ |
| 1364 |
... pv.Sphere(center=(2, 0, 0)), |
| 1365 |
... pv.Cube(center=(0, 2, 0)), |
| 1366 |
... pv.Cone(), |
| 1367 |
... ] |
| 1368 |
>>> blocks = pv.MultiBlock(data) |
| 1369 |
>>> blocks.length |
| 1370 |
4.3584 |
| 1371 |
|
| 1372 |
""" |
| 1373 |
return Box(self.bounds).length |
| 1374 |
|
| 1375 |
@property |
| 1376 |
def n_blocks(self: MultiBlock) -> int: |
| 1377 |
"""Return the total number of blocks set. |
| 1378 |
|
| 1379 |
Returns |
| 1380 |
------- |
| 1381 |
int |
| 1382 |
Total number of blocks set. |
| 1383 |
|
| 1384 |
Examples |
| 1385 |
-------- |
| 1386 |
>>> import pyvista as pv |
| 1387 |
>>> data = [ |
| 1388 |
... pv.Sphere(center=(2, 0, 0)), |
| 1389 |
... pv.Cube(center=(0, 2, 0)), |
| 1390 |
... pv.Cone(), |
| 1391 |
... ] |
| 1392 |
>>> blocks = pv.MultiBlock(data) |
| 1393 |
>>> blocks.n_blocks |
| 1394 |
3 |
| 1395 |
|
| 1396 |
""" |
| 1397 |
return self.GetNumberOfBlocks() |
| 1398 |
|
| 1399 |
@n_blocks.setter |
| 1400 |
def n_blocks(self: MultiBlock, n: int) -> None: |
| 1401 |
"""Change the total number of blocks set. |
| 1402 |
|
| 1403 |
Parameters |
| 1404 |
---------- |
| 1405 |
n : int |
| 1406 |
The total number of blocks set. |
| 1407 |
|
| 1408 |
""" |
| 1409 |
self.SetNumberOfBlocks(n) |
| 1410 |
self.Modified() |
| 1411 |
|
| 1412 |
@property |
| 1413 |
def volume(self: MultiBlock) -> float: |
| 1414 |
"""Return the total volume of all meshes in this dataset. |
| 1415 |
|
| 1416 |
Returns |
| 1417 |
------- |
| 1418 |
float |
| 1419 |
Total volume of the mesh. |
| 1420 |
|
| 1421 |
Examples |
| 1422 |
-------- |
| 1423 |
>>> import pyvista as pv |
| 1424 |
>>> data = [ |
| 1425 |
... pv.Sphere(center=(2, 0, 0)), |
| 1426 |
... pv.Cube(center=(0, 2, 0)), |
| 1427 |
... pv.Cone(), |
| 1428 |
... ] |
| 1429 |
>>> blocks = pv.MultiBlock(data) |
| 1430 |
>>> blocks.volume |
| 1431 |
1.7348 |
| 1432 |
|
| 1433 |
""" |
| 1434 |
return sum(block.volume for block in self if block) |
| 1435 |
|
| 1436 |
@_deprecate_positional_args(allowed=['name']) |
| 1437 |
def get_data_range( # type: ignore[override] |
| 1438 |
self: MultiBlock, |
| 1439 |
name: str | None, |
| 1440 |
allow_missing: bool = False, # noqa: FBT001, FBT002 |
| 1441 |
preference: PointLiteral | CellLiteral | FieldLiteral = 'cell', |
| 1442 |
) -> tuple[float, float]: |
| 1443 |
"""Get the min/max of an array given its name across all blocks. |
| 1444 |
|
| 1445 |
Parameters |
| 1446 |
---------- |
| 1447 |
name : str, optional |
| 1448 |
The name of the array to get the range. If ``None``, the |
| 1449 |
active scalars are used. |
| 1450 |
|
| 1451 |
allow_missing : bool, default: False |
| 1452 |
Allow a block to be missing the named array. |
| 1453 |
|
| 1454 |
preference : str, default: "cell" |
| 1455 |
When scalars is specified, this is the preferred array type |
| 1456 |
to search for in the dataset. Must be either ``'point'``, |
| 1457 |
``'cell'``, or ``'field'``. |
| 1458 |
|
| 1459 |
.. versionadded:: 0.45 |
| 1460 |
|
| 1461 |
Returns |
| 1462 |
------- |
| 1463 |
tuple |
| 1464 |
``(min, max)`` of the named array. |
| 1465 |
|
| 1466 |
""" |
| 1467 |
mini, maxi = np.inf, -np.inf |
| 1468 |
for i in range(self.n_blocks): |
| 1469 |
data = self[i] |
| 1470 |
if data is None: |
| 1471 |
continue |
| 1472 |
# get the scalars if available - recursive |
| 1473 |
try: |
| 1474 |
tmi, tma = data.get_data_range(name, preference=preference) |
| 1475 |
except KeyError: |
| 1476 |
if allow_missing: |
| 1477 |
continue |
| 1478 |
else: |
| 1479 |
raise |
| 1480 |
if not np.isnan(tmi) and tmi < mini: |
| 1481 |
mini = tmi |
| 1482 |
if not np.isnan(tma) and tma > maxi: |
| 1483 |
maxi = tma |
| 1484 |
return mini, maxi |
| 1485 |
|
| 1486 |
def get_index_by_name(self: MultiBlock, name: str) -> int: |
| 1487 |
"""Find the index number by block name. |
| 1488 |
|
| 1489 |
Parameters |
| 1490 |
---------- |
| 1491 |
name : str |
| 1492 |
Name of the block. |
| 1493 |
|
| 1494 |
Returns |
| 1495 |
------- |
| 1496 |
int |
| 1497 |
Index of the block. |
| 1498 |
|
| 1499 |
Examples |
| 1500 |
-------- |
| 1501 |
>>> import pyvista as pv |
| 1502 |
>>> data = { |
| 1503 |
... 'cube': pv.Cube(), |
| 1504 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1505 |
... } |
| 1506 |
>>> blocks = pv.MultiBlock(data) |
| 1507 |
>>> blocks.get_index_by_name('sphere') |
| 1508 |
1 |
| 1509 |
|
| 1510 |
""" |
| 1511 |
for i in range(self.n_blocks): |
| 1512 |
if self.get_block_name(i) == name: |
| 1513 |
return i |
| 1514 |
msg = f'Block name ({name}) not found' |
| 1515 |
raise KeyError(msg) |
| 1516 |
|
| 1517 |
@overload |
| 1518 |
def __getitem__( |
| 1519 |
self: MultiBlock, |
| 1520 |
index: int | str, |
| 1521 |
) -> _TypeMultiBlockLeaf: ... # pragma: no cover |
| 1522 |
|
| 1523 |
@overload |
| 1524 |
def __getitem__(self: MultiBlock, index: slice) -> MultiBlock: ... # pragma: no cover |
| 1525 |
|
| 1526 |
def __getitem__(self: MultiBlock, index): |
| 1527 |
"""Get a block by its index or name. |
| 1528 |
|
| 1529 |
If the name is non-unique then returns the first occurrence. |
| 1530 |
|
| 1531 |
""" |
| 1532 |
if isinstance(index, slice): |
| 1533 |
multi = MultiBlock() |
| 1534 |
for i in range(self.n_blocks)[index]: |
| 1535 |
multi.append(self[i], self.get_block_name(i)) |
| 1536 |
return multi |
| 1537 |
elif isinstance(index, str): |
| 1538 |
index = self.get_index_by_name(index) |
| 1539 |
############################ |
| 1540 |
if index < -self.n_blocks or index >= self.n_blocks: |
| 1541 |
msg = f'index ({index}) out of range for this dataset.' |
| 1542 |
raise IndexError(msg) |
| 1543 |
if index < 0: |
| 1544 |
index = self.n_blocks + index |
| 1545 |
|
| 1546 |
return wrap(self.GetBlock(index)) |
| 1547 |
|
| 1548 |
def append(self: MultiBlock, dataset: _TypeMultiBlockLeaf, name: str | None = None) -> None: |
| 1549 |
"""Add a data set to the next block index. |
| 1550 |
|
| 1551 |
Parameters |
| 1552 |
---------- |
| 1553 |
dataset : pyvista.DataSet or pyvista.MultiBlock |
| 1554 |
Dataset to append to this multi-block. |
| 1555 |
|
| 1556 |
name : str, optional |
| 1557 |
Block name to give to dataset. A default name is given |
| 1558 |
depending on the block index as ``'Block-{i:02}'``. |
| 1559 |
|
| 1560 |
Examples |
| 1561 |
-------- |
| 1562 |
>>> import pyvista as pv |
| 1563 |
>>> from pyvista import examples |
| 1564 |
>>> data = { |
| 1565 |
... 'cube': pv.Cube(), |
| 1566 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1567 |
... } |
| 1568 |
>>> blocks = pv.MultiBlock(data) |
| 1569 |
>>> blocks.append(pv.Cone()) |
| 1570 |
>>> len(blocks) |
| 1571 |
3 |
| 1572 |
>>> blocks.append(examples.load_uniform(), 'uniform') |
| 1573 |
>>> blocks.keys() |
| 1574 |
['cube', 'sphere', 'Block-02', 'uniform'] |
| 1575 |
|
| 1576 |
""" |
| 1577 |
# do not allow to add self |
| 1578 |
if dataset is self: |
| 1579 |
msg = 'Cannot nest a composite dataset in itself.' |
| 1580 |
raise ValueError(msg) |
| 1581 |
|
| 1582 |
index = self.n_blocks # note off by one so use as index |
| 1583 |
# always wrap since we may need to reference the VTK memory address |
| 1584 |
wrapped = wrap(dataset) |
| 1585 |
if isinstance(wrapped, pyvista_ndarray): |
| 1586 |
msg = 'dataset should not be or contain an array' # type: ignore[unreachable] |
| 1587 |
raise TypeError(msg) |
| 1588 |
dataset = wrapped |
| 1589 |
self.n_blocks += 1 |
| 1590 |
self[index] = dataset |
| 1591 |
# No overwrite if name is None |
| 1592 |
self.set_block_name(index, name) |
| 1593 |
|
| 1594 |
def extend(self: MultiBlock, datasets: Iterable[_TypeMultiBlockLeaf]) -> None: |
| 1595 |
"""Extend MultiBlock with an Iterable. |
| 1596 |
|
| 1597 |
If another MultiBlock object is supplied, the key names will |
| 1598 |
be preserved. |
| 1599 |
|
| 1600 |
Parameters |
| 1601 |
---------- |
| 1602 |
datasets : Iterable[pyvista.DataSet or pyvista.MultiBlock] |
| 1603 |
Datasets to extend. |
| 1604 |
|
| 1605 |
Examples |
| 1606 |
-------- |
| 1607 |
>>> import pyvista as pv |
| 1608 |
>>> from pyvista import examples |
| 1609 |
>>> data = { |
| 1610 |
... 'cube': pv.Cube(), |
| 1611 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1612 |
... } |
| 1613 |
>>> blocks = pv.MultiBlock(data) |
| 1614 |
>>> blocks_uniform = pv.MultiBlock({'uniform': examples.load_uniform()}) |
| 1615 |
>>> blocks.extend(blocks_uniform) |
| 1616 |
>>> len(blocks) |
| 1617 |
3 |
| 1618 |
>>> blocks.keys() |
| 1619 |
['cube', 'sphere', 'uniform'] |
| 1620 |
|
| 1621 |
""" |
| 1622 |
# Code based on collections.abc |
| 1623 |
if isinstance(datasets, MultiBlock): |
| 1624 |
for key, data in zip(datasets.keys(), datasets, strict=True): |
| 1625 |
self.append(data, key) |
| 1626 |
else: |
| 1627 |
for v in datasets: |
| 1628 |
self.append(v) |
| 1629 |
|
| 1630 |
def get( |
| 1631 |
self: MultiBlock, |
| 1632 |
index: int | str, |
| 1633 |
default: _TypeMultiBlockLeaf = None, |
| 1634 |
) -> _TypeMultiBlockLeaf: |
| 1635 |
"""Get a block by its index or name. |
| 1636 |
|
| 1637 |
If the name is non-unique then returns the first occurrence. |
| 1638 |
Returns ``default`` if name isn't in the dataset. |
| 1639 |
|
| 1640 |
Parameters |
| 1641 |
---------- |
| 1642 |
index : int | str |
| 1643 |
Index or name of the dataset within the multiblock. |
| 1644 |
|
| 1645 |
default : pyvista.DataSet or pyvista.MultiBlock, optional |
| 1646 |
Default to return if index is not in the multiblock. |
| 1647 |
|
| 1648 |
Returns |
| 1649 |
------- |
| 1650 |
output : pyvista.DataSet | pyvista.MultiBlock | None |
| 1651 |
Dataset from the given index if it exists. |
| 1652 |
|
| 1653 |
See Also |
| 1654 |
-------- |
| 1655 |
get_block |
| 1656 |
Get a block and raise an ``IndexError`` if index is not found. |
| 1657 |
|
| 1658 |
Examples |
| 1659 |
-------- |
| 1660 |
>>> import pyvista as pv |
| 1661 |
>>> from pyvista import examples |
| 1662 |
>>> data = {'poly': pv.PolyData(), 'img': pv.ImageData()} |
| 1663 |
>>> blocks = pv.MultiBlock(data) |
| 1664 |
>>> blocks.get('poly') |
| 1665 |
PolyData ... |
| 1666 |
>>> blocks.get('cone') |
| 1667 |
|
| 1668 |
""" |
| 1669 |
try: |
| 1670 |
return self[index] |
| 1671 |
except KeyError: |
| 1672 |
return default |
| 1673 |
|
| 1674 |
def get_block( |
| 1675 |
self: MultiBlock, |
| 1676 |
index: int | Sequence[int] | str, |
| 1677 |
) -> _TypeMultiBlockLeaf: |
| 1678 |
"""Get a block by its index or name. |
| 1679 |
|
| 1680 |
If the name is non-unique then returns the first occurrence. This |
| 1681 |
method is similar to using ``[]`` for indexing except this method also |
| 1682 |
supports indexing nested blocks. |
| 1683 |
|
| 1684 |
.. versionadded:: 0.45 |
| 1685 |
|
| 1686 |
Parameters |
| 1687 |
---------- |
| 1688 |
index : int | Sequence[int] | str |
| 1689 |
Index or name of the dataset within the multiblock. Specify a sequence of |
| 1690 |
indices to replace a nested block. |
| 1691 |
|
| 1692 |
Returns |
| 1693 |
------- |
| 1694 |
output : pyvista.DataSet | pyvista.MultiBlock | None |
| 1695 |
Dataset from the given index if it exists. |
| 1696 |
|
| 1697 |
See Also |
| 1698 |
-------- |
| 1699 |
get |
| 1700 |
Get a block and return a default value instead of raising an ``IndexError``. |
| 1701 |
|
| 1702 |
Examples |
| 1703 |
-------- |
| 1704 |
>>> import pyvista as pv |
| 1705 |
>>> blocks = pv.MultiBlock([pv.PolyData(), pv.ImageData()]) |
| 1706 |
>>> nested = pv.MultiBlock([blocks]) |
| 1707 |
|
| 1708 |
>>> nested.get_block(0) |
| 1709 |
MultiBlock ... |
| 1710 |
>>> nested.get_block((0, 1)) |
| 1711 |
ImageData ... |
| 1712 |
|
| 1713 |
""" |
| 1714 |
if isinstance(index, Sequence) and not isinstance(index, str): |
| 1715 |
parent, final_index = self._navigate_to_parent(index) |
| 1716 |
return parent[final_index] |
| 1717 |
return self[index] |
| 1718 |
|
| 1719 |
def set_block_name(self: MultiBlock, index: int | str, name: str | None) -> None: |
| 1720 |
"""Set a block's string name at the specified index. |
| 1721 |
|
| 1722 |
Parameters |
| 1723 |
---------- |
| 1724 |
index : int | str |
| 1725 |
Index or the dataset within the multiblock. |
| 1726 |
|
| 1727 |
.. versionadded:: 0.45 |
| 1728 |
|
| 1729 |
Allow indexing by name. |
| 1730 |
|
| 1731 |
name : str, optional |
| 1732 |
Name to assign to the block at ``index``. If ``None``, no name is |
| 1733 |
assigned to the block. |
| 1734 |
|
| 1735 |
Examples |
| 1736 |
-------- |
| 1737 |
>>> import pyvista as pv |
| 1738 |
>>> data = { |
| 1739 |
... 'cube': pv.Cube(), |
| 1740 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1741 |
... } |
| 1742 |
>>> blocks = pv.MultiBlock(data) |
| 1743 |
>>> blocks.append(pv.Cone()) |
| 1744 |
>>> blocks.set_block_name(2, 'cone') |
| 1745 |
>>> blocks.keys() |
| 1746 |
['cube', 'sphere', 'cone'] |
| 1747 |
|
| 1748 |
""" |
| 1749 |
if name is None: |
| 1750 |
return |
| 1751 |
index = ( |
| 1752 |
self.get_index_by_name(index) |
| 1753 |
if isinstance(index, str) |
| 1754 |
else range(self.n_blocks)[index] |
| 1755 |
) |
| 1756 |
self.GetMetaData(index).Set(_vtk.vtkCompositeDataSet.NAME(), name) |
| 1757 |
self.Modified() |
| 1758 |
|
| 1759 |
def get_block_name(self: MultiBlock, index: int) -> str: |
| 1760 |
"""Return the string name of the block at the given index. |
| 1761 |
|
| 1762 |
Parameters |
| 1763 |
---------- |
| 1764 |
index : int |
| 1765 |
Index of the block to get the name of. |
| 1766 |
|
| 1767 |
Returns |
| 1768 |
------- |
| 1769 |
str |
| 1770 |
Name of the block at the given index. |
| 1771 |
|
| 1772 |
Examples |
| 1773 |
-------- |
| 1774 |
>>> import pyvista as pv |
| 1775 |
>>> data = { |
| 1776 |
... 'cube': pv.Cube(), |
| 1777 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1778 |
... } |
| 1779 |
>>> blocks = pv.MultiBlock(data) |
| 1780 |
>>> blocks.get_block_name(0) |
| 1781 |
'cube' |
| 1782 |
|
| 1783 |
""" |
| 1784 |
index = range(self.n_blocks)[index] |
| 1785 |
# Safely cast as vtkInformation since `None` case is caught by IndexError above |
| 1786 |
meta = cast('_vtk.vtkInformation', self.GetMetaData(index)) |
| 1787 |
return meta.Get(_vtk.vtkCompositeDataSet.NAME()) # type:ignore[return-value] |
| 1788 |
|
| 1789 |
def keys(self: MultiBlock) -> list[str]: |
| 1790 |
"""Get all the block names in the dataset. |
| 1791 |
|
| 1792 |
Returns |
| 1793 |
------- |
| 1794 |
list |
| 1795 |
List of block names. |
| 1796 |
|
| 1797 |
Examples |
| 1798 |
-------- |
| 1799 |
>>> import pyvista as pv |
| 1800 |
>>> data = { |
| 1801 |
... 'cube': pv.Cube(), |
| 1802 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1803 |
... } |
| 1804 |
>>> blocks = pv.MultiBlock(data) |
| 1805 |
>>> blocks.keys() |
| 1806 |
['cube', 'sphere'] |
| 1807 |
|
| 1808 |
""" |
| 1809 |
return [self.get_block_name(i) for i in range(self.n_blocks)] |
| 1810 |
|
| 1811 |
def _ipython_key_completions_(self: MultiBlock) -> list[str]: |
| 1812 |
return self.keys() |
| 1813 |
|
| 1814 |
def replace( |
| 1815 |
self: MultiBlock, index: int | Sequence[int] | str, dataset: _TypeMultiBlockLeaf |
| 1816 |
) -> None: |
| 1817 |
"""Replace dataset at index while preserving key name. |
| 1818 |
|
| 1819 |
Parameters |
| 1820 |
---------- |
| 1821 |
index : int | Sequence[int] | str |
| 1822 |
Index or name of the block to replace. Specify a sequence of indices to replace |
| 1823 |
a nested block. |
| 1824 |
|
| 1825 |
.. versionadded:: 0.45 |
| 1826 |
|
| 1827 |
Allow indexing nested blocks. |
| 1828 |
|
| 1829 |
dataset : pyvista.DataSet or pyvista.MultiBlock |
| 1830 |
Dataset for replacing the one at index. |
| 1831 |
|
| 1832 |
Examples |
| 1833 |
-------- |
| 1834 |
>>> import pyvista as pv |
| 1835 |
>>> from pyvista import examples |
| 1836 |
>>> import numpy as np |
| 1837 |
>>> data = { |
| 1838 |
... 'cube': pv.Cube(), |
| 1839 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 1840 |
... } |
| 1841 |
>>> blocks = pv.MultiBlock(data) |
| 1842 |
>>> blocks.replace(1, pv.Sphere(center=(10, 10, 10))) |
| 1843 |
>>> blocks.keys() |
| 1844 |
['cube', 'sphere'] |
| 1845 |
>>> np.allclose(blocks[1].center, [10.0, 10.0, 10.0]) |
| 1846 |
True |
| 1847 |
|
| 1848 |
Load a dataset with nested blocks. |
| 1849 |
|
| 1850 |
>>> multi = examples.download_cgns_multi() |
| 1851 |
|
| 1852 |
Get one of the blocks and extract its surface. |
| 1853 |
|
| 1854 |
>>> block = multi[0][3] |
| 1855 |
>>> surface = block.extract_surface(algorithm=None) |
| 1856 |
|
| 1857 |
Replace the block. |
| 1858 |
|
| 1859 |
>>> multi.replace((0, 3), surface) |
| 1860 |
|
| 1861 |
This is similar to replacing the block directly with indexing but the block |
| 1862 |
name is also preserved. |
| 1863 |
|
| 1864 |
>>> multi[0][3] = surface |
| 1865 |
|
| 1866 |
""" |
| 1867 |
if isinstance(index, Sequence) and not isinstance(index, str): |
| 1868 |
parent, final_index = self._navigate_to_parent(index) |
| 1869 |
parent.replace(final_index, dataset) |
| 1870 |
return |
| 1871 |
name = index if isinstance(index, str) else self.get_block_name(index) |
| 1872 |
self[index] = dataset |
| 1873 |
self.set_block_name(index, name) |
| 1874 |
return |
| 1875 |
|
| 1876 |
def _navigate_to_parent(self, indices: Sequence[int]) -> tuple[MultiBlock, int]: |
| 1877 |
"""Navigate to the parent MultiBlock and return (parent, final_index).""" |
| 1878 |
_validation.check_length(indices, min_length=1, name='index') |
| 1879 |
# Navigate through the indices except the last one |
| 1880 |
target: _TypeMultiBlockLeaf = self |
| 1881 |
for ind in indices[:-1]: |
| 1882 |
if target is None or isinstance(target, pv.DataSet): |
| 1883 |
msg = f'Invalid indices {indices}.' |
| 1884 |
raise IndexError(msg) |
| 1885 |
target = target[ind] |
| 1886 |
if not isinstance(target, MultiBlock): |
| 1887 |
msg = f'Invalid indices {indices}.' |
| 1888 |
raise IndexError(msg) |
| 1889 |
return target, indices[-1] |
| 1890 |
|
| 1891 |
@overload |
| 1892 |
def __setitem__( |
| 1893 |
self: MultiBlock, |
| 1894 |
index: int | str, |
| 1895 |
data: _TypeMultiBlockLeaf, |
| 1896 |
) -> None: ... # pragma: no cover |
| 1897 |
|
| 1898 |
@overload |
| 1899 |
def __setitem__( |
| 1900 |
self: MultiBlock, |
| 1901 |
index: slice, |
| 1902 |
data: Iterable[_TypeMultiBlockLeaf], |
| 1903 |
) -> None: ... # pragma: no cover |
| 1904 |
|
| 1905 |
def __setitem__( |
| 1906 |
self: MultiBlock, |
| 1907 |
index: int | str | slice, |
| 1908 |
data, |
| 1909 |
) -> None: |
| 1910 |
"""Set a block with a VTK data object. |
| 1911 |
|
| 1912 |
To set the name simultaneously, pass a string name as the 2nd index. |
| 1913 |
|
| 1914 |
Examples |
| 1915 |
-------- |
| 1916 |
>>> import pyvista as pv |
| 1917 |
>>> multi = pv.MultiBlock() |
| 1918 |
>>> multi.append(pv.PolyData()) |
| 1919 |
>>> multi[0] = pv.UnstructuredGrid() |
| 1920 |
>>> multi.append(pv.PolyData(), 'poly') |
| 1921 |
>>> multi.keys() |
| 1922 |
['Block-00', 'poly'] |
| 1923 |
>>> multi['bar'] = pv.PolyData() |
| 1924 |
>>> multi.n_blocks |
| 1925 |
3 |
| 1926 |
|
| 1927 |
""" |
| 1928 |
i: int = 0 |
| 1929 |
name: str | None = None |
| 1930 |
if isinstance(index, str): |
| 1931 |
try: |
| 1932 |
i = self.get_index_by_name(index) |
| 1933 |
except KeyError: |
| 1934 |
self.append(data, index) |
| 1935 |
return |
| 1936 |
name = index |
| 1937 |
elif isinstance(index, slice): |
| 1938 |
index_iter = range(self.n_blocks)[index] |
| 1939 |
for i, (idx, d) in enumerate(itertools.zip_longest(index_iter, data)): |
| 1940 |
if idx is None: |
| 1941 |
self.insert( |
| 1942 |
index_iter[-1] + 1 + (i - len(index_iter)), |
| 1943 |
d, |
| 1944 |
) # insert after last entry, increasing |
| 1945 |
elif d is None: |
| 1946 |
del self[index_iter[-1] + 1] # delete next entry |
| 1947 |
else: |
| 1948 |
self[idx] = d |
| 1949 |
return |
| 1950 |
else: |
| 1951 |
i = index |
| 1952 |
|
| 1953 |
# data, i, and name are a single value now |
| 1954 |
data = cast('DataSet', wrap(data)) |
| 1955 |
|
| 1956 |
i = range(self.n_blocks)[i] |
| 1957 |
|
| 1958 |
# this is the only spot in the class where we actually add |
| 1959 |
# data to the MultiBlock |
| 1960 |
|
| 1961 |
# check if we are overwriting a block |
| 1962 |
existing_dataset = self.GetBlock(i) |
| 1963 |
if existing_dataset is not None: |
| 1964 |
self._remove_ref(i) |
| 1965 |
self.SetBlock(i, data) |
| 1966 |
if data is not None: |
| 1967 |
self._refs[data.memory_address] = data |
| 1968 |
|
| 1969 |
if name is None: |
| 1970 |
name = f'Block-{i:02}' |
| 1971 |
self.set_block_name(i, name) # Note that this calls self.Modified() |
| 1972 |
|
| 1973 |
def __delitem__(self: MultiBlock, index: int | str | slice) -> None: |
| 1974 |
"""Remove a block at the specified index.""" |
| 1975 |
if isinstance(index, slice): |
| 1976 |
if index.indices(self.n_blocks)[2] > 0: |
| 1977 |
for i in reversed(range(*index.indices(self.n_blocks))): |
| 1978 |
self.__delitem__(i) |
| 1979 |
else: |
| 1980 |
for i in range(*index.indices(self.n_blocks)): |
| 1981 |
self.__delitem__(i) |
| 1982 |
return |
| 1983 |
if isinstance(index, str): |
| 1984 |
index = self.get_index_by_name(index) |
| 1985 |
self._remove_ref(index) |
| 1986 |
self.RemoveBlock(index) |
| 1987 |
|
| 1988 |
def _remove_ref(self: MultiBlock, index: int) -> None: |
| 1989 |
"""Remove python reference to the dataset.""" |
| 1990 |
dataset = self[index] |
| 1991 |
if hasattr(dataset, 'memory_address'): |
| 1992 |
self._refs.pop(dataset.memory_address, None) # type: ignore[union-attr] |
| 1993 |
|
| 1994 |
def __eq__(self: MultiBlock, other: object) -> bool: |
| 1995 |
"""Equality comparison.""" |
| 1996 |
if not isinstance(other, MultiBlock): |
| 1997 |
return False |
| 1998 |
|
| 1999 |
if self is other: |
| 2000 |
return True |
| 2001 |
|
| 2002 |
if len(self) != len(other): |
| 2003 |
return False |
| 2004 |
|
| 2005 |
if not self.keys() == other.keys(): |
| 2006 |
return False |
| 2007 |
|
| 2008 |
return not any( |
| 2009 |
self_mesh != other_mesh for self_mesh, other_mesh in zip(self, other, strict=True) |
| 2010 |
) |
| 2011 |
|
| 2012 |
__hash__ = None # type: ignore[assignment] # https://github.com/pyvista/pyvista/pull/7671 |
| 2013 |
|
| 2014 |
def insert( |
| 2015 |
self: MultiBlock, |
| 2016 |
index: int, |
| 2017 |
dataset: _TypeMultiBlockLeaf, |
| 2018 |
name: str | None = None, |
| 2019 |
) -> None: |
| 2020 |
"""Insert data before index. |
| 2021 |
|
| 2022 |
Parameters |
| 2023 |
---------- |
| 2024 |
index : int |
| 2025 |
Index before which to insert data. |
| 2026 |
dataset : pyvista.DataSet or pyvista.MultiBlock |
| 2027 |
Data to insert. |
| 2028 |
name : str, optional |
| 2029 |
Name for key to give dataset. A default name is given |
| 2030 |
depending on the block index as ``'Block-{i:02}'``. |
| 2031 |
|
| 2032 |
Examples |
| 2033 |
-------- |
| 2034 |
Insert a new :class:`pyvista.PolyData` at the start of the multiblock. |
| 2035 |
|
| 2036 |
>>> import pyvista as pv |
| 2037 |
>>> data = { |
| 2038 |
... 'cube': pv.Cube(), |
| 2039 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 2040 |
... } |
| 2041 |
>>> blocks = pv.MultiBlock(data) |
| 2042 |
>>> blocks.keys() |
| 2043 |
['cube', 'sphere'] |
| 2044 |
>>> blocks.insert(0, pv.Plane(), 'plane') |
| 2045 |
>>> blocks.keys() |
| 2046 |
['plane', 'cube', 'sphere'] |
| 2047 |
|
| 2048 |
""" |
| 2049 |
index = range(self.n_blocks)[index] |
| 2050 |
|
| 2051 |
self.n_blocks += 1 |
| 2052 |
for i in reversed(range(index, self.n_blocks - 1)): |
| 2053 |
self[i + 1] = self[i] |
| 2054 |
self.set_block_name(i + 1, self.get_block_name(i)) |
| 2055 |
|
| 2056 |
self[index] = dataset |
| 2057 |
self.set_block_name(index, name) |
| 2058 |
|
| 2059 |
def pop(self: MultiBlock, index: int | str = -1) -> _TypeMultiBlockLeaf: |
| 2060 |
"""Pop off a block at the specified index. |
| 2061 |
|
| 2062 |
Parameters |
| 2063 |
---------- |
| 2064 |
index : int or str, default: -1 |
| 2065 |
Index or name of the dataset within the multiblock. Defaults to |
| 2066 |
last dataset. |
| 2067 |
|
| 2068 |
Returns |
| 2069 |
------- |
| 2070 |
output : pyvista.DataSet | pyvista.MultiBlock |
| 2071 |
Dataset from the given index that was removed. |
| 2072 |
|
| 2073 |
Examples |
| 2074 |
-------- |
| 2075 |
Pop the ``"cube"`` multiblock. |
| 2076 |
|
| 2077 |
>>> import pyvista as pv |
| 2078 |
>>> data = { |
| 2079 |
... 'cube': pv.Cube(), |
| 2080 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 2081 |
... } |
| 2082 |
>>> blocks = pv.MultiBlock(data) |
| 2083 |
>>> blocks.keys() |
| 2084 |
['cube', 'sphere'] |
| 2085 |
>>> cube = blocks.pop('cube') |
| 2086 |
>>> blocks.keys() |
| 2087 |
['sphere'] |
| 2088 |
|
| 2089 |
""" |
| 2090 |
if isinstance(index, int): |
| 2091 |
index = range(self.n_blocks)[index] |
| 2092 |
data = self[index] |
| 2093 |
del self[index] |
| 2094 |
return data |
| 2095 |
|
| 2096 |
def reverse(self: MultiBlock) -> None: |
| 2097 |
"""Reverse MultiBlock in-place. |
| 2098 |
|
| 2099 |
Examples |
| 2100 |
-------- |
| 2101 |
Reverse a multiblock. |
| 2102 |
|
| 2103 |
>>> import pyvista as pv |
| 2104 |
>>> data = { |
| 2105 |
... 'cube': pv.Cube(), |
| 2106 |
... 'sphere': pv.Sphere(center=(2, 2, 0)), |
| 2107 |
... } |
| 2108 |
>>> blocks = pv.MultiBlock(data) |
| 2109 |
>>> blocks.keys() |
| 2110 |
['cube', 'sphere'] |
| 2111 |
>>> blocks.reverse() |
| 2112 |
>>> blocks.keys() |
| 2113 |
['sphere', 'cube'] |
| 2114 |
|
| 2115 |
""" |
| 2116 |
# Taken from implementation in collections.abc.MutableSequence |
| 2117 |
names = self.keys() |
| 2118 |
n = len(self) |
| 2119 |
for i in range(n // 2): |
| 2120 |
self[i], self[n - i - 1] = self[n - i - 1], self[i] |
| 2121 |
for i, name in enumerate(reversed(names)): |
| 2122 |
self.set_block_name(i, name) |
| 2123 |
|
| 2124 |
@_deprecate_positional_args |
| 2125 |
def clean(self: MultiBlock, empty: bool = True) -> None: # noqa: FBT001, FBT002 |
| 2126 |
"""Remove any null blocks in place. |
| 2127 |
|
| 2128 |
Parameters |
| 2129 |
---------- |
| 2130 |
empty : bool, default: True |
| 2131 |
Remove any meshes that are empty as well (have zero points). |
| 2132 |
|
| 2133 |
Examples |
| 2134 |
-------- |
| 2135 |
>>> import pyvista as pv |
| 2136 |
>>> data = {'cube': pv.Cube(), 'empty': pv.PolyData()} |
| 2137 |
>>> blocks = pv.MultiBlock(data) |
| 2138 |
>>> blocks.clean(empty=True) |
| 2139 |
>>> blocks.keys() |
| 2140 |
['cube'] |
| 2141 |
|
| 2142 |
""" |
| 2143 |
null_blocks = [] |
| 2144 |
for i in range(self.n_blocks): |
| 2145 |
data = self[i] |
| 2146 |
if isinstance(data, MultiBlock): |
| 2147 |
# Recursively move through nested structures |
| 2148 |
data.clean() |
| 2149 |
if data.n_blocks < 1: |
| 2150 |
null_blocks.append(i) |
| 2151 |
elif data is None or (empty and data.n_points < 1): |
| 2152 |
null_blocks.append(i) |
| 2153 |
# Now remove the null/empty meshes |
| 2154 |
null_blocks = np.array(null_blocks, dtype=int) # type: ignore[assignment] |
| 2155 |
for i in range(len(null_blocks)): |
| 2156 |
# Cast as int because windows is super annoying |
| 2157 |
del self[int(null_blocks[i])] |
| 2158 |
null_blocks -= 1 # type: ignore[assignment, operator] |
| 2159 |
|
| 2160 |
def _get_attrs(self: MultiBlock) -> list[tuple[str, Any, str]]: |
| 2161 |
"""Return the representation methods (internal helper).""" |
| 2162 |
attrs: list[tuple[str, Any, str]] = [] |
| 2163 |
attrs.append(('N Blocks:', self.n_blocks, '{}')) |
| 2164 |
bds = self.bounds |
| 2165 |
attrs.append(('X Bounds:', (bds.x_min, bds.x_max), '{:.3e}, {:.3e}')) |
| 2166 |
attrs.append(('Y Bounds:', (bds.y_min, bds.y_max), '{:.3e}, {:.3e}')) |
| 2167 |
attrs.append(('Z Bounds:', (bds.z_min, bds.z_max), '{:.3e}, {:.3e}')) |
| 2168 |
return attrs |
| 2169 |
|
| 2170 |
def _repr_html_(self: MultiBlock) -> str: |
| 2171 |
"""Define a pretty representation for Jupyter notebooks.""" |
| 2172 |
sections: list[str] = [] |
| 2173 |
|
| 2174 |
# Bounds metadata |
| 2175 |
bds = self.bounds |
| 2176 |
fmt = pv.FLOAT_FORMAT |
| 2177 |
meta: list[tuple[str, list[tuple[str, str]], str]] = [ |
| 2178 |
( |
| 2179 |
'Bounds', |
| 2180 |
[ |
| 2181 |
('X', f'[{fmt.format(bds.x_min)}, {fmt.format(bds.x_max)}]'), |
| 2182 |
('Y', f'[{fmt.format(bds.y_min)}, {fmt.format(bds.y_max)}]'), |
| 2183 |
('Z', f'[{fmt.format(bds.z_min)}, {fmt.format(bds.z_max)}]'), |
| 2184 |
], |
| 2185 |
repr(tuple(bds)), |
| 2186 |
), |
| 2187 |
] |
| 2188 |
|
| 2189 |
# Children |
| 2190 |
children: list[tuple[str, str, str]] = [] |
| 2191 |
for i in range(self.n_blocks): |
| 2192 |
block = self[i] |
| 2193 |
name = self.get_block_name(i) or f'Block {i}' |
| 2194 |
if block is None: |
| 2195 |
children.append((name, 'None', '')) |
| 2196 |
continue |
| 2197 |
ctype = type(block).__name__ |
| 2198 |
if isinstance(block, MultiBlock): |
| 2199 |
detail = f'{block.n_blocks} blocks \u00b7 {_fmt_memory(block.actual_memory_size)}' |
| 2200 |
elif hasattr(block, 'n_points') and hasattr(block, 'n_cells'): |
| 2201 |
detail = ( |
| 2202 |
f'{block.n_points:,} pts \u00b7 ' |
| 2203 |
f'{block.n_cells:,} cells \u00b7 ' |
| 2204 |
f'{_fmt_memory(block.actual_memory_size)}' |
| 2205 |
) |
| 2206 |
else: |
| 2207 |
detail = '' |
| 2208 |
children.append((name, ctype, detail)) |
| 2209 |
if children: |
| 2210 |
sections.append(_children_section('Blocks', children)) |
| 2211 |
|
| 2212 |
return build_repr_html( |
| 2213 |
obj_type=type(self).__name__, |
| 2214 |
mesh_type='MultiBlock', |
| 2215 |
header_badges=[ |
| 2216 |
f'{self.n_blocks} blocks', |
| 2217 |
_fmt_memory(self.actual_memory_size), |
| 2218 |
], |
| 2219 |
metadata=meta, |
| 2220 |
sections=sections, |
| 2221 |
text_repr=repr(self), |
| 2222 |
) |
| 2223 |
|
| 2224 |
def __repr__(self: MultiBlock) -> str: |
| 2225 |
"""Define an adequate representation.""" |
| 2226 |
# return a string that is Python console friendly |
| 2227 |
fmt = f'{type(self).__name__} ({hex(id(self))})\n' |
| 2228 |
# now make a call on the object to get its attributes as a list of len 2 tuples |
| 2229 |
max_len = max(len(attr[0]) for attr in self._get_attrs()) + 3 |
| 2230 |
row = f' {{:{max_len}s}}' + '{}\n' |
| 2231 |
for attr in self._get_attrs(): |
| 2232 |
try: |
| 2233 |
fmt += row.format(attr[0], attr[2].format(*attr[1])) |
| 2234 |
except TypeError: |
| 2235 |
fmt += row.format(attr[0], attr[2].format(attr[1])) |
| 2236 |
return fmt.strip() |
| 2237 |
|
| 2238 |
def __str__(self: MultiBlock) -> str: |
| 2239 |
"""Return the str representation of the multi block.""" |
| 2240 |
return MultiBlock.__repr__(self) |
| 2241 |
|
| 2242 |
def __len__(self: MultiBlock) -> int: |
| 2243 |
"""Return the number of blocks.""" |
| 2244 |
return self.n_blocks |
| 2245 |
|
| 2246 |
@_deprecate_positional_args(allowed=['ido']) |
| 2247 |
def copy_meta_from( |
| 2248 |
self: MultiBlock, |
| 2249 |
ido: MultiBlock, |
| 2250 |
deep: bool, # noqa: FBT001 |
| 2251 |
) -> None: # numpydoc ignore=PR01 |
| 2252 |
"""Copy pyvista meta data onto this object from another object.""" |
| 2253 |
# Note that `pyvista.MultiBlock` datasets currently don't have any meta. |
| 2254 |
# This method is here for consistency with the rest of the API and |
| 2255 |
# in case we add meta data to this pbject down the road. |
| 2256 |
|
| 2257 |
@_deprecate_positional_args |
| 2258 |
def copy(self: Self, deep: bool = True) -> Self: # noqa: FBT001, FBT002 |
| 2259 |
"""Return a copy of the multiblock. |
| 2260 |
|
| 2261 |
Parameters |
| 2262 |
---------- |
| 2263 |
deep : bool, default: True |
| 2264 |
When ``True``, make a full copy of the object. |
| 2265 |
|
| 2266 |
Returns |
| 2267 |
------- |
| 2268 |
pyvista.MultiBlock |
| 2269 |
Deep or shallow copy of the ``MultiBlock``. |
| 2270 |
|
| 2271 |
Examples |
| 2272 |
-------- |
| 2273 |
>>> import pyvista as pv |
| 2274 |
>>> data = [ |
| 2275 |
... pv.Sphere(center=(2, 0, 0)), |
| 2276 |
... pv.Cube(center=(0, 2, 0)), |
| 2277 |
... pv.Cone(), |
| 2278 |
... ] |
| 2279 |
>>> blocks = pv.MultiBlock(data) |
| 2280 |
>>> new_blocks = blocks.copy() |
| 2281 |
>>> len(new_blocks) |
| 2282 |
3 |
| 2283 |
|
| 2284 |
""" |
| 2285 |
thistype = type(self) |
| 2286 |
newobject = thistype() |
| 2287 |
if deep: |
| 2288 |
newobject.deep_copy(self) |
| 2289 |
else: |
| 2290 |
newobject.shallow_copy(self) |
| 2291 |
newobject.copy_meta_from(self, deep=deep) |
| 2292 |
return newobject |
| 2293 |
|
| 2294 |
@_deprecate_positional_args(allowed=['to_copy']) |
| 2295 |
def shallow_copy( # type: ignore[override] |
| 2296 |
self: MultiBlock, |
| 2297 |
to_copy: _vtk.vtkMultiBlockDataSet, |
| 2298 |
recursive: bool = False, # noqa: FBT001, FBT002 |
| 2299 |
) -> None: |
| 2300 |
"""Shallow copy the given multiblock to this multiblock. |
| 2301 |
|
| 2302 |
Parameters |
| 2303 |
---------- |
| 2304 |
to_copy : MultiBlock | :vtk:`vtkMultiBlockDataSet` |
| 2305 |
Data object to perform a shallow copy from. |
| 2306 |
|
| 2307 |
recursive : bool, default: False |
| 2308 |
Also shallow-copy any nested :class:`~pyvista.MultiBlock` blocks. By |
| 2309 |
default, only the root :class:`~pyvista.MultiBlock` is shallow-copied and |
| 2310 |
any nested multi-blocks are not shallow-copied. |
| 2311 |
|
| 2312 |
""" |
| 2313 |
if pv.vtk_version_info >= (9, 3): # pragma: no cover |
| 2314 |
self.CompositeShallowCopy(to_copy) |
| 2315 |
else: |
| 2316 |
self.ShallowCopy(to_copy) |
| 2317 |
self.wrap_nested() |
| 2318 |
|
| 2319 |
# Shallow copy creates new instances of nested multiblocks |
| 2320 |
# Iterate through the blocks to fix this recursively |
| 2321 |
def _replace_nested_multiblocks( |
| 2322 |
this_object_: MultiBlock, new_object: _vtk.vtkMultiBlockDataSet |
| 2323 |
) -> None: |
| 2324 |
for i, this_block in enumerate(this_object_): |
| 2325 |
if isinstance(this_block, _vtk.vtkMultiBlockDataSet): |
| 2326 |
block_to_copy = cast('MultiBlock', new_object.GetBlock(i)) |
| 2327 |
this_object_.replace(i, block_to_copy) |
| 2328 |
_replace_nested_multiblocks(cast('MultiBlock', this_block), block_to_copy) |
| 2329 |
|
| 2330 |
if not recursive: |
| 2331 |
_replace_nested_multiblocks(self, to_copy) |
| 2332 |
|
| 2333 |
def deep_copy(self: MultiBlock, to_copy: _vtk.vtkMultiBlockDataSet) -> None: # type: ignore[override] |
| 2334 |
"""Overwrite this MultiBlock with another MultiBlock as a deep copy. |
| 2335 |
|
| 2336 |
Parameters |
| 2337 |
---------- |
| 2338 |
to_copy : MultiBlock | :vtk:`vtkMultiBlockDataSet` |
| 2339 |
MultiBlock to perform a deep copy from. |
| 2340 |
|
| 2341 |
""" |
| 2342 |
super().deep_copy(to_copy) |
| 2343 |
self.wrap_nested() |
| 2344 |
|
| 2345 |
# Deep copy will not copy the block name for None blocks (name is set to None instead) |
| 2346 |
# Iterate through the blocks to fix this recursively |
| 2347 |
def _set_name_for_none_blocks( |
| 2348 |
this_object_: MultiBlock, new_object_: _vtk.vtkMultiBlockDataSet |
| 2349 |
) -> None: |
| 2350 |
new_object_ = pv.wrap(new_object_) |
| 2351 |
for i, dataset in enumerate(new_object_): |
| 2352 |
if dataset is None: |
| 2353 |
this_object_.set_block_name(i, new_object_.get_block_name(i)) |
| 2354 |
elif isinstance(dataset, MultiBlock): |
| 2355 |
_set_name_for_none_blocks(cast('MultiBlock', this_object_[i]), dataset) |
| 2356 |
|
| 2357 |
_set_name_for_none_blocks(self, to_copy) |
| 2358 |
|
| 2359 |
@_deprecate_positional_args(allowed=['name']) |
| 2360 |
def set_active_scalars( |
| 2361 |
self: MultiBlock, |
| 2362 |
name: str | None, |
| 2363 |
preference: PointLiteral | CellLiteral = 'cell', |
| 2364 |
allow_missing: bool = False, # noqa: FBT001, FBT002 |
| 2365 |
) -> tuple[FieldAssociation, NumpyArray[float]]: |
| 2366 |
"""Find the scalars by name and appropriately set it as active. |
| 2367 |
|
| 2368 |
To deactivate any active scalars, pass ``None`` as the ``name``. |
| 2369 |
|
| 2370 |
Parameters |
| 2371 |
---------- |
| 2372 |
name : str or None |
| 2373 |
Name of the scalars array to assign as active. If |
| 2374 |
``None``, deactivates active scalars for both point and |
| 2375 |
cell data. |
| 2376 |
|
| 2377 |
preference : str, default: "cell" |
| 2378 |
If there are two arrays of the same name associated with |
| 2379 |
points or cells, it will prioritize an array matching this |
| 2380 |
type. Can be either ``'cell'`` or ``'point'``. |
| 2381 |
|
| 2382 |
allow_missing : bool, default: False |
| 2383 |
Allow missing scalars in part of the composite dataset. If all |
| 2384 |
blocks are missing the array, it will raise a ``KeyError``. |
| 2385 |
|
| 2386 |
Returns |
| 2387 |
------- |
| 2388 |
pyvista.core.utilities.arrays.FieldAssociation |
| 2389 |
Field association of the scalars activated. |
| 2390 |
|
| 2391 |
numpy.ndarray |
| 2392 |
An array from the dataset matching ``name``. |
| 2393 |
|
| 2394 |
Notes |
| 2395 |
----- |
| 2396 |
The number of components of the data must match. |
| 2397 |
|
| 2398 |
""" |
| 2399 |
data_assoc: list[tuple[FieldAssociation, NumpyArray[float], _TypeMultiBlockLeaf]] = [] |
| 2400 |
for block in self: |
| 2401 |
if block is not None: |
| 2402 |
if isinstance(block, MultiBlock): |
| 2403 |
field, scalars = block.set_active_scalars( |
| 2404 |
name, |
| 2405 |
preference=preference, |
| 2406 |
allow_missing=allow_missing, |
| 2407 |
) |
| 2408 |
else: |
| 2409 |
try: |
| 2410 |
field, scalars_out = block.set_active_scalars(name, preference=preference) |
| 2411 |
if scalars_out is None: |
| 2412 |
field, scalars = FieldAssociation.NONE, pyvista_ndarray([]) |
| 2413 |
else: |
| 2414 |
scalars = scalars_out |
| 2415 |
except KeyError: |
| 2416 |
if not allow_missing: |
| 2417 |
raise |
| 2418 |
block.set_active_scalars(None, preference=preference) |
| 2419 |
field, scalars = FieldAssociation.NONE, pyvista_ndarray([]) |
| 2420 |
|
| 2421 |
if field != FieldAssociation.NONE: |
| 2422 |
data_assoc.append((field, scalars, block)) |
| 2423 |
|
| 2424 |
if name is None: |
| 2425 |
return FieldAssociation.NONE, pyvista_ndarray([]) |
| 2426 |
|
| 2427 |
if not data_assoc: |
| 2428 |
msg = f'"{name}" is missing from all the blocks of this composite dataset.' |
| 2429 |
raise KeyError(msg) |
| 2430 |
|
| 2431 |
field_asc = data_assoc[0][0] |
| 2432 |
# set the field association to the preference if at least one occurrence |
| 2433 |
# of it exists |
| 2434 |
preference_ = parse_field_choice(preference) |
| 2435 |
if field_asc != preference_: |
| 2436 |
for field, _, _ in data_assoc: |
| 2437 |
if field == preference_: |
| 2438 |
field_asc = preference_ |
| 2439 |
break |
| 2440 |
|
| 2441 |
# Verify array consistency |
| 2442 |
dims: set[int] = set() |
| 2443 |
dtypes: set[np.dtype[Any]] = set() |
| 2444 |
for _ in self: |
| 2445 |
for field, scalars, _ in data_assoc: |
| 2446 |
# only check for the active field association |
| 2447 |
if field != field_asc: |
| 2448 |
continue |
| 2449 |
dims.add(scalars.ndim) |
| 2450 |
dtypes.add(scalars.dtype) |
| 2451 |
|
| 2452 |
if len(dims) > 1: |
| 2453 |
msg = f'Inconsistent dimensions {dims} in active scalars.' |
| 2454 |
raise ValueError(msg) |
| 2455 |
|
| 2456 |
# check complex mismatch |
| 2457 |
is_complex = [np.issubdtype(dtype, np.complexfloating) for dtype in dtypes] |
| 2458 |
if any(is_complex) and not all(is_complex): |
| 2459 |
msg = 'Inconsistent complex and real data types in active scalars.' |
| 2460 |
raise ValueError(msg) |
| 2461 |
|
| 2462 |
return field_asc, scalars |
| 2463 |
|
| 2464 |
@_deprecate_positional_args |
| 2465 |
def as_polydata_blocks(self: MultiBlock, copy: bool = False) -> MultiBlock: # noqa: FBT001, FBT002 |
| 2466 |
"""Convert all the datasets within this MultiBlock to :class:`~pyvista.PolyData`. |
| 2467 |
|
| 2468 |
Parameters |
| 2469 |
---------- |
| 2470 |
copy : bool, default: False |
| 2471 |
Option to create a shallow copy of any datasets that are already a |
| 2472 |
:class:`~pyvista.PolyData`. When ``False``, any datasets that are |
| 2473 |
already PolyData will not be copied. |
| 2474 |
|
| 2475 |
Returns |
| 2476 |
------- |
| 2477 |
pyvista.MultiBlock |
| 2478 |
MultiBlock containing only :class:`pyvista.PolyData` datasets. |
| 2479 |
|
| 2480 |
See Also |
| 2481 |
-------- |
| 2482 |
as_unstructured_grid_blocks |
| 2483 |
Convert all blocks to :class:`~pyvista.UnstructuredGrid`. |
| 2484 |
is_all_polydata |
| 2485 |
Check if all blocks are :class:`~pyvista.PolyData`. |
| 2486 |
:meth:`~pyvista.DataObjectFilters.extract_surface` |
| 2487 |
Convert this :class:`~pyvista.MultiBlock` to :class:`~pyvista.PolyData`. |
| 2488 |
|
| 2489 |
Notes |
| 2490 |
----- |
| 2491 |
Null blocks are converted to empty :class:`pyvista.PolyData` |
| 2492 |
objects. Downstream filters that operate on PolyData cannot accept |
| 2493 |
MultiBlocks with null blocks. |
| 2494 |
|
| 2495 |
""" |
| 2496 |
|
| 2497 |
# Define how to process each block |
| 2498 |
def block_filter(block: DataSet | None) -> PolyData: |
| 2499 |
if block is None: |
| 2500 |
return pv.PolyData() |
| 2501 |
elif isinstance(block, pv.PointSet): |
| 2502 |
return block.cast_to_polydata(deep=True) |
| 2503 |
elif isinstance(block, pv.PolyData): |
| 2504 |
return block.copy(deep=False) if copy else block |
| 2505 |
else: |
| 2506 |
return block.extract_surface(algorithm=None) |
| 2507 |
|
| 2508 |
return self.generic_filter(block_filter, _skip_none=False) |
| 2509 |
|
| 2510 |
@_deprecate_positional_args |
| 2511 |
def as_unstructured_grid_blocks(self: MultiBlock, copy: bool = False) -> MultiBlock: # noqa: FBT001, FBT002 |
| 2512 |
"""Convert all the datasets within this MultiBlock to :class:`~pyvista.UnstructuredGrid`. |
| 2513 |
|
| 2514 |
.. versionadded:: 0.45 |
| 2515 |
|
| 2516 |
Parameters |
| 2517 |
---------- |
| 2518 |
copy : bool, default: False |
| 2519 |
Option to create a shallow copy of any datasets that are already a |
| 2520 |
:class:`~pyvista.UnstructuredGrid`. When ``False``, any datasets that are |
| 2521 |
already UnstructuredGrid will not be copied. |
| 2522 |
|
| 2523 |
Returns |
| 2524 |
------- |
| 2525 |
MultiBlock |
| 2526 |
MultiBlock containing only :class:`~pyvista.UnstructuredGrid` datasets. |
| 2527 |
|
| 2528 |
See Also |
| 2529 |
-------- |
| 2530 |
as_polydata_blocks |
| 2531 |
|
| 2532 |
Notes |
| 2533 |
----- |
| 2534 |
Null blocks are converted to empty :class:`~pyvista.UnstructuredGrid` |
| 2535 |
objects. Downstream filters that operate on UnstructuredGrid may not accept |
| 2536 |
MultiBlocks with null blocks. |
| 2537 |
|
| 2538 |
""" |
| 2539 |
|
| 2540 |
# Define how to process each block |
| 2541 |
def block_filter(block: DataSet | None) -> DataSet: |
| 2542 |
if block is None: |
| 2543 |
return pv.UnstructuredGrid() |
| 2544 |
elif isinstance(block, pv.UnstructuredGrid): |
| 2545 |
return block.copy(deep=False) if copy else block |
| 2546 |
else: |
| 2547 |
return block.cast_to_unstructured_grid() |
| 2548 |
|
| 2549 |
return self.generic_filter(block_filter, _skip_none=False) |
| 2550 |
|
| 2551 |
@property |
| 2552 |
def is_all_polydata(self: MultiBlock) -> bool: |
| 2553 |
"""Return ``True`` when all the blocks are :class:`~pyvista.PolyData`. |
| 2554 |
|
| 2555 |
This method will recursively check if any internal blocks are also |
| 2556 |
:class:`~pyvista.PolyData`. |
| 2557 |
|
| 2558 |
Returns |
| 2559 |
------- |
| 2560 |
bool |
| 2561 |
Return ``True`` when all blocks are :class:`~pyvista.PolyData`. |
| 2562 |
|
| 2563 |
See Also |
| 2564 |
-------- |
| 2565 |
as_polydata_blocks |
| 2566 |
Convert all blocks to :class:`~pyvista.PolyData`. |
| 2567 |
:meth:`~pyvista.DataObjectFilters.extract_surface` |
| 2568 |
Convert this :class:`~pyvista.MultiBlock` to :class:`~pyvista.PolyData`. |
| 2569 |
|
| 2570 |
""" |
| 2571 |
return all(isinstance(block, pv.PolyData) for block in self.recursive_iterator()) |
| 2572 |
|
| 2573 |
@property |
| 2574 |
def block_types(self) -> set[type[_TypeMultiBlockLeaf]]: # numpydoc ignore=RT01 |
| 2575 |
"""Return a set of all block type(s). |
| 2576 |
|
| 2577 |
.. versionadded:: 0.45 |
| 2578 |
|
| 2579 |
See Also |
| 2580 |
-------- |
| 2581 |
nested_block_types |
| 2582 |
|
| 2583 |
Examples |
| 2584 |
-------- |
| 2585 |
Load a dataset with nested multi-blocks. Here we load |
| 2586 |
:func:`~pyvista.examples.downloads.download_cgns_multi`. |
| 2587 |
|
| 2588 |
>>> from pyvista import examples |
| 2589 |
>>> multi = examples.download_cgns_multi() |
| 2590 |
|
| 2591 |
The dataset has eight nested multi-block blocks, so the block types |
| 2592 |
only contains :class:`MultiBlock`. |
| 2593 |
|
| 2594 |
>>> multi.block_types |
| 2595 |
{<class 'pyvista.core.composite.MultiBlock'>} |
| 2596 |
|
| 2597 |
The nested blocks only contain a single mesh type so the nested block types |
| 2598 |
only contains :class:`~pyvista.UnstructuredGrid`. |
| 2599 |
|
| 2600 |
>>> multi.nested_block_types |
| 2601 |
{<class 'pyvista.core.pointset.StructuredGrid'>} |
| 2602 |
|
| 2603 |
""" |
| 2604 |
return {type(block) for block in self} |
| 2605 |
|
| 2606 |
@property |
| 2607 |
def nested_block_types(self) -> set[type[DataSet | None]]: # numpydoc ignore=RT01 |
| 2608 |
"""Return a set of all nested block type(s). |
| 2609 |
|
| 2610 |
.. versionadded:: 0.45 |
| 2611 |
|
| 2612 |
See Also |
| 2613 |
-------- |
| 2614 |
block_types |
| 2615 |
is_homogeneous |
| 2616 |
is_heterogeneous |
| 2617 |
recursive_iterator |
| 2618 |
|
| 2619 |
Examples |
| 2620 |
-------- |
| 2621 |
Load a dataset with nested multi-blocks. Here we load |
| 2622 |
:func:`~pyvista.examples.downloads.download_cgns_multi`. |
| 2623 |
|
| 2624 |
>>> from pyvista import examples |
| 2625 |
>>> multi = examples.download_cgns_multi() |
| 2626 |
|
| 2627 |
The dataset has eight nested multi-block blocks, so the block types |
| 2628 |
only contains :class:`MultiBlock`. |
| 2629 |
|
| 2630 |
>>> multi.block_types |
| 2631 |
{<class 'pyvista.core.composite.MultiBlock'>} |
| 2632 |
|
| 2633 |
The nested blocks only contain a single mesh type so the nested block types |
| 2634 |
only contains :class:`~pyvista.UnstructuredGrid`. |
| 2635 |
|
| 2636 |
>>> multi.nested_block_types |
| 2637 |
{<class 'pyvista.core.pointset.StructuredGrid'>} |
| 2638 |
|
| 2639 |
""" |
| 2640 |
return {type(block) for block in self.recursive_iterator()} |
| 2641 |
|
| 2642 |
@property |
| 2643 |
def is_homogeneous(self: MultiBlock) -> bool: # numpydoc ignore=RT01 |
| 2644 |
"""Return ``True`` if all nested blocks have the same type. |
| 2645 |
|
| 2646 |
.. versionadded:: 0.45 |
| 2647 |
|
| 2648 |
See Also |
| 2649 |
-------- |
| 2650 |
is_heterogeneous |
| 2651 |
nested_block_types |
| 2652 |
recursive_iterator |
| 2653 |
|
| 2654 |
Examples |
| 2655 |
-------- |
| 2656 |
Load a dataset with nested multi-blocks. Here we load |
| 2657 |
:func:`~pyvista.examples.downloads.download_cgns_multi`. |
| 2658 |
|
| 2659 |
>>> from pyvista import examples |
| 2660 |
>>> multi = examples.download_cgns_multi() |
| 2661 |
|
| 2662 |
Show the :attr:`nested_block_types`. |
| 2663 |
|
| 2664 |
>>> multi.nested_block_types |
| 2665 |
{<class 'pyvista.core.pointset.StructuredGrid'>} |
| 2666 |
|
| 2667 |
Since there is only one type, the dataset is homogeneous. |
| 2668 |
|
| 2669 |
>>> multi.is_homogeneous |
| 2670 |
True |
| 2671 |
|
| 2672 |
""" |
| 2673 |
return len(self.nested_block_types) == 1 |
| 2674 |
|
| 2675 |
@property |
| 2676 |
def is_heterogeneous(self: MultiBlock) -> bool: # numpydoc ignore=RT01 |
| 2677 |
"""Return ``True`` any two nested blocks have different type. |
| 2678 |
|
| 2679 |
.. versionadded:: 0.45 |
| 2680 |
|
| 2681 |
See Also |
| 2682 |
-------- |
| 2683 |
is_homogeneous |
| 2684 |
nested_block_types |
| 2685 |
recursive_iterator |
| 2686 |
|
| 2687 |
Examples |
| 2688 |
-------- |
| 2689 |
Load a dataset with nested multi-blocks. Here we load |
| 2690 |
:func:`~pyvista.examples.downloads.download_mug`. |
| 2691 |
|
| 2692 |
>>> from pyvista import examples |
| 2693 |
>>> multi = examples.download_mug() |
| 2694 |
|
| 2695 |
Show the :attr:`nested_block_types`. |
| 2696 |
|
| 2697 |
>>> multi.nested_block_types # doctest:+SKIP |
| 2698 |
{<class 'pyvista.core.pointset.UnstructuredGrid'>, <class 'NoneType'>} |
| 2699 |
|
| 2700 |
Since there is more than one type, the dataset is heterogeneous. |
| 2701 |
|
| 2702 |
>>> multi.is_heterogeneous |
| 2703 |
True |
| 2704 |
|
| 2705 |
""" |
| 2706 |
return len(self.nested_block_types) > 1 |
| 2707 |
|
| 2708 |
def _activate_plotting_scalars( |
| 2709 |
self: MultiBlock, |
| 2710 |
*, |
| 2711 |
scalars_name: str, |
| 2712 |
preference: PointLiteral | CellLiteral, |
| 2713 |
component: int | None, |
| 2714 |
rgb: NumpyArray[float], |
| 2715 |
) -> tuple[FieldAssociation, str, np.dtype[np.number[Any]]]: |
| 2716 |
"""Active a scalars for an instance of :class:`pyvista.Plotter`.""" |
| 2717 |
# set the active scalars |
| 2718 |
field, scalars = self.set_active_scalars( |
| 2719 |
scalars_name, |
| 2720 |
preference=preference, |
| 2721 |
allow_missing=True, |
| 2722 |
) |
| 2723 |
|
| 2724 |
data_attr = f'{field.name.lower()}_data' |
| 2725 |
dtype = scalars.dtype |
| 2726 |
if rgb: |
| 2727 |
if scalars.ndim != 2 or scalars.shape[1] not in (3, 4): |
| 2728 |
msg = 'RGB array must be n_points/n_cells by 3/4 in shape.' |
| 2729 |
raise ValueError(msg) |
| 2730 |
if dtype != np.uint8: |
| 2731 |
# uint8 is required by the mapper to display correctly |
| 2732 |
_validation.check_subdtype(scalars, (np.floating, np.integer), name='rgb scalars') |
| 2733 |
scalars_name = self._convert_to_uint8_rgb_scalars(data_attr, scalars_name) |
| 2734 |
elif np.issubdtype(scalars.dtype, np.complexfloating): |
| 2735 |
# Use only the real component if an array is complex |
| 2736 |
scalars_name = self._convert_to_real_scalars(data_attr, scalars_name) |
| 2737 |
elif scalars.dtype in (np.bool_, np.uint8): |
| 2738 |
# bool and uint8 do not display properly, must convert to float |
| 2739 |
self._convert_to_real_scalars(data_attr, scalars_name) |
| 2740 |
if scalars.dtype == np.bool_: |
| 2741 |
dtype = np.bool_ # type: ignore[assignment] |
| 2742 |
elif scalars.ndim > 1: |
| 2743 |
# multi-component |
| 2744 |
if not isinstance(component, (int, type(None))): |
| 2745 |
msg = '`component` must be either None or an integer' # type: ignore[unreachable] |
| 2746 |
raise TypeError(msg) |
| 2747 |
if component is not None: |
| 2748 |
if component >= scalars.shape[1] or component < 0: |
| 2749 |
msg = ( |
| 2750 |
'Component must be nonnegative and less than the ' |
| 2751 |
f'dimensionality of the scalars array: {scalars.shape[1]}' |
| 2752 |
) |
| 2753 |
raise ValueError(msg) |
| 2754 |
scalars_name = self._convert_to_single_component(data_attr, scalars_name, component) |
| 2755 |
|
| 2756 |
return field, scalars_name, dtype |
| 2757 |
|
| 2758 |
def _convert_to_real_scalars(self: MultiBlock, data_attr: str, scalars_name: str) -> str: |
| 2759 |
"""Extract the real component of the active scalars of this dataset.""" |
| 2760 |
for block in self: |
| 2761 |
if isinstance(block, MultiBlock): |
| 2762 |
block._convert_to_real_scalars(data_attr, scalars_name) |
| 2763 |
elif block is not None: |
| 2764 |
scalars = getattr(block, data_attr).get(scalars_name, None) |
| 2765 |
if scalars is not None: |
| 2766 |
scalars = np.array(scalars.astype(float)) |
| 2767 |
dattr = getattr(block, data_attr) |
| 2768 |
dattr[f'{scalars_name}-real'] = scalars |
| 2769 |
dattr.active_scalars_name = f'{scalars_name}-real' |
| 2770 |
return f'{scalars_name}-real' |
| 2771 |
|
| 2772 |
def _convert_to_uint8_rgb_scalars(self: MultiBlock, data_attr: str, scalars_name: str) -> str: |
| 2773 |
"""Convert rgb float or int scalars to uint8.""" |
| 2774 |
for block in self: |
| 2775 |
if isinstance(block, MultiBlock): |
| 2776 |
block._convert_to_uint8_rgb_scalars(data_attr, scalars_name) |
| 2777 |
elif block is not None: |
| 2778 |
scalars = getattr(block, data_attr).get(scalars_name, None) |
| 2779 |
if scalars is not None: |
| 2780 |
if np.issubdtype(scalars.dtype, np.floating): |
| 2781 |
_validation.check_range(scalars, [0.0, 1.0], name='rgb float scalars') |
| 2782 |
scalars = np.array(scalars, dtype=np.uint8) * 255 |
| 2783 |
elif np.issubdtype(scalars.dtype, np.integer): |
| 2784 |
_validation.check_range(scalars, [0, 255], name='rgb int scalars') |
| 2785 |
scalars = np.array(scalars, dtype=np.uint8) |
| 2786 |
dattr = getattr(block, data_attr) |
| 2787 |
dattr[f'{scalars_name}-uint8'] = scalars |
| 2788 |
dattr.active_scalars_name = f'{scalars_name}-uint8' |
| 2789 |
return f'{scalars_name}-uint8' |
| 2790 |
|
| 2791 |
def _convert_to_single_component( |
| 2792 |
self: MultiBlock, |
| 2793 |
data_attr: str, |
| 2794 |
scalars_name: str, |
| 2795 |
component: int | None, |
| 2796 |
) -> str: |
| 2797 |
"""Convert multi-component scalars to a single component.""" |
| 2798 |
if component is None: |
| 2799 |
for block in self: |
| 2800 |
if isinstance(block, MultiBlock): |
| 2801 |
block._convert_to_single_component(data_attr, scalars_name, component) |
| 2802 |
elif block is not None: |
| 2803 |
scalars = getattr(block, data_attr).get(scalars_name, None) |
| 2804 |
if scalars is not None: |
| 2805 |
scalars = np.linalg.norm(scalars, axis=1) |
| 2806 |
dattr = getattr(block, data_attr) |
| 2807 |
dattr[f'{scalars_name}-normed'] = scalars |
| 2808 |
dattr.active_scalars_name = f'{scalars_name}-normed' |
| 2809 |
return f'{scalars_name}-normed' |
| 2810 |
|
| 2811 |
for block in self: |
| 2812 |
if isinstance(block, MultiBlock): |
| 2813 |
block._convert_to_single_component(data_attr, scalars_name, component) |
| 2814 |
elif block is not None: |
| 2815 |
scalars = getattr(block, data_attr).get(scalars_name, None) |
| 2816 |
if scalars is not None: |
| 2817 |
dattr = getattr(block, data_attr) |
| 2818 |
dattr[f'{scalars_name}-{component}'] = scalars[:, component] |
| 2819 |
dattr.active_scalars_name = f'{scalars_name}-{component}' |
| 2820 |
return f'{scalars_name}-{component}' |
| 2821 |
|
| 2822 |
def _get_consistent_active_scalars( |
| 2823 |
self: MultiBlock, |
| 2824 |
) -> tuple[str | None, str | None]: |
| 2825 |
"""Get if there are any consistent active scalars.""" |
| 2826 |
point_names = set() |
| 2827 |
cell_names = set() |
| 2828 |
for block in self: |
| 2829 |
if block is not None: |
| 2830 |
if isinstance(block, MultiBlock): |
| 2831 |
point_name, cell_name = block._get_consistent_active_scalars() |
| 2832 |
else: |
| 2833 |
point_name = block.point_data.active_scalars_name |
| 2834 |
cell_name = block.cell_data.active_scalars_name |
| 2835 |
point_names.add(point_name) |
| 2836 |
cell_names.add(cell_name) |
| 2837 |
|
| 2838 |
point_name = point_names.pop() if len(point_names) == 1 else None |
| 2839 |
cell_name = cell_names.pop() if len(cell_names) == 1 else None |
| 2840 |
return point_name, cell_name |
| 2841 |
|
| 2842 |
def clear_all_data(self: MultiBlock) -> None: |
| 2843 |
"""Clear all data from all blocks.""" |
| 2844 |
for block in self: |
| 2845 |
if isinstance(block, MultiBlock): |
| 2846 |
block.clear_all_data() |
| 2847 |
elif block is not None: |
| 2848 |
block.clear_data() |
| 2849 |
|
| 2850 |
def clear_all_point_data(self: MultiBlock) -> None: |
| 2851 |
"""Clear all point data from all blocks.""" |
| 2852 |
for block in self: |
| 2853 |
if isinstance(block, MultiBlock): |
| 2854 |
block.clear_all_point_data() |
| 2855 |
elif block is not None: |
| 2856 |
block.clear_point_data() |
| 2857 |
|
| 2858 |
def clear_all_cell_data(self: MultiBlock) -> None: |
| 2859 |
"""Clear all cell data from all blocks.""" |
| 2860 |
for block in self: |
| 2861 |
if isinstance(block, MultiBlock): |
| 2862 |
block.clear_all_cell_data() |
| 2863 |
elif block is not None: |
| 2864 |
block.clear_cell_data() |