| 1 |
"""Utilities related to VTK.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from functools import cache |
| 6 |
import sys |
| 7 |
from typing import Literal |
| 8 |
from typing import NamedTuple |
| 9 |
|
| 10 |
from pyvista import _vtk |
| 11 |
from pyvista._warn_external import warn_external |
| 12 |
from pyvista.core.config import global_config |
| 13 |
|
| 14 |
|
| 15 |
class VersionInfo(NamedTuple): |
| 16 |
"""Version information as a named tuple.""" |
| 17 |
|
| 18 |
major: int |
| 19 |
minor: int |
| 20 |
micro: int |
| 21 |
|
| 22 |
def __str__(self): |
| 23 |
return str((self.major, self.minor, self.micro)) |
| 24 |
|
| 25 |
@staticmethod |
| 26 |
def _format(version: tuple[int, int, int]): |
| 27 |
return '.'.join(map(str, version)) |
| 28 |
|
| 29 |
|
| 30 |
def _get_vtk_version(): |
| 31 |
"""Return the vtk version as a namedtuple. |
| 32 |
|
| 33 |
Returns |
| 34 |
------- |
| 35 |
VersionInfo |
| 36 |
Version information as a named tuple. |
| 37 |
|
| 38 |
""" |
| 39 |
try: |
| 40 |
ver = _vtk.vtkVersion() |
| 41 |
major = ver.GetVTKMajorVersion() |
| 42 |
minor = ver.GetVTKMinorVersion() |
| 43 |
micro = ver.GetVTKBuildVersion() |
| 44 |
except AttributeError: # pragma: no cover |
| 45 |
msg = ( |
| 46 |
f'Unable to detect VTK version. ' |
| 47 |
f'Defaulting to {VersionInfo._format(_MIN_SUPPORTED_VTK_VERSION)}' |
| 48 |
) |
| 49 |
warn_external(msg) |
| 50 |
major, minor, micro = _MIN_SUPPORTED_VTK_VERSION |
| 51 |
return VersionInfo(major, minor, micro) |
| 52 |
|
| 53 |
|
| 54 |
class VTKVersionInfo(VersionInfo): |
| 55 |
def _check_min_supported(self, other: tuple[int, int, int]) -> None: |
| 56 |
if isinstance(other, tuple) and other < _MIN_SUPPORTED_VTK_VERSION: # type: ignore[redundant-expr] |
| 57 |
from pyvista.core.errors import VTKVersionError # noqa: PLC0415 |
| 58 |
|
| 59 |
msg = ( |
| 60 |
f'Comparing against unsupported VTK version {VersionInfo._format(other):}. ' |
| 61 |
f'Minimum supported is {VersionInfo._format(_MIN_SUPPORTED_VTK_VERSION):}.' |
| 62 |
) |
| 63 |
raise VTKVersionError(msg) |
| 64 |
|
| 65 |
def __lt__(self, other): |
| 66 |
self._check_min_supported(other) |
| 67 |
return super().__lt__(other) |
| 68 |
|
| 69 |
def __le__(self, other): |
| 70 |
self._check_min_supported(other) |
| 71 |
return super().__le__(other) |
| 72 |
|
| 73 |
def __gt__(self, other): |
| 74 |
self._check_min_supported(other) |
| 75 |
return super().__gt__(other) |
| 76 |
|
| 77 |
def __ge__(self, other): |
| 78 |
self._check_min_supported(other) |
| 79 |
return super().__ge__(other) |
| 80 |
|
| 81 |
|
| 82 |
vtk_version_info = VTKVersionInfo(*_get_vtk_version()) |
| 83 |
_MIN_SUPPORTED_VTK_VERSION = (9, 2, 2) |
| 84 |
|
| 85 |
|
| 86 |
class vtkPyVistaOverride: # noqa: N801 |
| 87 |
"""Base class to automatically override VTK classes with PyVista classes.""" |
| 88 |
|
| 89 |
def __init_subclass__(cls, **kwargs): |
| 90 |
if vtk_version_info >= (9, 4): |
| 91 |
# Check for VTK base classes and call the override method |
| 92 |
for base in cls.__bases__: |
| 93 |
if ( |
| 94 |
hasattr(base, '__module__') |
| 95 |
and base.__module__.startswith('vtkmodules.') |
| 96 |
and hasattr(base, 'override') |
| 97 |
): |
| 98 |
# For now, just remove any overrides for these classes |
| 99 |
# There are clear issues with the current implementation |
| 100 |
# of overriding these classes upstream and until they are |
| 101 |
# resolved, we will entirely remove the overrides. |
| 102 |
# See https://gitlab.kitware.com/vtk/vtk/-/merge_requests/11698 |
| 103 |
# See https://gitlab.kitware.com/vtk/vtk/-/issues/19550#note_1598883 |
| 104 |
base.override(None) |
| 105 |
break |
| 106 |
|
| 107 |
return cls |
| 108 |
|
| 109 |
|
| 110 |
_VTK_SNAKE_CASE_STATE: Literal['allow', 'warning', 'error'] = 'error' |
| 111 |
|
| 112 |
|
| 113 |
class DisableVtkSnakeCase: |
| 114 |
"""Base class to raise error if using VTK's `snake_case` API.""" |
| 115 |
|
| 116 |
@staticmethod |
| 117 |
def check_attribute(target, attr): |
| 118 |
# Skip check and exit early if possible |
| 119 |
if ( |
| 120 |
_VTK_SNAKE_CASE_STATE == 'allow' |
| 121 |
or not attr |
| 122 |
or not attr[0].islower() |
| 123 |
or attr in ('__class__', '__init__') |
| 124 |
or vtk_version_info < (9, 4) |
| 125 |
): |
| 126 |
return |
| 127 |
|
| 128 |
# Check if we have a vtk-defined attribute using cached lookup |
| 129 |
cls = target if isinstance(target, type) else target.__class__ |
| 130 |
if not _is_vtk_attribute_cached(cls, attr): |
| 131 |
return |
| 132 |
|
| 133 |
# We have a VTK attribute, so raise or warn |
| 134 |
if sys.meta_path is not None: # Avoid dynamic imports when Python is shutting down |
| 135 |
msg = f'The attribute {attr!r} is defined by VTK and is not part of the PyVista API' |
| 136 |
if _VTK_SNAKE_CASE_STATE == 'error': |
| 137 |
from pyvista import PyVistaAttributeError # noqa: PLC0415 |
| 138 |
|
| 139 |
raise PyVistaAttributeError(msg) |
| 140 |
else: |
| 141 |
warn_external(msg, RuntimeWarning) |
| 142 |
return |
| 143 |
|
| 144 |
def __getattribute__(self, item): |
| 145 |
DisableVtkSnakeCase.check_attribute(self, item) |
| 146 |
return object.__getattribute__(self, item) |
| 147 |
|
| 148 |
def __dir__(self) -> list[str]: |
| 149 |
"""Return a filtered attribute listing for :func:`dir` and tab-completion. |
| 150 |
|
| 151 |
VTK-inherited names are hidden by default so PyVista objects present |
| 152 |
a curated public surface in data-science IDEs (Positron Variables |
| 153 |
pane, VS Code Jupyter extension, ...) and in IPython / Jupyter |
| 154 |
tab-completion. VTK methods remain fully callable; only their |
| 155 |
enumeration is suppressed. |
| 156 |
|
| 157 |
- CamelCase VTK attributes (``GetNumberOfPoints``, ``DeepCopy``, ...) are |
| 158 |
hidden unless :attr:`pyvista.global_config.show_vtk_api` is |
| 159 |
``True``. |
| 160 |
- snake_case VTK aliases (``number_of_points``, ``deep_copy``, ...) are |
| 161 |
hidden unless VTK snake_case is allowed via |
| 162 |
:func:`pyvista.vtk_snake_case`, since they would otherwise raise |
| 163 |
``PyVistaAttributeError`` on access. |
| 164 |
""" |
| 165 |
cls: type = type(self) |
| 166 |
listing = super().__dir__() |
| 167 |
show_camel = global_config.show_vtk_api |
| 168 |
show_snake = _VTK_SNAKE_CASE_STATE == 'allow' |
| 169 |
if show_camel and show_snake: |
| 170 |
return sorted(listing) |
| 171 |
|
| 172 |
def keep(attr: str) -> bool: |
| 173 |
if not _is_vtk_attribute_cached(cls, attr): |
| 174 |
return True |
| 175 |
if attr and attr[0].islower(): |
| 176 |
return show_snake |
| 177 |
return show_camel |
| 178 |
|
| 179 |
return sorted(attr for attr in listing if keep(attr)) |
| 180 |
|
| 181 |
|
| 182 |
def is_vtk_attribute(obj: object, attr: str): # numpydoc ignore=RT01 |
| 183 |
"""Return True if the attribute is defined by a vtk class. |
| 184 |
|
| 185 |
Parameters |
| 186 |
---------- |
| 187 |
obj : object |
| 188 |
Class or instance to check. |
| 189 |
|
| 190 |
attr : str |
| 191 |
Name of the attribute to check. |
| 192 |
|
| 193 |
""" |
| 194 |
|
| 195 |
def _find_defining_class(cls, attr): |
| 196 |
"""Find the class that defines a given attribute.""" |
| 197 |
for base in cls.__mro__: |
| 198 |
if attr in base.__dict__: |
| 199 |
return base |
| 200 |
return None |
| 201 |
|
| 202 |
cls = _find_defining_class(obj if isinstance(obj, type) else obj.__class__, attr) |
| 203 |
return cls is not None and cls.__module__.startswith('vtkmodules') |
| 204 |
|
| 205 |
|
| 206 |
# Wrap the check in an LRU cache |
| 207 |
@cache |
| 208 |
def _is_vtk_attribute_cached(target_type, attr): |
| 209 |
return is_vtk_attribute(target_type, attr) |
| 210 |
|
| 211 |
|
| 212 |
class VTKObjectWrapperCheckSnakeCase(_vtk.VTKObjectWrapper): |
| 213 |
"""Superclass for classes that wrap VTK objects with Python objects. |
| 214 |
|
| 215 |
This class overrides __getattr__ to disable the VTK snake case API. |
| 216 |
""" |
| 217 |
|
| 218 |
def __getattr__(self, name: str): |
| 219 |
"""Forward unknown attribute requests to VTKArray's __getattr__.""" |
| 220 |
if self.VTKObject is not None: |
| 221 |
# Check if forwarding snake_case attributes |
| 222 |
DisableVtkSnakeCase.check_attribute(self.VTKObject, name) |
| 223 |
return getattr(self.VTKObject, name) |
| 224 |
raise AttributeError |