Debian Codegraph @

pyvista/core/utilities/misc.py

raw
1 """Miscellaneous core utilities."""
2
3 from __future__ import annotations
4
5 from abc import ABCMeta
6 from collections.abc import Sequence
7 import enum
8 from functools import cache
9 import importlib
10 from inspect import getattr_static
11 import sys
12 import threading
13 import traceback
14 from typing import TYPE_CHECKING
15 from typing import Literal
16 from typing import TypeVar
17
18 import numpy as np
19 from typing_extensions import Self
20
21 from pyvista import _vtk
22 from pyvista._warn_external import warn_external
23
24 if TYPE_CHECKING:
25 from typing import Any
26
27 from pyvista._typing_core import ArrayLike
28 from pyvista._typing_core import NumpyArray
29 from pyvista._typing_core import VectorLike
30
31 _T = TypeVar('_T')
32
33 T = TypeVar('T', bound='AnnotatedIntEnum')
34
35 _SMPBackendOptions = Literal['stdthread', 'tbb', 'openmp', 'sequential']
36 _SMP_BACKEND_NAMES: dict[str, str] = {
37 'stdthread': 'STDThread',
38 'tbb': 'TBB',
39 'openmp': 'OpenMP',
40 'sequential': 'Sequential',
41 }
42
43 if sys.version_info >= (3, 11):
44 from enum import StrEnum
45 else:
46 from enum import Enum
47
48 class StrEnum(str, Enum): # noqa: D101
49 def __str__(self) -> str:
50 return self.value
51
52
53 def assert_empty_kwargs(**kwargs) -> bool:
54 """Assert that all keyword arguments have been used (internal helper).
55
56 If any keyword arguments are passed, a ``TypeError`` is raised.
57
58 Parameters
59 ----------
60 **kwargs : dict
61 Keyword arguments passed to the function.
62
63 Returns
64 -------
65 bool
66 ``True`` when successful.
67
68 Raises
69 ------
70 TypeError
71 If any keyword arguments are passed, a ``TypeError`` is raised.
72
73 """
74 n = len(kwargs)
75 if n == 0:
76 return True
77 caller = sys._getframe(1).f_code.co_name
78 keys = list(kwargs.keys())
79 bad_arguments = ', '.join([f'"{key}"' for key in keys])
80 grammar = 'is an invalid keyword argument' if n == 1 else 'are invalid keyword arguments'
81 message = f'{bad_arguments} {grammar} for `{caller}`'
82 raise TypeError(message)
83
84
85 def check_valid_vector(point: VectorLike[float], name: str = '') -> None:
86 """Check if a vector contains three components.
87
88 Parameters
89 ----------
90 point : VectorLike[float]
91 Input vector to check. Must be an iterable with exactly three components.
92 name : str, optional
93 Name to use in the error messages. If not provided, "Vector" will be used.
94
95 Raises
96 ------
97 TypeError
98 If the input is not an iterable.
99 ValueError
100 If the input does not have exactly three components.
101
102 """
103 if not isinstance(point, (Sequence, np.ndarray)):
104 msg = f'{name} must be a length three iterable of floats.'
105 raise TypeError(msg)
106 if len(point) != 3:
107 if name == '':
108 name = 'Vector'
109 msg = f'{name} must be a length three iterable of floats.'
110 raise ValueError(msg)
111
112
113 def abstract_class(cls_): # noqa: ANN001, ANN201 # numpydoc ignore=RT01
114 """Decorate a class, overriding __new__.
115
116 Preventing a class from being instantiated similar to abc.ABCMeta
117 but does not require an abstract method.
118
119 Parameters
120 ----------
121 cls_ : type
122 The class to be decorated as abstract.
123
124 """
125
126 def __new__(cls, *args, **kwargs): # noqa: ANN001, ANN202, ARG001, N807
127 if cls is cls_:
128 msg = f'{cls.__name__} is an abstract class and may not be instantiated.'
129 raise TypeError(msg)
130 return super(cls_, cls).__new__(cls)
131
132 cls_.__new__ = __new__
133 return cls_
134
135
136 class AnnotatedIntEnum(int, enum.Enum):
137 """Annotated enum type."""
138
139 annotation: str
140
141 def __new__(cls, value: int, annotation: str) -> Self:
142 """Initialize."""
143 obj = int.__new__(cls, value)
144 obj._value_ = value
145 obj.annotation = annotation
146 return obj
147
148 @classmethod
149 def from_str(cls, input_str: str) -> Self:
150 """Create an enum member from a string.
151
152 Parameters
153 ----------
154 input_str : str
155 The string representation of the annotation for the enum member.
156
157 Returns
158 -------
159 AnnotatedIntEnum
160 The enum member with the specified annotation.
161
162 Raises
163 ------
164 ValueError
165 If there is no enum member with the specified annotation.
166
167 """
168 for value in cls:
169 if value.annotation.lower() == input_str.lower():
170 return value
171 msg = f'{cls.__name__} has no value matching {input_str}'
172 raise ValueError(msg)
173
174 @classmethod
175 def from_any(cls, value: AnnotatedIntEnum | int | str) -> Self:
176 """Create an enum member from a string, int, etc.
177
178 Parameters
179 ----------
180 value : int | str | AnnotatedIntEnum
181 The value used to determine the corresponding enum member.
182
183 Returns
184 -------
185 AnnotatedIntEnum
186 The enum member matching the specified value.
187
188 Raises
189 ------
190 ValueError
191 If there is no enum member matching the specified value.
192
193 """
194 if isinstance(value, cls):
195 return value
196 elif isinstance(value, int):
197 return cls(value) # type: ignore[call-arg]
198 elif isinstance(value, str):
199 return cls.from_str(value)
200 else:
201 msg = f'Invalid type {type(value)} for class {cls.__name__}.' # type: ignore[unreachable]
202 raise TypeError(msg)
203
204
205 @cache
206 def has_module(module_name: str) -> bool:
207 """Return if a module can be imported.
208
209 Parameters
210 ----------
211 module_name : str
212 Name of the module to check.
213
214 Returns
215 -------
216 bool
217 ``True`` if the module can be imported, otherwise ``False``.
218
219 """
220 module_spec = importlib.util.find_spec(module_name)
221 return module_spec is not None
222
223
224 class _SMPToolsContext:
225 """Context manager that restores VTK SMP backend state on exit."""
226
227 def __init__(self, original_backend: str, original_threads: int) -> None:
228 self._original_backend = original_backend
229 self._original_threads = original_threads
230
231 def __enter__(self) -> Self:
232 return self
233
234 def __exit__(self, *exc_info: object) -> None:
235 _vtk.vtkSMPTools.SetBackend(self._original_backend)
236 _vtk.vtkSMPTools.Initialize(self._original_threads)
237
238
239 def enable_smp_tools(
240 backend: _SMPBackendOptions = 'stdthread',
241 n_threads: int | None = None,
242 ) -> _SMPToolsContext:
243 """Enable a VTK SMP backend for filters that support shared-memory parallelism.
244
245 VTK's Python wheels currently default to the sequential SMP backend. This
246 helper switches to a parallel backend and optionally configures the maximum
247 number of threads used by VTK filters that rely on :vtk:`vtkSMPTools`.
248
249 The backend is applied immediately, so calling this function by itself
250 enables the chosen backend for the rest of the process. The return value is
251 also a context manager, so using it with a ``with`` statement will restore
252 the previous backend and thread count on exit.
253
254 Parameters
255 ----------
256 backend : str, default: 'stdthread'
257 SMP backend to enable. Acceptable values are:
258
259 - ``'stdthread'``: Enable VTK's ``std::thread`` backend. This is the
260 default and is available in the current VTK wheels.
261 - ``'tbb'``: Enable Intel oneTBB when available in the current VTK
262 build.
263 - ``'openmp'``: Enable OpenMP when available in the current VTK build.
264 - ``'sequential'``: Use VTK's sequential backend.
265
266 n_threads : int, optional
267 Maximum number of threads to use. If not provided, VTK resets to its
268 default maximum thread count and honors the ``VTK_SMP_MAX_THREADS``
269 environment variable when it is set.
270
271 Returns
272 -------
273 contextlib.AbstractContextManager
274 A context manager that restores the previous SMP backend and thread
275 count when exited. The return value may be discarded when the change
276 should apply for the remainder of the process.
277
278 Raises
279 ------
280 TypeError
281 If ``backend`` is not a string or if ``n_threads`` is not an integer.
282
283 ValueError
284 If ``backend`` is invalid or if ``n_threads`` is less than ``1``.
285
286 RuntimeError
287 If this VTK build does not support runtime SMP backend selection, or if
288 the requested backend is unavailable.
289
290 Examples
291 --------
292 Enable the wheel-supported ``stdthread`` backend for the rest of the
293 process.
294
295 >>> import pyvista as pv
296 >>> pv.enable_smp_tools() # doctest:+SKIP
297
298 Configure the backend before running a contour filter.
299
300 >>> from pyvista import examples
301 >>> pv.enable_smp_tools(n_threads=8) # doctest:+SKIP
302 >>> grid = examples.download_fea_bracket() # doctest:+SKIP
303 >>> _ = grid.contour(5, scalars='Equivalent Stress') # doctest:+SKIP
304
305 Scope the backend change to a ``with`` block. The previous backend and
306 thread count are restored on exit, even if an exception is raised.
307
308 >>> with pv.enable_smp_tools(n_threads=8): # doctest:+SKIP
309 ... _ = grid.contour(5, scalars='Equivalent Stress')
310
311 """
312 if not isinstance(backend, str):
313 msg = '`backend` must be a string.' # type: ignore[unreachable]
314 raise TypeError(msg)
315
316 backend_key = backend.lower()
317 vtk_backend = _SMP_BACKEND_NAMES.get(backend_key)
318 if vtk_backend is None:
319 valid_backends = ', '.join(f'`{name}`' for name in _SMP_BACKEND_NAMES)
320 msg = f'Invalid SMP backend `{backend}`. Valid options are: {valid_backends}.'
321 raise ValueError(msg)
322
323 if n_threads is not None:
324 if isinstance(n_threads, bool) or not isinstance(n_threads, (int, np.integer)):
325 msg = '`n_threads` must be an integer.'
326 raise TypeError(msg)
327 if n_threads < 1:
328 msg = '`n_threads` must be greater than or equal to 1.'
329 raise ValueError(msg)
330 n_threads_ = int(n_threads)
331 else:
332 n_threads_ = None
333
334 if not hasattr(_vtk, 'vtkSMPTools') or not hasattr(_vtk.vtkSMPTools, 'SetBackend'):
335 msg = 'This VTK build does not support runtime SMP backend selection.'
336 raise RuntimeError(msg)
337
338 original_backend = _vtk.vtkSMPTools.GetBackend()
339 original_threads = _vtk.vtkSMPTools.GetEstimatedNumberOfThreads()
340
341 available = _vtk.vtkSMPTools.SetBackend(vtk_backend)
342 if not available:
343 _vtk.vtkSMPTools.SetBackend(original_backend)
344 _vtk.vtkSMPTools.Initialize(original_threads)
345 msg = f'The requested SMP backend `{backend_key}` is not available in this VTK build.'
346 raise RuntimeError(msg)
347
348 if n_threads_ is None:
349 _vtk.vtkSMPTools.Initialize()
350 else:
351 _vtk.vtkSMPTools.Initialize(n_threads_)
352
353 return _SMPToolsContext(original_backend, original_threads)
354
355
356 def try_callback(func, *args) -> None: # noqa: ANN001
357 """Wrap a given callback in a try statement.
358
359 Parameters
360 ----------
361 func : callable
362 Callable object.
363
364 *args
365 Any arguments.
366
367 """
368 try:
369 func(*args)
370 except Exception: # noqa: BLE001 # pragma: no cover
371 etype, exc, tb = sys.exc_info()
372 stack = traceback.extract_tb(tb)[1:]
373 formatted_exception = 'Encountered issue in callback (most recent call last):\n' + ''.join(
374 traceback.format_list(stack) + traceback.format_exception_only(etype, exc),
375 ).rstrip('\n')
376 warn_external(formatted_exception)
377
378
379 def threaded(fn): # noqa: ANN001, ANN201
380 """Call a function using a thread.
381
382 Parameters
383 ----------
384 fn : callable
385 Callable object.
386
387 Returns
388 -------
389 function
390 Wrapped function.
391
392 """
393
394 def wrapper(*args, **kwargs): # noqa: ANN202
395 thread = threading.Thread(target=fn, args=args, kwargs=kwargs)
396 thread.start()
397 return thread
398
399 return wrapper
400
401
402 class conditional_decorator: # noqa: N801
403 """Conditional decorator for methods.
404
405 Parameters
406 ----------
407 dec : callable
408 The decorator to be applied conditionally.
409 condition : bool
410 Condition to match. If ``True``, the decorator is applied. If
411 ``False``, the function is returned unchanged.
412
413 """
414
415 def __init__(self, dec, condition) -> None: # noqa: ANN001
416 """Initialize."""
417 self.decorator = dec
418 self.condition = condition
419
420 def __call__(self, func): # noqa: ANN001, ANN204
421 """Call the decorated function if condition is matched."""
422 if not self.condition:
423 # Return the function unchanged, not decorated.
424 return func
425 return self.decorator(func)
426
427
428 def _check_range(value: float, rng: Sequence[float], parm_name: str) -> None:
429 """Check if a parameter is within a range."""
430 if value < rng[0] or value > rng[1]:
431 msg = (
432 f'The value {float(value)} for `{parm_name}` is outside the '
433 f'acceptable range {tuple(rng)}.'
434 )
435 raise ValueError(msg)
436
437
438 class _AutoFreezeMeta(type):
439 """Metaclass to automatically freeze a class when called."""
440
441 def __call__(cls: type[_T], *args, **kwargs) -> _T:
442 obj = super().__call__(*args, **kwargs) # type: ignore[misc]
443 obj._no_new_attributes(cls)
444 return obj
445
446
447 class _AutoFreezeABCMeta(_AutoFreezeMeta, ABCMeta):
448 """Metaclass to combine automatic attribute freezing with ABC support."""
449
450
451 class _DataObjectMeta(_AutoFreezeABCMeta):
452 """Metaclass for ``DataObject`` that resolves accessor entry-points on class access.
453
454 Without this hook, class-level attribute access (e.g. ``pv.PolyData.manifold``)
455 bypasses lazy loading of ``pyvista.accessors`` entry-point plugins and raises
456 ``AttributeError`` until the plugin happens to be imported some other way.
457 Instance access is handled by ``DataObject.__getattr__``.
458 """
459
460 def __getattr__(cls, name: str) -> Any:
461 from pyvista.core.utilities.accessor_registry import ( # noqa: PLC0415
462 _resolve_pending_accessor,
463 )
464
465 if _resolve_pending_accessor(name):
466 return getattr(cls, name)
467 msg = f'type object {cls.__name__!r} has no attribute {name!r}'
468 raise AttributeError(msg)
469
470
471 def _hasattr_static(obj: Any, attr: str) -> bool:
472 """Replicate behavior of hasattr using static lookup."""
473 try:
474 getattr_static(obj, attr)
475 except AttributeError:
476 return False
477 return True
478
479
480 class _NoNewAttrMixin(metaclass=_AutoFreezeABCMeta):
481 """Mixin to prevent adding new attributes.
482
483 This class is mainly used to prevent users from setting the wrong attributes on an
484 object. It freezes the attributes when called and prevents setting new ones via
485 "normal" methods like ``obj.foo = 42``.
486 """
487
488 def _no_new_attributes(self, this_class: type) -> None:
489 """Prevent setting additional attributes."""
490 object.__setattr__(self, '__frozen', True)
491 object.__setattr__(self, '__frozen_by_class', this_class)
492
493 def _check_new_attribute(self, key: str) -> None:
494 # Check sys.meta_path to avoid dynamic imports when Python is shutting down
495 if sys.meta_path is not None:
496 # Get mode for setting new attributes
497 try:
498 from pyvista import _ALLOW_NEW_ATTRIBUTES_MODE # noqa: PLC0415
499 except ImportError:
500 # Circular import, set to False to disallow new attributes during initial import
501 _ALLOW_NEW_ATTRIBUTES_MODE = False
502
503 # Check if setting a new attribute is allowed
504 if not (
505 _ALLOW_NEW_ATTRIBUTES_MODE is True
506 or (key.startswith('_') and _ALLOW_NEW_ATTRIBUTES_MODE == 'private')
507 ):
508 # Check if this class froze itself. Any frozen state already set by parent classes,
509 # e.g. by calling super().__init__(), will be ignored. This allows subclasses to
510 # set attributes during init without being affected by a parent class init.
511 frozen = self.__dict__.get('__frozen', False)
512 frozen_by = self.__dict__.get('__frozen_by_class', None)
513 if (
514 frozen
515 and frozen_by is type(self)
516 and not (key in type(self).__dict__ or _hasattr_static(self, key))
517 ):
518 from pyvista import PyVistaAttributeError # noqa: PLC0415
519
520 msg = (
521 f'Attribute {key!r} does not exist and cannot be added to class '
522 f'{self.__class__.__name__!r}\nUse `pyvista.set_new_attribute` '
523 f'or `pyvista.allow_new_attributes` to set new attributes.\n'
524 f'Setting new private variables (with `_` prefix) is allowed by default.'
525 )
526 raise PyVistaAttributeError(msg)
527
528 def __setattr__(self, key: str, value: Any) -> None:
529 """Prevent adding new attributes to classes using "normal" methods."""
530 self._check_new_attribute(key)
531 object.__setattr__(self, key, value)
532
533
534 def set_new_attribute(obj: object, name: str, value: Any) -> None:
535 """Set a new attribute for this object.
536
537 Python allows arbitrarily setting new attributes on objects at any time,
538 but PyVista's classes do not allow this. If an attribute is not part of
539 PyVista's API, an ``AttributeError`` is normally raised when attempting
540 to set it.
541
542 Use :func:`set_new_attribute` to override this and set a new attribute anyway.
543
544 See Also
545 --------
546 pyvista.allow_new_attributes
547 Context manager for controlling if setting new attributes is allowed.
548
549 Examples
550 --------
551 Set a new custom attribute on a mesh.
552
553 >>> import pyvista as pv
554 >>> mesh = pv.PolyData()
555 >>> pv.set_new_attribute(mesh, 'foo', 42)
556 >>> mesh.foo
557 42
558
559 This is equivalent to using :data:`allow_new_attributes` with ``True``.
560
561 >>> with pv.allow_new_attributes(True):
562 ... mesh.foo = 42
563
564 .. versionadded:: 0.46
565
566 """
567 if hasattr(obj, name):
568 from pyvista import PyVistaAttributeError # noqa: PLC0415
569
570 msg = (
571 f'Attribute {name!r} already exists. '
572 '`set_new_attribute` can only be used for setting NEW attributes.'
573 )
574 raise PyVistaAttributeError(msg)
575 object.__setattr__(obj, name, value)
576
577
578 def _reciprocal(
579 x: ArrayLike[float], tol: float = 1e-8, value_if_division_by_zero: float = 0.0
580 ) -> NumpyArray[float]:
581 """Compute the element-wise reciprocal and avoid division by zero.
582
583 The reciprocal of elements with an absolute value less than a
584 specified tolerance has the value specified by ``default_if_div_by_zero``.
585
586 Parameters
587 ----------
588 x : array_like
589 Input array.
590 tol : float
591 Tolerance value. Values smaller than ``tol`` have a reciprocal of zero.
592 value_if_division_by_zero : float
593 Default value given to values less than ``tol``, i.e. the value given if division
594 by zero is detected.
595
596 Returns
597 -------
598 numpy.ndarray
599 Element-wise reciprocal of the input.
600
601 """
602 x = np.array(x)
603 x = x if np.issubdtype(x.dtype, np.floating) else x.astype(float)
604 zero = np.abs(x) < tol
605 x[~zero] = np.reciprocal(x[~zero])
606 x[zero] = value_if_division_by_zero
607 return x
608
609
610 class _classproperty(property): # noqa: N801
611 """Read-only class property decorator.
612
613 Use this decaorator as an alternative to chaining `@classmethod`
614 and `@property` which is deprecated.
615
616 See:
617 - https://docs.python.org/library/functions.html#classmethod
618 - https://stackoverflow.com/a/13624858
619
620 Examples
621 --------
622 >>> from pyvista.core.utilities.misc import _classproperty
623 >>> class Foo:
624 ... @_classproperty
625 ... def bar(cls): ...
626
627 """
628
629 def __get__(self: property, owner_self: Any, owner_cls: type | None = None) -> Any:
630 return self.fget(owner_cls) # type: ignore[misc]
631
632
633 class _NameMixin:
634 """Add a 'name' property to a class.
635
636 .. versionadded:: 0.45
637
638 """
639
640 @property
641 def name(self) -> str: # numpydoc ignore=RT01
642 """Get or set the unique name identifier used by PyVista."""
643 if not hasattr(self, '_name') or self._name is None:
644 address = (
645 self.GetAddressAsString('')
646 if hasattr(self, 'GetAddressAsString')
647 else hex(id(self))
648 )
649 return f'{type(self).__name__}({address})'
650 return self._name
651
652 @name.setter
653 def name(self, value: str) -> None:
654 if not value:
655 msg = 'Name must be truthy.'
656 raise ValueError(msg)
657 object.__setattr__(self, '_name', str(value))
658
659
660 class _BoundsSizeMixin:
661 @property
662 def bounds_size(self) -> tuple[float, float, float]:
663 """Return the size of each axis of the object's bounding box.
664
665 .. versionadded:: 0.46
666
667 Returns
668 -------
669 tuple[float, float, float]
670 Size of each x-y-z axis.
671
672 Examples
673 --------
674 Get the size of a cube. The cube has edge lengths af ``(1.0, 1.0, 1.0)``
675 by default.
676
677 >>> import pyvista as pv
678 >>> mesh = pv.Cube()
679 >>> mesh.bounds_size
680 (1.0, 1.0, 1.0)
681
682 """
683 bounds = self.bounds # type: ignore[attr-defined]
684 return (
685 bounds.x_max - bounds.x_min,
686 bounds.y_max - bounds.y_min,
687 bounds.z_max - bounds.z_min,
688 )