| 1 |
"""Contains the PartitionedDataSet class.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from collections.abc import MutableSequence |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
from typing import overload |
| 8 |
|
| 9 |
import pyvista as pv |
| 10 |
from pyvista import _vtk |
| 11 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 12 |
from pyvista.core._vtk_utilities import vtk_version_info |
| 13 |
|
| 14 |
from .dataobject import DataObject |
| 15 |
from .errors import PartitionedDataSetsNotSupported |
| 16 |
from .formatting_html import _children_section |
| 17 |
from .formatting_html import build_repr_html |
| 18 |
from .utilities.helpers import is_pyvista_dataset |
| 19 |
from .utilities.helpers import wrap |
| 20 |
from .utilities.writer import HDFWriter |
| 21 |
from .utilities.writer import XMLPartitionedDataSetWriter |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from collections.abc import Iterable |
| 25 |
from typing import ClassVar |
| 26 |
|
| 27 |
from typing_extensions import Self |
| 28 |
|
| 29 |
from .dataset import DataSet |
| 30 |
from .utilities.arrays import FieldAssociation |
| 31 |
from .utilities.writer import BaseWriter |
| 32 |
|
| 33 |
|
| 34 |
class PartitionedDataSet(DataObject, MutableSequence, _vtk.vtkPartitionedDataSet): # type: ignore[type-arg] |
| 35 |
"""Wrapper for the :vtk:`vtkPartitionedDataSet` class. |
| 36 |
|
| 37 |
DataSet which composite dataset to encapsulates a dataset consisting of partitions. |
| 38 |
|
| 39 |
Examples |
| 40 |
-------- |
| 41 |
>>> import pyvista as pv |
| 42 |
>>> data = [ |
| 43 |
... pv.Sphere(center=(2, 0, 0)), |
| 44 |
... pv.Cube(center=(0, 2, 0)), |
| 45 |
... pv.Cone(), |
| 46 |
... ] |
| 47 |
>>> partitions = pv.PartitionedDataSet(data) |
| 48 |
>>> len(partitions) |
| 49 |
3 |
| 50 |
|
| 51 |
""" |
| 52 |
|
| 53 |
plot = pv._plot.plot |
| 54 |
|
| 55 |
_WRITERS: ClassVar[dict[str, type[BaseWriter]]] = {'.vtpd': XMLPartitionedDataSetWriter} |
| 56 |
|
| 57 |
if vtk_version_info >= (9, 4): |
| 58 |
_WRITERS['.vtkhdf'] = HDFWriter |
| 59 |
|
| 60 |
def __init__(self, *args, **kwargs): |
| 61 |
"""Initialize the PartitionedDataSet.""" |
| 62 |
super().__init__() |
| 63 |
if len(args) == 1: |
| 64 |
if isinstance(args[0], _vtk.vtkPartitionedDataSet): |
| 65 |
deep = kwargs.get('deep', True) |
| 66 |
if deep: |
| 67 |
self.deep_copy(args[0]) |
| 68 |
else: |
| 69 |
raise PartitionedDataSetsNotSupported |
| 70 |
elif isinstance(args[0], (list, tuple)): |
| 71 |
for partition in args[0]: |
| 72 |
self.append(partition) |
| 73 |
self.wrap_nested() |
| 74 |
|
| 75 |
def wrap_nested(self) -> None: |
| 76 |
"""Ensure that all nested data structures are wrapped as PyVista datasets. |
| 77 |
|
| 78 |
This is performed in place. |
| 79 |
|
| 80 |
""" |
| 81 |
for i in range(self.n_partitions): |
| 82 |
partition = self.GetPartition(i) |
| 83 |
if not is_pyvista_dataset(partition): |
| 84 |
self.SetPartition(i, wrap(partition)) |
| 85 |
|
| 86 |
@overload |
| 87 |
def __getitem__(self, index: int) -> DataSet | None: ... # pragma: no cover |
| 88 |
|
| 89 |
@overload |
| 90 |
def __getitem__(self, index: slice) -> PartitionedDataSet: ... # pragma: no cover |
| 91 |
|
| 92 |
def __getitem__(self, index): |
| 93 |
"""Get a partition by its index.""" |
| 94 |
if isinstance(index, slice): |
| 95 |
return PartitionedDataSet([self[i] for i in range(self.n_partitions)[index]]) |
| 96 |
else: |
| 97 |
if index < -self.n_partitions or index >= self.n_partitions: |
| 98 |
msg = f'index ({index}) out of range for this dataset.' |
| 99 |
raise IndexError(msg) |
| 100 |
if index < 0: |
| 101 |
index = self.n_partitions + index |
| 102 |
return wrap(self.GetPartition(index)) |
| 103 |
|
| 104 |
@overload |
| 105 |
def __setitem__(self, index: int, data: DataSet | None) -> None: ... # pragma: no cover |
| 106 |
|
| 107 |
@overload |
| 108 |
def __setitem__( |
| 109 |
self, index: slice, data: Iterable[DataSet | None] |
| 110 |
) -> None: ... # pragma: no cover |
| 111 |
|
| 112 |
def __setitem__( |
| 113 |
self, |
| 114 |
index: int | slice, |
| 115 |
data, |
| 116 |
): |
| 117 |
"""Set a partition with a VTK data object.""" |
| 118 |
if isinstance(index, slice): |
| 119 |
for i, d in zip(range(self.n_partitions)[index], data, strict=True): |
| 120 |
self.SetPartition(i, d) |
| 121 |
else: |
| 122 |
if index < -self.n_partitions or index >= self.n_partitions: |
| 123 |
msg = f'index ({index}) out of range for this dataset.' |
| 124 |
raise IndexError(msg) |
| 125 |
if index < 0: |
| 126 |
index = self.n_partitions + index |
| 127 |
self.SetPartition(index, data) |
| 128 |
|
| 129 |
def __delitem__(self, index: int | slice) -> None: |
| 130 |
"""Remove a partition at the specified index are not supported.""" |
| 131 |
raise PartitionedDataSetsNotSupported |
| 132 |
|
| 133 |
def insert(self, index: int, dataset: DataSet) -> None: # numpydoc ignore=PR01 |
| 134 |
"""Insert data before index.""" |
| 135 |
index = range(self.n_partitions)[index] |
| 136 |
self.n_partitions += 1 |
| 137 |
for i in reversed(range(index, self.n_partitions - 1)): |
| 138 |
self[i + 1] = self[i] |
| 139 |
self[index] = dataset |
| 140 |
|
| 141 |
def pop(self, index: int = -1) -> None: # numpydoc ignore=PR01 # noqa: ARG002 |
| 142 |
"""Pop off a partition at the specified index are not supported.""" |
| 143 |
raise PartitionedDataSetsNotSupported |
| 144 |
|
| 145 |
def _get_attrs(self): |
| 146 |
"""Return the representation methods (internal helper).""" |
| 147 |
attrs = [] |
| 148 |
attrs.append(('N Partitions', self.n_partitions, '{}')) |
| 149 |
return attrs |
| 150 |
|
| 151 |
def _repr_html_(self) -> str: |
| 152 |
"""Define a pretty representation for Jupyter notebooks.""" |
| 153 |
sections: list[str] = [] |
| 154 |
|
| 155 |
# Partitions |
| 156 |
children = [ |
| 157 |
(f'{i}', type(p).__name__ if (p := self[i]) is not None else 'None', '') |
| 158 |
for i in range(self.n_partitions) |
| 159 |
] |
| 160 |
if children: |
| 161 |
sections.append(_children_section('Partitions', children)) |
| 162 |
|
| 163 |
return build_repr_html( |
| 164 |
obj_type=type(self).__name__, |
| 165 |
mesh_type='ImageData', |
| 166 |
header_badges=[f'{self.n_partitions} partitions'], |
| 167 |
sections=sections, |
| 168 |
text_repr=repr(self), |
| 169 |
) |
| 170 |
|
| 171 |
def __repr__(self) -> str: |
| 172 |
"""Define an adequate representation.""" |
| 173 |
fmt = f'{type(self).__name__} ({hex(id(self))})\n' |
| 174 |
max_len = max(len(attr[0]) for attr in self._get_attrs()) + 4 |
| 175 |
row = f' {{:{max_len}s}}' + '{}\n' |
| 176 |
for attr in self._get_attrs(): |
| 177 |
try: |
| 178 |
fmt += row.format(attr[0], attr[2].format(*attr[1])) |
| 179 |
except TypeError: |
| 180 |
fmt += row.format(attr[0], attr[2].format(attr[1])) |
| 181 |
return fmt.strip() |
| 182 |
|
| 183 |
def __str__(self) -> str: |
| 184 |
"""Return the str representation of the multi partition.""" |
| 185 |
return PartitionedDataSet.__repr__(self) |
| 186 |
|
| 187 |
def __len__(self) -> int: |
| 188 |
"""Return the number of partitions.""" |
| 189 |
return self.n_partitions |
| 190 |
|
| 191 |
def copy_meta_from(self, ido, deep) -> None: # numpydoc ignore=PR01 |
| 192 |
"""Copy pyvista meta data onto this object from another object.""" |
| 193 |
|
| 194 |
@_deprecate_positional_args |
| 195 |
def copy(self, deep: bool = True): # noqa: FBT001, FBT002 |
| 196 |
"""Return a copy of the PartitionedDataSet. |
| 197 |
|
| 198 |
Parameters |
| 199 |
---------- |
| 200 |
deep : bool, default: True |
| 201 |
When ``True``, make a full copy of the object. |
| 202 |
|
| 203 |
Returns |
| 204 |
------- |
| 205 |
pyvista.PartitionedDataSet |
| 206 |
Deep or shallow copy of the ``PartitionedDataSet``. |
| 207 |
|
| 208 |
Examples |
| 209 |
-------- |
| 210 |
>>> import pyvista as pv |
| 211 |
>>> data = [ |
| 212 |
... pv.Sphere(center=(2, 0, 0)), |
| 213 |
... pv.Cube(center=(0, 2, 0)), |
| 214 |
... pv.Cone(), |
| 215 |
... ] |
| 216 |
>>> partitions = pv.PartitionedDataSet(data) |
| 217 |
>>> new_partitions = partitions.copy() |
| 218 |
>>> len(new_partitions) |
| 219 |
3 |
| 220 |
|
| 221 |
""" |
| 222 |
thistype = type(self) |
| 223 |
newobject = thistype() |
| 224 |
if deep: |
| 225 |
newobject.deep_copy(self) |
| 226 |
else: |
| 227 |
raise PartitionedDataSetsNotSupported |
| 228 |
newobject.copy_meta_from(self, deep) |
| 229 |
newobject.wrap_nested() |
| 230 |
return newobject |
| 231 |
|
| 232 |
@property |
| 233 |
def n_partitions(self) -> int: |
| 234 |
"""Return the number of partitions. |
| 235 |
|
| 236 |
Returns |
| 237 |
------- |
| 238 |
int |
| 239 |
The number of partitions. |
| 240 |
|
| 241 |
""" |
| 242 |
return self.GetNumberOfPartitions() |
| 243 |
|
| 244 |
@n_partitions.setter |
| 245 |
def n_partitions(self, n) -> None: |
| 246 |
self.SetNumberOfPartitions(n) |
| 247 |
self.Modified() |
| 248 |
|
| 249 |
@property |
| 250 |
def is_empty(self) -> bool: # numpydoc ignore=RT01 |
| 251 |
"""Return ``True`` if there are no partitions. |
| 252 |
|
| 253 |
.. versionadded:: 0.46 |
| 254 |
|
| 255 |
Examples |
| 256 |
-------- |
| 257 |
>>> import pyvista as pv |
| 258 |
>>> mesh = pv.PartitionedDataSet() |
| 259 |
>>> mesh.is_empty |
| 260 |
True |
| 261 |
|
| 262 |
>>> mesh.append(pv.Sphere()) |
| 263 |
>>> mesh.is_empty |
| 264 |
False |
| 265 |
|
| 266 |
""" |
| 267 |
return self.n_partitions == 0 |
| 268 |
|
| 269 |
def append(self, dataset) -> None: |
| 270 |
"""Add a data set to the next partition index. |
| 271 |
|
| 272 |
Parameters |
| 273 |
---------- |
| 274 |
dataset : pyvista.DataSet |
| 275 |
Dataset to append to this partitioned dataset. |
| 276 |
|
| 277 |
""" |
| 278 |
index = self.n_partitions |
| 279 |
self.n_partitions += 1 |
| 280 |
self[index] = dataset |
| 281 |
|
| 282 |
def get_data_range( # numpydoc ignore=RT01 |
| 283 |
self: Self, name: str | None, preference: FieldAssociation | str |
| 284 |
) -> tuple[float, float]: # pragma: no cover |
| 285 |
"""Get the non-NaN min and max of a named array.""" |
| 286 |
return DataObject.get_data_range(self, name=name, preference=preference) |