Debian Codegraph @

pyvista/core/_validation/validate.py

raw
1 """Functions that validate input and return a standard representation.
2
3 .. versionadded:: 0.43.0
4
5 A ``validate`` function typically:
6
7 * Uses :py:mod:`~pyvista.core._validation.check` functions to
8 check the type and/or value of input arguments.
9 * Applies (optional) constraints, e.g. input or output must have a
10 specific length, shape, type, data-type, etc.
11 * Accepts many different input types or values and standardizes the
12 output as a single representation with known properties.
13
14 """
15
16 from __future__ import annotations
17
18 import inspect
19 from itertools import product
20 import reprlib
21 from typing import TYPE_CHECKING
22 from typing import Any
23 from typing import Literal
24
25 import numpy as np
26
27 from pyvista import _vtk
28 from pyvista.core._validation import check_contains
29 from pyvista.core._validation import check_finite
30 from pyvista.core._validation import check_integer
31 from pyvista.core._validation import check_length
32 from pyvista.core._validation import check_ndim
33 from pyvista.core._validation import check_nonnegative
34 from pyvista.core._validation import check_range
35 from pyvista.core._validation import check_real
36 from pyvista.core._validation import check_shape
37 from pyvista.core._validation import check_sorted
38 from pyvista.core._validation import check_string
39 from pyvista.core._validation import check_subdtype
40 from pyvista.core._validation._cast_array import _cast_to_numpy
41 from pyvista.core._validation._cast_array import _cast_to_tuple
42
43 if TYPE_CHECKING:
44 from collections.abc import Sequence
45
46 import numpy.typing as npt
47
48 from pyvista.core._typing_core import ArrayLike
49 from pyvista.core._typing_core import MatrixLike
50 from pyvista.core._typing_core import RotationLike
51 from pyvista.core._typing_core import TransformLike
52 from pyvista.core._typing_core import VectorLike
53 from pyvista.core._typing_core._array_like import NumpyArray
54 from pyvista.plotting._typing import ColorLike
55 from pyvista.plotting.colors import Color
56
57 from .check import _ShapeLike
58
59
60 def validate_array(
61 arr: float | ArrayLike[float],
62 /,
63 *,
64 must_have_shape: _ShapeLike | list[_ShapeLike] | None = None,
65 must_have_ndim: int | VectorLike[int] | None = None,
66 must_have_dtype: npt.DTypeLike | None = None,
67 must_have_length: int | VectorLike[int] | None = None,
68 must_have_min_length: int | None = None,
69 must_have_max_length: int | None = None,
70 must_be_nonnegative: bool = False,
71 must_be_finite: bool = False,
72 must_be_real: bool = True,
73 must_be_integer: bool = False,
74 must_be_sorted: bool | dict[str, Any] = False,
75 must_be_in_range: VectorLike[float] | None = None,
76 strict_lower_bound: bool = False,
77 strict_upper_bound: bool = False,
78 reshape_to: int | tuple[int, ...] | None = None,
79 broadcast_to: int | tuple[int, ...] | None = None,
80 dtype_out: npt.DTypeLike = None,
81 as_any: bool = True,
82 copy: bool = False,
83 to_list: bool = False,
84 to_tuple: bool = False,
85 name: str = 'Array',
86 ):
87 """Check and validate a numeric array meets specific requirements.
88
89 Validate an array to ensure it is numeric, has a specific shape,
90 data-type, and/or has values that meet specific
91 requirements such as being sorted, integer-like, or finite.
92
93 The array's output can also be reshaped or broadcast, cast as a
94 nested tuple or list array, or cast to a specific data type.
95
96 See Also
97 --------
98 validate_number
99 Specialized function for single numbers.
100
101 validate_array3
102 Specialized function for 3-element arrays.
103
104 validate_arrayN
105 Specialized function for one-dimensional arrays.
106
107 validate_arrayNx3
108 Specialized function for Nx3 dimensional arrays.
109
110 validate_data_range
111 Specialized function for data ranges.
112
113 Parameters
114 ----------
115 arr : array_like
116 Array to be validated, in any form that can be converted to
117 a :class:`np.ndarray`. This includes lists, lists of tuples, tuples,
118 tuples of tuples, tuples of lists and ndarrays.
119
120 must_have_shape : int | tuple[int, ...] | list[int, tuple[int, ...]], optional
121 :func:`Check <pyvista.core._validation.check.check_shape>`
122 if the array has a specific shape. Specify a single shape
123 or a ``list`` of any allowable shapes. If an integer, the array must
124 be 1-dimensional with that length. Use a value of ``-1`` for any
125 dimension where its size is allowed to vary. Use ``()`` to allow
126 scalar values (i.e. 0-dimensional). Set to ``None`` if the array
127 can have any shape (default).
128
129 must_have_ndim : int | VectorLike[int], optional
130 :func:`Check <pyvista.core._validation.check.check_ndim>` if
131 the array has the specified number of dimension(s). Specify a
132 single dimension or a sequence of allowable dimensions. If a
133 sequence, the array must have at least one of the specified
134 number of dimensions.
135
136 must_have_dtype : DTypeLike | list[DTypeLike, ...], optional
137 :func:`Check <pyvista.core._validation.check.check_subdtype>`
138 if the array's data-type has the given dtype. Specify a
139 :class:`np.dtype` object or dtype-like base class which the
140 array's data must be a subtype of. If a ``list``, the array's data
141 must be a subtype of at least one of the specified dtypes.
142
143 must_have_length : int | VectorLike[int], optional
144 :func:`Check <pyvista.core._validation.check.check_length>`
145 if the array has the given length. If multiple values are given,
146 the array's length must match one of the values.
147
148 .. note ::
149
150 The array's length is determined after reshaping the array
151 (if ``reshape`` is not ``None``) and after broadcasting (if
152 ``broadcast_to`` is not ``None``). Therefore, the values of
153 `length`` should take the array's new shape into
154 consideration if applicable.
155
156 must_have_min_length : int, optional
157 :func:`Check <pyvista.core._validation.check.check_length>`
158 if the array's length is this value or greater.
159
160 must_have_max_length : int, optional
161 :func:`Check <pyvista.core._validation.check.check_length>`
162 if the array' length is this value or less.
163
164 must_be_nonnegative : bool, default: False
165 :func:`Check <pyvista.core._validation.check.check_nonnegative>`
166 if all elements of the array are nonnegative.
167
168 must_be_finite : bool, default: False
169 :func:`Check <pyvista.core._validation.check.check_finite>`
170 if all elements of the array are finite, i.e. not ``infinity``
171 and not Not a Number (``NaN``).
172
173 must_be_real : bool, default: True
174 :func:`Check <pyvista.core._validation.check.check_real>`
175 if the array has real numbers, i.e. its data type is integer or
176 floating.
177
178 must_be_integer : bool, default: False
179 :func:`Check <pyvista.core._validation.check.check_integer>`
180 if the array's values are integer-like (i.e. that
181 ``np.all(arr, np.floor(arr))``).
182
183 must_be_sorted : bool | dict, default: False
184 :func:`Check <pyvista.core._validation.check.check_sorted>`
185 if the array's values are sorted. If ``True``, the check is
186 performed with default parameters:
187
188 * ``ascending=True``: the array must be sorted in ascending order
189 * ``strict=False``: sequential elements with the same value are allowed
190 * ``axis=-1``: the sorting is checked along the array's last axis
191
192 To check for descending order, enforce strict ordering, or to check
193 along a different axis, use a ``dict`` with keyword arguments that
194 will be passed to ``check_sorted``.
195
196 must_be_in_range : VectorLike[float], optional
197 :func:`Check <pyvista.core._validation.check.check_range>`
198 if the array's values are all within a specific range. Range
199 must be array-like with two elements specifying the minimum and
200 maximum data values allowed, respectively. By default, the range
201 endpoints are inclusive, i.e. values must be >= minimum and <=
202 maximum. Use ``strict_lower_bound`` and/or ``strict_upper_bound``
203 to further restrict the allowable range.
204
205 ..note ::
206
207 Use ``np.inf`` to check for open intervals, e.g.:
208
209 * ``[-np.inf, upper_bound]`` to check if values are less
210 than (or equal to) ``upper_bound``
211 * ``[lower_bound, np.inf]`` to check if values are greater
212 than (or equal to) ``lower_bound``
213
214 strict_lower_bound : bool, default: False
215 Enforce a strict lower bound for the range specified by
216 ``must_be_in_range``, i.e. array values must be strictly greater
217 than the specified minimum.
218
219 strict_upper_bound : bool, default: False
220 Enforce a strict upper bound for the range specified by
221 ``must_be_in_range``, i.e. array values must be strictly less
222 than the specified maximum.
223
224 reshape_to : int | tuple[int, ...], optional
225 Reshape the output array to a new shape with :func:`np.reshape`.
226 The shape should be compatible with the original shape. If an
227 integer, then the result will be a 1-D array of that length. One
228 shape dimension can be -1.
229
230 broadcast_to : int | tuple[int, ...], optional
231 Broadcast the array with :func:`np.broadcast_to` to a
232 read-only view with the specified shape. Broadcasting is done
233 after reshaping (if ``reshape_to`` is not ``None``).
234
235 dtype_out : DTypeLike, optional
236 Set the data-type of the returned array. By default, the
237 dtype is inferred from the input data.
238
239 as_any : bool, default: True
240 Allow subclasses of ``np.ndarray`` to pass through without
241 making a copy.
242
243 copy : bool, default: False
244 If ``True``, a copy of the array is returned. A copy is always
245 returned if the array:
246
247 * is a nested sequence
248 * is a subclass of ``np.ndarray`` and ``as_any`` is ``False``.
249
250 A copy may also be made to satisfy ``dtype_out`` requirements.
251
252 to_list : bool, default: False
253 Return the validated array as a ``list`` or nested ``list``. Scalar
254 values are always returned as a ``Number`` (i.e. ``int`` or ``float``).
255 Has no effect if ``to_tuple=True``.
256
257 to_tuple : bool, default: False
258 Return the validated array as a ``tuple`` or nested ``tuple``. Scalar
259 values are always returned as a ``Number`` (i.e. ``int`` or ``float``).
260
261 name : str, default: "Array"
262 Variable name to use in the error messages if any of the
263 validation checks fail.
264
265 Returns
266 -------
267 array_like
268 Validated array. Returned object is:
269
270 * an instance of ``np.ndarray`` (default), or
271 * a nested ``list`` (if ``to_list=True``), or
272 * a nested ``tuple`` (if ``to_tuple=True``), or
273 * a ``Number`` (i.e. ``int`` or ``float``) if the input is a scalar.
274
275 Examples
276 --------
277 Validate a one-dimensional array has at least length two, is
278 monotonically increasing (i.e. has strict ascending order), and
279 is within some range.
280
281 >>> from pyvista import _validation
282 >>> array_in = (1, 2, 3, 5, 8, 13)
283 >>> rng = (0, 20)
284 >>> _validation.validate_array(
285 ... array_in,
286 ... must_have_shape=(-1),
287 ... must_have_min_length=2,
288 ... must_be_sorted=dict(strict=True),
289 ... must_be_in_range=rng,
290 ... )
291 array([ 1, 2, 3, 5, 8, 13])
292
293 """
294 arr_out = _cast_to_numpy(arr, as_any=as_any, copy=copy)
295
296 # Check type
297 if must_be_real:
298 check_real(arr_out, name=name)
299
300 if must_have_dtype is not None:
301 check_subdtype(arr_out, must_have_dtype, name=name)
302
303 # Check shape
304 if must_have_shape is not None:
305 check_shape(arr_out, must_have_shape, name=name)
306 if must_have_ndim is not None:
307 check_ndim(arr_out, ndim=must_have_ndim, name=name)
308
309 # Do reshape _after_ checking shape to prevent unexpected reshaping
310 if reshape_to is not None and arr_out.shape != reshape_to:
311 arr_out = arr_out.reshape(reshape_to)
312
313 if broadcast_to is not None and arr_out.shape != broadcast_to:
314 arr_out = np.broadcast_to(arr_out, broadcast_to, subok=True)
315
316 # Check length _after_ reshaping otherwise length may be wrong
317 if (
318 must_have_length is not None
319 or must_have_min_length is not None
320 or must_have_max_length is not None
321 ):
322 check_length(
323 arr,
324 exact_length=must_have_length,
325 min_length=must_have_min_length,
326 max_length=must_have_max_length,
327 allow_scalar=True,
328 name=name,
329 )
330
331 # Check data values
332 if must_be_nonnegative:
333 check_nonnegative(arr_out, name=name)
334 if must_be_finite:
335 check_finite(arr_out, name=name)
336 if must_be_integer:
337 check_integer(arr_out, strict=False, name=name)
338 if must_be_in_range is not None:
339 check_range(
340 arr_out,
341 must_be_in_range,
342 strict_lower=strict_lower_bound,
343 strict_upper=strict_upper_bound,
344 name=name,
345 )
346 if must_be_sorted:
347 if isinstance(must_be_sorted, dict):
348 check_sorted(arr_out, **must_be_sorted, name=name)
349 else:
350 check_sorted(arr_out, name=name)
351
352 # Process output
353 if dtype_out is not None:
354 # Copy was done earlier, so don't do it again here
355 arr_out = arr_out.astype(dtype_out, copy=False)
356 if to_tuple:
357 return _cast_to_tuple(arr_out)
358 if to_list:
359 return arr_out.tolist()
360 return arr_out
361
362
363 def validate_axes(
364 *axes: VectorLike[float] | MatrixLike[float],
365 normalize: bool = True,
366 must_be_orthogonal: bool = True,
367 must_have_orientation: Literal['right', 'left'] | None = 'right',
368 name: str = 'Axes',
369 ):
370 """Validate 3D axes vectors.
371
372 By default, the axes are normalized and checked to ensure they are orthogonal and
373 have a right-handed orientation.
374
375 Parameters
376 ----------
377 *axes : VectorLike[float] | MatrixLike[float]
378 Axes to be validated. Axes may be specified as a single argument of a 3x3
379 array of row vectors or as separate arguments for each 3-element axis vector.
380 If only two vectors are given and ``must_have_orientation`` is not ``None``,
381 the third vector is automatically calculated as the cross-product of the
382 two vectors such that the axes have the correct orientation.
383
384 normalize : bool, default: True
385 If ``True``, the axes vectors are individually normalized to each have a norm
386 of 1.
387
388 must_be_orthogonal : bool, default: True
389 Check if the axes are orthogonal. If ``True``, the cross product between any
390 two axes vectors must be parallel to the third.
391
392 must_have_orientation : str, default: 'right'
393 Check if the axes have a specific orientation. If ``right``, the
394 cross-product of the first axis vector with the second must have a positive
395 direction. If ``left``, the direction must be negative. If ``None``, the
396 orientation is not checked.
397
398 name : str, default: "Axes"
399 Variable name to use in the error messages if any of the
400 validation checks fail.
401
402 Returns
403 -------
404 np.ndarray
405 Validated 3x3 axes array of row vectors.
406
407 Examples
408 --------
409 Validate an axes array.
410
411 >>> import numpy as np
412 >>> from pyvista import _validation
413 >>> _validation.validate_axes(np.eye(3))
414 array([[1., 0., 0.],
415 [0., 1., 0.],
416 [0., 0., 1.]])
417
418 Validate individual axes vectors as a 3x3 array.
419
420 >>> _validation.validate_axes([1, 0, 0], [0, 1, 0], [0, 0, 1])
421 array([[1., 0., 0.],
422 [0., 1., 0.],
423 [0., 0., 1.]])
424
425 Create a validated left-handed axes array from two vectors.
426
427 >>> _validation.validate_axes(
428 ... [1, 0, 0], [0, 1, 0], must_have_orientation='left'
429 ... )
430 array([[ 1., 0., 0.],
431 [ 0., 1., 0.],
432 [ 0., 0., -1.]])
433
434 """
435 # Validate number of args
436 check_length(axes, exact_length=[1, 2, 3], name=f'{name} arguments')
437 if must_have_orientation is not None:
438 check_contains(
439 ['right', 'left'],
440 must_contain=must_have_orientation,
441 name=f'{name} orientation',
442 )
443 elif len(axes) == 2:
444 msg = f'{name} orientation must be specified when only two vectors are given.'
445 raise ValueError(msg)
446
447 # Validate axes array
448 if len(axes) == 1:
449 axes_array = validate_array(axes[0], must_have_shape=(3, 3), name=name)
450 else:
451 axes_array = np.zeros((3, 3))
452 axes_array[0] = validate_array3(axes[0], name=f'{name} Vector[0]')
453 axes_array[1] = validate_array3(axes[1], name=f'{name} Vector[1]')
454 if len(axes) == 3:
455 axes_array[2] = validate_array3(axes[2], name=f'{name} Vector[2]')
456 elif must_have_orientation == 'right':
457 axes_array[2] = np.cross(axes_array[0], axes_array[1])
458 else:
459 axes_array[2] = np.cross(axes_array[1], axes_array[0])
460 check_finite(axes_array, name=name)
461
462 if np.isclose(np.dot(axes_array[0], axes_array[1]), 1) or np.isclose(
463 np.dot(axes_array[0], axes_array[2]),
464 1,
465 ):
466 msg = f'{name} cannot be parallel.'
467 raise ValueError(msg)
468 if np.any(np.all(np.isclose(axes_array, np.zeros(3)), axis=1)):
469 msg = f'{name} cannot be zeros.'
470 raise ValueError(msg)
471
472 # Check orthogonality and orientation using cross products
473 # Normalize axes first since norm values are needed for cross product calc
474 axes_norm = axes_array / np.linalg.norm(axes_array, axis=1).reshape((3, 1))
475 cross_0_1 = np.cross(axes_norm[0], axes_norm[1])
476 cross_1_2 = np.cross(axes_norm[1], axes_norm[2])
477
478 if must_be_orthogonal and not (
479 (np.allclose(cross_0_1, axes_norm[2]) or np.allclose(cross_0_1, -axes_norm[2]))
480 and (np.allclose(cross_1_2, axes_norm[0]) or np.allclose(cross_1_2, -axes_norm[0]))
481 ):
482 msg = f'{name} are not orthogonal.'
483 raise ValueError(msg)
484
485 if must_have_orientation:
486 dot = np.dot(cross_0_1, axes_norm[2])
487 if must_have_orientation == 'right' and dot < 0:
488 msg = f'{name} do not have a right-handed orientation.'
489 raise ValueError(msg)
490 if must_have_orientation == 'left' and dot > 0:
491 msg = f'{name} do not have a left-handed orientation.'
492 raise ValueError(msg)
493
494 if normalize:
495 return axes_norm
496 return axes_array
497
498
499 def validate_rotation(
500 rotation: RotationLike,
501 must_have_handedness: Literal['right', 'left'] | None = None,
502 *,
503 tolerance: float = 1e-6,
504 name: str = 'Rotation',
505 ):
506 """Validate a rotation as a 3x3 matrix.
507
508 The rotation is valid if it is orthogonal and has a determinant
509 of ``1`` (right-handed or "proper" rotation) or ``-1`` (left-handed or "improper"
510 rotation). By default, right- and left-handed rotations are allowed.
511 Use ``must_have_handedness`` to restrict the handedness.
512
513 Parameters
514 ----------
515 rotation : RotationLike
516 3x3 rotation matrix or a SciPy ``Rotation`` object.
517
518 must_have_handedness : 'right' | 'left' | None, default: None
519 Check if the rotation has a specific handedness. If ``right``, the
520 determinant must be ``1``. If ``left``, the determinant must be ``-1``.
521 By default, either handedness is allowed.
522
523 tolerance : float, default: 1e-6
524 Tolerance used for checking orthogonality.
525
526 name : str, default: "Rotation"
527 Variable name to use in the error messages if any of the
528 validation checks fail.
529
530 Returns
531 -------
532 np.ndarray
533 Validated 3x3 rotation matrix.
534
535 Examples
536 --------
537 Validate a rotation matrix. The identity matrix is used as a toy example.
538
539 >>> import numpy as np
540 >>> from pyvista import _validation
541 >>> rotation = np.eye(3)
542 >>> _validation.validate_rotation(rotation)
543 array([[1., 0., 0.],
544 [0., 1., 0.],
545 [0., 0., 1.]])
546
547 By default, left-handed rotations (which include reflections) are allowed.
548
549 >>> rotation *= -1 # Add reflections
550 >>> _validation.validate_rotation(rotation)
551 array([[-1., -0., -0.],
552 [-0., -1., -0.],
553 [-0., -0., -1.]])
554
555 """
556 check_contains(
557 ['right', 'left', None], must_contain=must_have_handedness, name='must_have_handedness'
558 )
559
560 rotation_matrix = validate_transform3x3(rotation, name=name)
561 # Check orthogonality
562 # A matrix M is orthogonal if the product of M with its transpose is the identity
563 norm_diff = np.linalg.norm(rotation_matrix @ rotation_matrix.T - np.eye(3), ord='fro')
564 if not norm_diff < tolerance:
565 msg = f'{name} is not valid. Rotation must be orthogonal.'
566 raise ValueError(msg)
567
568 if must_have_handedness is not None:
569 det = np.linalg.det(rotation_matrix)
570 if must_have_handedness == 'right' and not det > 0:
571 msg = (
572 f'{name} has incorrect handedness. Expected a right-handed rotation, but got a '
573 f'left-handed rotation instead.'
574 )
575 raise ValueError(msg)
576 elif must_have_handedness == 'left' and not det < 0:
577 msg = (
578 f'{name} has incorrect handedness. Expected a left-handed rotation, but got a '
579 f'right-handed rotation instead.'
580 )
581 raise ValueError(msg)
582
583 return rotation_matrix
584
585
586 def validate_transform4x4(
587 transform: TransformLike, /, *, must_be_finite: bool = True, name: str = 'Transform'
588 ) -> NumpyArray[float]:
589 """Validate transform-like input as a 4x4 ndarray.
590
591 Parameters
592 ----------
593 transform : TransformLike
594 Transformation matrix as a 3x3 or 4x4 array, :vtk:`vtkMatrix3x3` or
595 :vtk:`vtkMatrix4x4`, :vtk:`vtkTransform`, or a SciPy ``Rotation`` instance.
596 If the input is 3x3, the array is padded using a 4x4 identity matrix.
597
598 must_be_finite : bool, default: True
599 :func:`Check <pyvista.core._validation.check.check_finite>`
600 if all elements of the array are finite, i.e. not ``infinity``
601 and not Not a Number (``NaN``).
602
603 name : str, default: "Transform"
604 Variable name to use in the error messages if any of the
605 validation checks fail.
606
607 Returns
608 -------
609 np.ndarray
610 Validated 4x4 transformation matrix.
611
612 See Also
613 --------
614 validate_transform3x3
615 Similar function for 3x3 transforms.
616
617 validate_array
618 Generic array validation function.
619
620 """
621 check_string(name, name='Name')
622 try:
623 arr = np.eye(4) # initialize
624 arr[:3, :3] = validate_transform3x3(transform, must_be_finite=must_be_finite, name=name)
625 except (ValueError, TypeError):
626 if isinstance(transform, _vtk.vtkMatrix4x4):
627 arr = _array_from_vtkmatrix(transform, shape=(4, 4)) # type: ignore[assignment]
628 elif isinstance(transform, _vtk.vtkTransform):
629 arr = _array_from_vtkmatrix(transform.GetMatrix(), shape=(4, 4)) # type: ignore[assignment]
630 else:
631 try:
632 arr = validate_array(
633 transform, # type: ignore[arg-type]
634 must_have_shape=[(3, 3), (4, 4)],
635 must_be_finite=must_be_finite,
636 name=name,
637 )
638 except TypeError:
639 msg = (
640 'Input transform must be one of:\n'
641 '\tvtkMatrix4x4\n'
642 '\tvtkMatrix3x3\n'
643 '\tvtkTransform\n'
644 '\t4x4 np.ndarray\n'
645 '\t3x3 np.ndarray\n'
646 '\tscipy.spatial.transform.Rotation\n'
647 f'Got {reprlib.repr(transform)} with type {type(transform)} instead.',
648 )
649 raise TypeError(msg)
650
651 return arr
652
653
654 def validate_transform3x3(
655 transform: TransformLike, /, *, must_be_finite: bool = True, name: str = 'Transform'
656 ):
657 """Validate transform-like input as a 3x3 ndarray.
658
659 Parameters
660 ----------
661 transform : RotationLike
662 Transformation matrix as a 3x3 array, vtk matrix, or a SciPy ``Rotation``
663 instance.
664
665 .. note::
666
667 Although ``RotationLike`` inputs are accepted, no checks are done
668 to verify that the transformation is actually a rotation.
669 Therefore, any 3x3 transformation is acceptable.
670
671 must_be_finite : bool, default: True
672 :func:`Check <pyvista.core._validation.check.check_finite>`
673 if all elements of the array are finite, i.e. not ``infinity``
674 and not Not a Number (``NaN``).
675
676 name : str, default: "Transform"
677 Variable name to use in the error messages if any of the
678 validation checks fail.
679
680 Returns
681 -------
682 np.ndarray
683 Validated 3x3 transformation matrix.
684
685 See Also
686 --------
687 validate_transform4x4
688 Similar function for 4x4 transforms.
689
690 validate_array
691 Generic array validation function.
692
693 """
694 check_string(name, name='Name')
695 if isinstance(transform, _vtk.vtkMatrix3x3):
696 return _array_from_vtkmatrix(transform, shape=(3, 3))
697 else:
698 try:
699 return validate_array(
700 transform, # type: ignore[arg-type]
701 must_have_shape=(3, 3),
702 must_be_finite=must_be_finite,
703 name=name,
704 )
705 except ValueError:
706 pass
707 except TypeError:
708 try:
709 from scipy.spatial.transform import Rotation # noqa: PLC0415
710 except ModuleNotFoundError: # pragma: no cover
711 pass
712 else:
713 if isinstance(transform, Rotation):
714 # Get matrix output and try validating again
715 return validate_transform3x3(
716 transform.as_matrix(), must_be_finite=must_be_finite, name=name
717 )
718
719 error_message = (
720 f'Input transform must be one of:\n'
721 '\tvtkMatrix3x3\n'
722 '\t3x3 np.ndarray\n'
723 '\tscipy.spatial.transform.Rotation\n'
724 f'Got {reprlib.repr(transform)} with type {type(transform)} instead.'
725 )
726 raise TypeError(error_message)
727
728
729 def _array_from_vtkmatrix(
730 matrix: _vtk.vtkMatrix3x3 | _vtk.vtkMatrix4x4,
731 shape: tuple[Literal[3], Literal[3]] | tuple[Literal[4], Literal[4]],
732 ) -> NumpyArray[float]:
733 """Convert a vtk matrix to an array."""
734 array = np.zeros(shape)
735 for i, j in product(range(shape[0]), range(shape[1])):
736 array[i, j] = matrix.GetElement(i, j)
737 return array
738
739
740 def validate_number(num: float, /, *, reshape: bool = True, **kwargs):
741 """Validate a real, finite number.
742
743 By default, the number is checked to ensure it:
744
745 * is scalar or is an array which can be reshaped as a scalar
746 * is a real number
747 * is finite
748
749 Parameters
750 ----------
751 num : float
752 Number to validate.
753
754 reshape : bool, default: True
755 If ``True``, 1D arrays with 1 element are considered valid input
756 and are reshaped to be 0-dimensional.
757
758 **kwargs : dict, optional
759 Additional keyword arguments passed to :func:`~validate_array`.
760
761 Returns
762 -------
763 output : int | float
764 Validated number.
765
766 See Also
767 --------
768 validate_array
769 Generic array validation function.
770
771 Examples
772 --------
773 Validate a number.
774
775 >>> from pyvista import _validation
776 >>> _validation.validate_number(1)
777 1
778
779 1D arrays are automatically reshaped.
780
781 >>> _validation.validate_number([42.0])
782 42.0
783
784 Additional checks can be added as needed.
785
786 >>> _validation.validate_number(
787 ... 10, must_be_in_range=[0, 10], must_be_integer=True
788 ... )
789 10
790
791 """
792 kwargs.setdefault('name', 'Number')
793 kwargs.setdefault('to_list', True)
794 kwargs.setdefault('must_be_finite', True)
795
796 if reshape:
797 shape = [(), (1,)]
798 _set_default_kwarg_mandatory(kwargs, 'reshape_to', ())
799 else:
800 shape = () # type: ignore[assignment]
801 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', shape)
802
803 return validate_array(num, **kwargs)
804
805
806 def validate_data_range(rng: VectorLike[float], /, **kwargs):
807 """Validate a data range.
808
809 By default, the data range is checked to ensure:
810
811 * it has two values
812 * it has real numbers
813 * the lower bound is not more than the upper bound
814
815 Parameters
816 ----------
817 rng : VectorLike[float]
818 Range to validate in the form ``(lower_bound, upper_bound)``.
819
820 **kwargs : dict, optional
821 Additional keyword arguments passed to :func:`~validate_array`.
822
823 Returns
824 -------
825 tuple
826 Validated range as ``(lower_bound, upper_bound)``.
827
828 See Also
829 --------
830 validate_array
831 Generic array validation function.
832
833 Examples
834 --------
835 Validate a data range.
836
837 >>> from pyvista import _validation
838 >>> _validation.validate_data_range([-5, 5])
839 (-5, 5)
840
841 Add additional constraints if needed.
842
843 >>> _validation.validate_data_range([0, 1.0], must_be_nonnegative=True)
844 (0.0, 1.0)
845
846 """
847 kwargs.setdefault('name', 'Data Range')
848 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', 2)
849 _set_default_kwarg_mandatory(kwargs, 'must_be_sorted', True)
850 if 'to_list' not in kwargs:
851 kwargs.setdefault('to_tuple', True)
852 return validate_array(rng, **kwargs)
853
854
855 def validate_arrayNx3( # noqa: N802
856 arr: VectorLike[float] | MatrixLike[float], /, *, reshape: bool = True, **kwargs
857 ):
858 """Validate an array is numeric and has shape Nx3.
859
860 The array is checked to ensure its input values:
861
862 * have shape ``(N, 3)`` or can be reshaped to ``(N, 3)``
863 * are numeric
864
865 The returned array is formatted so that its values:
866
867 * have shape ``(N, 3)``.
868
869 Parameters
870 ----------
871 arr : VectorLike[float] | MatrixLike[float]
872 Array to validate.
873
874 reshape : bool, default: True
875 If ``True``, 1D arrays with 3 elements are considered valid
876 input and are reshaped to ``(1, 3)`` to ensure the output is
877 two-dimensional.
878
879 **kwargs : dict, optional
880 Additional keyword arguments passed to :func:`~validate_array`.
881
882 Returns
883 -------
884 np.ndarray
885 Validated array with shape ``(N, 3)``.
886
887 See Also
888 --------
889 validate_arrayN
890 Similar function for one-dimensional arrays.
891
892 validate_array
893 Generic array validation function.
894
895 Examples
896 --------
897 Validate an Nx3 array.
898
899 >>> from pyvista import _validation
900 >>> _validation.validate_arrayNx3(((1, 2, 3), (4, 5, 6)))
901 array([[1, 2, 3],
902 [4, 5, 6]])
903
904 One-dimensional 3-element arrays are automatically reshaped to 2D.
905
906 >>> _validation.validate_arrayNx3([1, 2, 3])
907 array([[1, 2, 3]])
908
909 Add additional constraints.
910
911 >>> _validation.validate_arrayNx3(
912 ... ((1, 2, 3), (4, 5, 6)), must_be_in_range=[0, 10]
913 ... )
914 array([[1, 2, 3],
915 [4, 5, 6]])
916
917 """
918 if reshape:
919 shape = [3, (-1, 3)]
920 _set_default_kwarg_mandatory(kwargs, 'reshape_to', (-1, 3))
921 else:
922 shape = (-1, 3) # type: ignore[assignment]
923 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', shape)
924
925 return validate_array(arr, **kwargs)
926
927
928 def validate_arrayN(arr: float | VectorLike[float], /, *, reshape: bool = True, **kwargs): # noqa: N802
929 """Validate a numeric 1D array.
930
931 The array is checked to ensure its input values:
932
933 * have shape ``(N,)`` or can be reshaped to ``(N,)``
934 * are numeric
935
936 The returned array is formatted so that its values:
937
938 * have shape ``(N,)``
939
940 Parameters
941 ----------
942 arr : VectorLike[float]
943 Array to validate.
944
945 reshape : bool, default: True
946 If ``True``, 0-dimensional scalars are reshaped to ``(1,)`` and 2D
947 vectors with shape ``(1, N)`` are reshaped to ``(N,)`` to ensure the
948 output is consistently one-dimensional. Otherwise, all scalar and
949 2D inputs are not considered valid.
950
951 **kwargs : dict, optional
952 Additional keyword arguments passed to :func:`~validate_array`.
953
954 Returns
955 -------
956 np.ndarray
957 Validated 1D array.
958
959 See Also
960 --------
961 validate_arrayN_unsigned
962 Similar function for non-negative integer arrays.
963
964 validate_array
965 Generic array validation function.
966
967 Examples
968 --------
969 Validate a 1D array with four elements.
970
971 >>> from pyvista import _validation
972 >>> _validation.validate_arrayN((1, 2, 3, 4))
973 array([1, 2, 3, 4])
974
975 Scalar 0-dimensional values are automatically reshaped to be 1D.
976
977 >>> _validation.validate_arrayN(42.0)
978 array([42.0])
979
980 2D arrays where the first dimension is unity are automatically
981 reshaped to be 1D.
982
983 >>> _validation.validate_arrayN([[1, 2]])
984 array([1, 2])
985
986 Add additional constraints if needed.
987
988 >>> _validation.validate_arrayN((1, 2, 3), must_have_length=3)
989 array([1, 2, 3])
990
991 """
992 if reshape:
993 shape = [(), (-1), (1, -1)]
994 _set_default_kwarg_mandatory(kwargs, 'reshape_to', (-1))
995 else:
996 shape = -1 # type: ignore[assignment]
997 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', shape)
998 return validate_array(arr, **kwargs)
999
1000
1001 def validate_arrayN_unsigned( # noqa: N802
1002 arr: VectorLike[float], /, *, reshape: bool = True, **kwargs
1003 ) -> NumpyArray[int]:
1004 """Validate a numeric 1D array of non-negative (unsigned) integers.
1005
1006 The array is checked to ensure its input values:
1007
1008 * have shape ``(N,)`` or can be reshaped to ``(N,)``
1009 * are integer-like
1010 * are non-negative
1011
1012 The returned array is formatted so that its values:
1013
1014 * have shape ``(N,)``
1015 * have an integer data type
1016
1017 Parameters
1018 ----------
1019 arr : VectorLike[float]
1020 Array to validate.
1021
1022 reshape : bool, default: True
1023 If ``True``, 0-dimensional scalars are reshaped to ``(1,)`` and 2D
1024 vectors with shape ``(1, N)`` are reshaped to ``(N,)`` to ensure the
1025 output is consistently one-dimensional. Otherwise, all scalar and
1026 2D inputs are not considered valid.
1027
1028 **kwargs : dict, optional
1029 Additional keyword arguments passed to :func:`~validate_array`.
1030
1031 Returns
1032 -------
1033 np.ndarray
1034 Validated 1D array with non-negative integers.
1035
1036 See Also
1037 --------
1038 validate_arrayN
1039 Similar function for numeric one-dimensional arrays.
1040
1041 validate_array
1042 Generic array validation function.
1043
1044 Examples
1045 --------
1046 Validate a 1D array with four non-negative integer-like elements.
1047
1048 >>> import numpy as np
1049 >>> from pyvista import _validation
1050 >>> arr = _validation.validate_arrayN_unsigned((1.0, 2.0, 3.0, 4.0))
1051 >>> arr
1052 array([1, 2, 3, 4])
1053
1054 Verify that the output data type is integral.
1055
1056 >>> np.issubdtype(arr.dtype, int)
1057 True
1058
1059 Scalar 0-dimensional values are automatically reshaped to be 1D.
1060
1061 >>> _validation.validate_arrayN_unsigned(42)
1062 array([42])
1063
1064 2D arrays where the first dimension is unity are automatically
1065 reshaped to be 1D.
1066
1067 >>> _validation.validate_arrayN_unsigned([[1, 2]])
1068 array([1, 2])
1069
1070 Add additional constraints if needed.
1071
1072 >>> _validation.validate_arrayN_unsigned((1, 2, 3), must_be_in_range=[1, 3])
1073 array([1, 2, 3])
1074
1075 """
1076 # Set default dtype out but allow overriding as long as the dtype
1077 # is also integral
1078 kwargs.setdefault('dtype_out', int)
1079 if kwargs['dtype_out'] is not int:
1080 check_subdtype(kwargs['dtype_out'], np.integer)
1081
1082 _set_default_kwarg_mandatory(kwargs, 'must_be_integer', True)
1083 _set_default_kwarg_mandatory(kwargs, 'must_be_nonnegative', True)
1084
1085 return validate_arrayN(arr, reshape=reshape, **kwargs)
1086
1087
1088 def validate_array3(
1089 arr: float | VectorLike[float] | MatrixLike[float],
1090 /,
1091 *,
1092 reshape: bool = True,
1093 broadcast: bool = False,
1094 **kwargs,
1095 ):
1096 """Validate a numeric 1D array with 3 elements.
1097
1098 The array is checked to ensure its input values:
1099
1100 * have shape ``(3,)`` or can be reshaped to ``(3,)``
1101 * are numeric and real
1102
1103 The returned array is formatted so that it has shape ``(3,)``.
1104
1105 Parameters
1106 ----------
1107 arr : float | VectorLike[float] | MatrixLike[float]
1108 Array to validate.
1109
1110 reshape : bool, default: True
1111 If ``True``, 2D vectors with shape ``(1, 3)`` are considered valid
1112 input, and are reshaped to ``(3,)`` to ensure the output is
1113 consistently one-dimensional.
1114
1115 broadcast : bool, default: False
1116 If ``True``, scalar values or 1D arrays with a single element
1117 are considered valid input and the single value is broadcast to
1118 a length 3 array.
1119
1120 **kwargs : dict, optional
1121 Additional keyword arguments passed to :func:`~validate_array`.
1122
1123 Returns
1124 -------
1125 np.ndarray
1126 Validated 1D array with 3 elements.
1127
1128 See Also
1129 --------
1130 validate_number
1131 Similar function for a single number.
1132
1133 validate_arrayN
1134 Similar function for one-dimensional arrays.
1135
1136 validate_array
1137 Generic array validation function.
1138
1139 Examples
1140 --------
1141 Validate a 1D array with three elements.
1142
1143 >>> from pyvista import _validation
1144 >>> _validation.validate_array3((1, 2, 3))
1145 array([1, 2, 3])
1146
1147 2D 3-element arrays are automatically reshaped to be 1D.
1148
1149 >>> _validation.validate_array3([[1, 2, 3]])
1150 array([1, 2, 3])
1151
1152 Scalar 0-dimensional values can be automatically broadcast as
1153 a 3-element 1D array.
1154
1155 >>> _validation.validate_array3(42.0, broadcast=True)
1156 array([42.0, 42.0, 42.0])
1157
1158 Add additional constraints if needed.
1159
1160 >>> _validation.validate_array3((1, 2, 3), must_be_nonnegative=True)
1161 array([1, 2, 3])
1162
1163 """
1164 shape = [(3,)]
1165 if reshape:
1166 shape.append((1, 3)) # type: ignore[arg-type]
1167 shape.append((3, 1)) # type: ignore[arg-type]
1168 _set_default_kwarg_mandatory(kwargs, 'reshape_to', (-1))
1169 if broadcast:
1170 shape.append(()) # type: ignore[arg-type] # allow 0D scalars
1171 shape.append((1,)) # 1D 1-element vectors
1172 _set_default_kwarg_mandatory(kwargs, 'broadcast_to', (3,))
1173 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', shape)
1174
1175 return validate_array(arr, **kwargs)
1176
1177
1178 def _set_default_kwarg_mandatory(kwargs: dict[str, Any], key: str, default: Any) -> None:
1179 """Set a kwarg and raise ValueError if not set to its default value."""
1180 val = kwargs.pop(key, default)
1181 if val != default:
1182 calling_fname = inspect.stack()[1].function
1183 msg = (
1184 f"Parameter '{key}' cannot be set for function `{calling_fname}`.\n"
1185 f'Its value is automatically set to `{default}`.'
1186 )
1187 raise ValueError(msg)
1188 kwargs[key] = default
1189
1190
1191 def validate_dimensionality(
1192 dimensionality: Literal[0, 1, 2, 3, '0D', '1D', '2D', '3D'] | VectorLike[int],
1193 /,
1194 *,
1195 reshape: bool = True,
1196 **kwargs,
1197 ) -> int:
1198 """Validate a dimensionality.
1199
1200 By default, the dimensionality is checked to ensure it:
1201
1202 * is scalar or is an array which can be reshaped as a scalar
1203 * is an integer in the inclusive range ``[0, 3]``
1204 * or is a valid alias among ``'0D'``, ``'1D'``, ``'2D'``, or ``'3D'``
1205
1206 Parameters
1207 ----------
1208 dimensionality : Literal[0, 1, 2, 3, '0D', '1D', '2D', '3D'] | ArrayLike
1209 Number to validate.
1210
1211 reshape : bool, default: True
1212 If ``True``, 1D arrays with 1 element are considered valid input
1213 and are reshaped to be 0-dimensional.
1214
1215 **kwargs : dict, optional
1216 Additional keyword arguments passed to :func:`~validate_array`.
1217
1218 Returns
1219 -------
1220 int
1221 Validated dimensionality.
1222
1223 Examples
1224 --------
1225 Validate a dimensionality.
1226
1227 >>> from pyvista import _validation
1228 >>> _validation.validate_dimensionality('1D')
1229 1
1230
1231 1D arrays are automatically reshaped.
1232
1233 >>> _validation.validate_dimensionality([3])
1234 3
1235
1236 """
1237 kwargs.setdefault('name', 'Dimensionality')
1238 kwargs.setdefault('to_list', True)
1239 kwargs.setdefault('must_be_finite', True)
1240 kwargs.setdefault('must_be_in_range', [0, 3])
1241
1242 dimensionality_as_array = np.asarray(dimensionality)
1243 if np.issubdtype(dimensionality_as_array.dtype, str):
1244 dimensionality_as_array = np.char.replace(dimensionality_as_array, 'D', '')
1245
1246 try:
1247 dimensionality_as_array = dimensionality_as_array.astype(np.int64)
1248 except ValueError:
1249 msg = (
1250 f'`{dimensionality}` is not a valid dimensionality.'
1251 ' Use one of [0, 1, 2, 3, "0D", "1D", "2D", "3D"].'
1252 )
1253 raise ValueError(msg)
1254
1255 if reshape:
1256 shape = [(), (1,)]
1257 _set_default_kwarg_mandatory(kwargs, 'reshape_to', ())
1258 else:
1259 shape = () # type: ignore[assignment]
1260 _set_default_kwarg_mandatory(kwargs, 'must_have_shape', shape)
1261
1262 return validate_array(dimensionality_as_array, **kwargs)
1263
1264
1265 def _validate_color_sequence(
1266 color: ColorLike | Sequence[ColorLike],
1267 n_colors: int | None = None,
1268 ) -> tuple[Color, ...]:
1269 """Validate a color sequence.
1270
1271 If `n_colors` is specified, the output will have `n` colors. For single-color
1272 inputs, the color is copied and a sequence of `n` identical colors is returned.
1273 For inputs with multiple colors, the number of colors in the input must
1274 match `n_colors`.
1275
1276 If `n_colors` is None, no broadcasting or length-checking is performed.
1277 """
1278 from pyvista.plotting.colors import Color # noqa: PLC0415
1279
1280 try:
1281 # Assume we have one color
1282 color_list = [Color(color)]
1283 n_colors = 1 if n_colors is None else n_colors
1284 return tuple(color_list * n_colors)
1285 except ValueError:
1286 if isinstance(color, (tuple, list)):
1287 try:
1288 color_list = [_validate_color_sequence(c, n_colors=1)[0] for c in color]
1289 if len(color_list) == 1:
1290 n_colors = 1 if n_colors is None else n_colors
1291 color_list = color_list * n_colors
1292
1293 # Only return if we have the correct number of colors
1294 if n_colors is None or len(color_list) == n_colors:
1295 return tuple(color_list)
1296 except ValueError:
1297 pass
1298 n_colors_str = f' {n_colors} ' if n_colors else ' '
1299 msg = (
1300 f'Invalid color(s):\n'
1301 f'\t{color}\n'
1302 f'Input must be a single ColorLike color '
1303 f'or a sequence of{n_colors_str}ColorLike colors.'
1304 )
1305 raise ValueError(msg)