| 1 |
"""Functions that check the type and/or value of inputs. |
| 2 |
|
| 3 |
.. versionadded:: 0.43.0 |
| 4 |
|
| 5 |
A ``check`` function typically: |
| 6 |
|
| 7 |
* Performs a simple validation on a single input variable. |
| 8 |
* Raises an error if the check fails due to invalid input. |
| 9 |
* Does not modify input or return anything. |
| 10 |
|
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
|
| 15 |
from collections.abc import Container |
| 16 |
from collections.abc import Iterable |
| 17 |
from collections.abc import Sequence |
| 18 |
from collections.abc import Sized |
| 19 |
from numbers import Number |
| 20 |
import reprlib |
| 21 |
import types |
| 22 |
from typing import TYPE_CHECKING |
| 23 |
from typing import Any |
| 24 |
from typing import Union |
| 25 |
from typing import cast |
| 26 |
from typing import get_args |
| 27 |
from typing import get_origin |
| 28 |
|
| 29 |
import numpy as np |
| 30 |
import numpy.typing as npt |
| 31 |
|
| 32 |
from pyvista.core._validation._cast_array import _cast_to_numpy |
| 33 |
|
| 34 |
if TYPE_CHECKING: |
| 35 |
from pyvista.core._typing_core import NumberType |
| 36 |
from pyvista.core._typing_core import NumpyArray |
| 37 |
from pyvista.core._typing_core import VectorLike |
| 38 |
from pyvista.core._typing_core._aliases import _ArrayLikeOrScalar |
| 39 |
from pyvista.core._typing_core._array_like import _NumberType |
| 40 |
|
| 41 |
|
| 42 |
_Shape = tuple[()] | tuple[int, ...] |
| 43 |
_ShapeLike = int | _Shape |
| 44 |
|
| 45 |
|
| 46 |
def check_subdtype( |
| 47 |
input_obj: npt.DTypeLike | _ArrayLikeOrScalar[NumberType], |
| 48 |
/, |
| 49 |
base_dtype: npt.DTypeLike | tuple[npt.DTypeLike, ...] | list[npt.DTypeLike], |
| 50 |
*, |
| 51 |
name: str = 'Input', |
| 52 |
) -> None: |
| 53 |
"""Check if an input's data-type is a subtype of another data-type(s). |
| 54 |
|
| 55 |
Parameters |
| 56 |
---------- |
| 57 |
input_obj : float | ArrayLike[float] | numpy.typing.DTypeLike |
| 58 |
``dtype`` object (or object coercible to one) or an array-like object. |
| 59 |
If array-like, the dtype of the array is used. |
| 60 |
|
| 61 |
base_dtype : numpy.typing.DTypeLike | Sequence[numpy.typing.DTypeLike] |
| 62 |
``dtype``-like object or a sequence of ``dtype``-like objects. The ``input_obj`` |
| 63 |
must be a subtype of this value. If a sequence, ``input_obj`` must be a |
| 64 |
subtype of at least one of the specified dtypes. |
| 65 |
|
| 66 |
name : str, default: "Input" |
| 67 |
Variable name to use in the error messages if any are raised. |
| 68 |
|
| 69 |
Raises |
| 70 |
------ |
| 71 |
TypeError |
| 72 |
If ``input_obj`` is not a subtype of ``base_dtype``. |
| 73 |
|
| 74 |
See Also |
| 75 |
-------- |
| 76 |
check_real |
| 77 |
check_number |
| 78 |
|
| 79 |
Examples |
| 80 |
-------- |
| 81 |
Check if ``float`` is a subtype of ``np.floating``. |
| 82 |
|
| 83 |
>>> import numpy as np |
| 84 |
>>> from pyvista import _validation |
| 85 |
>>> _validation.check_subdtype(float, np.floating) |
| 86 |
|
| 87 |
Check from multiple allowable dtypes. |
| 88 |
|
| 89 |
>>> _validation.check_subdtype(int, [np.integer, np.floating]) |
| 90 |
|
| 91 |
Check an array's dtype. |
| 92 |
|
| 93 |
>>> array = np.array([1, 2, 3], dtype='uint8') |
| 94 |
>>> _validation.check_subdtype(array, np.integer) |
| 95 |
|
| 96 |
""" |
| 97 |
input_dtype: npt.DTypeLike |
| 98 |
try: |
| 99 |
input_dtype = np.dtype(input_obj) # type: ignore[arg-type] |
| 100 |
except TypeError: |
| 101 |
input_dtype = np.asanyarray(input_obj).dtype |
| 102 |
|
| 103 |
if not isinstance(base_dtype, (tuple, list)): |
| 104 |
base_dtype = [base_dtype] |
| 105 |
|
| 106 |
if not any(np.issubdtype(input_dtype, base) for base in base_dtype): |
| 107 |
# Not a subdtype, so raise error |
| 108 |
msg = f"{name} has incorrect dtype of '{input_dtype.name}'. " |
| 109 |
if len(base_dtype) == 1: |
| 110 |
msg += f'The dtype must be a subtype of {base_dtype[0]}.' |
| 111 |
else: |
| 112 |
msg += f'The dtype must be a subtype of at least one of \n{base_dtype}.' |
| 113 |
raise TypeError(msg) |
| 114 |
|
| 115 |
|
| 116 |
def check_real(array: _ArrayLikeOrScalar[NumberType], /, *, name: str = 'Array') -> None: |
| 117 |
"""Check if an array has real numbers, i.e. float or integer type. |
| 118 |
|
| 119 |
Notes |
| 120 |
----- |
| 121 |
- Boolean data types are not considered real and will raise an error. |
| 122 |
- Arrays with ``infinity`` or ``NaN`` values are considered real and |
| 123 |
will not raise an error. Use :func:`check_finite` to check for |
| 124 |
finite values. |
| 125 |
|
| 126 |
Parameters |
| 127 |
---------- |
| 128 |
array : float | ArrayLike[float] |
| 129 |
Number or array to check. |
| 130 |
|
| 131 |
name : str, default: "Array" |
| 132 |
Variable name to use in the error messages if any are raised. |
| 133 |
|
| 134 |
Raises |
| 135 |
------ |
| 136 |
TypeError |
| 137 |
If the array does not have real numbers. |
| 138 |
|
| 139 |
See Also |
| 140 |
-------- |
| 141 |
check_integer |
| 142 |
Similar function for integer arrays. |
| 143 |
check_number |
| 144 |
Similar function for scalar values. |
| 145 |
check_finite |
| 146 |
Check for finite values. |
| 147 |
|
| 148 |
Examples |
| 149 |
-------- |
| 150 |
Check if an array has real numbers. |
| 151 |
|
| 152 |
>>> from pyvista import _validation |
| 153 |
>>> _validation.check_real([1, 2, 3]) |
| 154 |
|
| 155 |
""" |
| 156 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 157 |
|
| 158 |
# Return early for common cases |
| 159 |
if array.dtype.type in [np.int32, np.int64, np.float32, np.float64]: |
| 160 |
return |
| 161 |
|
| 162 |
# Do not use np.isreal as it will fail in some cases (e.g. scalars). |
| 163 |
# Check dtype directly instead |
| 164 |
try: |
| 165 |
check_subdtype(array, (np.floating, np.integer), name=name) |
| 166 |
except TypeError as e: |
| 167 |
msg = f'{name} must have real numbers.' |
| 168 |
raise TypeError(msg) from e |
| 169 |
|
| 170 |
|
| 171 |
def check_sorted( |
| 172 |
array: _ArrayLikeOrScalar[NumberType], |
| 173 |
/, |
| 174 |
*, |
| 175 |
ascending: bool = True, |
| 176 |
strict: bool = False, |
| 177 |
axis: int = -1, |
| 178 |
name: str = 'Array', |
| 179 |
) -> None: |
| 180 |
"""Check if an array's values are sorted. |
| 181 |
|
| 182 |
Parameters |
| 183 |
---------- |
| 184 |
array : float | ArrayLike[float] |
| 185 |
Number or array to check. |
| 186 |
|
| 187 |
ascending : bool, default: True |
| 188 |
If ``True``, check if the array's elements are in ascending order. |
| 189 |
If ``False``, check if the array's elements are in descending order. |
| 190 |
|
| 191 |
strict : bool, default: False |
| 192 |
If ``True``, the array's elements must be strictly increasing (if |
| 193 |
``ascending=True``) or strictly decreasing (if ``ascending=False``). |
| 194 |
Effectively, this means the array must be sorted *and* its values |
| 195 |
must be unique. |
| 196 |
|
| 197 |
axis : int | None, default: -1 |
| 198 |
Axis along which to check sorting. If ``None``, the array is flattened |
| 199 |
before checking. The default is ``-1``, which checks sorting along the |
| 200 |
last axis. |
| 201 |
|
| 202 |
name : str, default: "Array" |
| 203 |
Variable name to use in the error messages if any are raised. |
| 204 |
|
| 205 |
Raises |
| 206 |
------ |
| 207 |
ValueError |
| 208 |
If the array is not sorted in ascending order. |
| 209 |
|
| 210 |
See Also |
| 211 |
-------- |
| 212 |
check_range |
| 213 |
|
| 214 |
Examples |
| 215 |
-------- |
| 216 |
Check if an array's values are sorted, |
| 217 |
|
| 218 |
>>> from pyvista import _validation |
| 219 |
>>> _validation.check_sorted([1, 2, 3]) |
| 220 |
|
| 221 |
""" |
| 222 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 223 |
|
| 224 |
ndim = array.ndim |
| 225 |
if ndim == 0: |
| 226 |
# Scalars are always sorted |
| 227 |
return |
| 228 |
|
| 229 |
# Validate axis |
| 230 |
if axis not in [-1, None]: |
| 231 |
check_number(axis, name='Axis') |
| 232 |
check_integer(axis, name='Axis') |
| 233 |
axis = int(axis) |
| 234 |
try: |
| 235 |
check_range(axis, rng=[-ndim, ndim - 1], name='Axis') |
| 236 |
except ValueError: |
| 237 |
msg = f'Axis {axis} is out of bounds for ndim {ndim}.' |
| 238 |
raise ValueError(msg) |
| 239 |
|
| 240 |
if axis is None and ndim >= 1: # type: ignore[unreachable] |
| 241 |
# Emulate np.sort(), which flattens array when axis is None |
| 242 |
array = array.ravel(order='A') # type: ignore[unreachable] |
| 243 |
ndim = 1 |
| 244 |
axis = 0 |
| 245 |
|
| 246 |
# Create slicers to get a view along an axis |
| 247 |
# Create two slicers to compare consecutive elements with each other |
| 248 |
first_slice = [slice(None)] * ndim |
| 249 |
first_slice[axis] = slice(None, -1) |
| 250 |
first_item = array[tuple(first_slice)] |
| 251 |
|
| 252 |
second_slice = [slice(None)] * ndim |
| 253 |
second_slice[axis] = slice(1, None) |
| 254 |
second_item = array[tuple(second_slice)] |
| 255 |
|
| 256 |
if ascending and not strict: |
| 257 |
is_sorted = np.all(first_item <= second_item) |
| 258 |
elif ascending and strict: |
| 259 |
is_sorted = np.all(first_item < second_item) |
| 260 |
elif not ascending and not strict: |
| 261 |
is_sorted = np.all(first_item >= second_item) |
| 262 |
else: # not ascending and strict |
| 263 |
is_sorted = np.all(first_item > second_item) |
| 264 |
|
| 265 |
if not is_sorted: |
| 266 |
# Show the array's elements in error msg if array is small |
| 267 |
msg_body = f'with {array.size} elements' |
| 268 |
order = 'ascending' if ascending else 'descending' |
| 269 |
strict_ = 'strict ' if strict else '' |
| 270 |
msg = ( |
| 271 |
f'{name} {msg_body} must be sorted in {strict_}{order} order. ' |
| 272 |
f'Got:\n {reprlib.repr(array)}' |
| 273 |
) |
| 274 |
raise ValueError(msg) |
| 275 |
|
| 276 |
|
| 277 |
def check_finite(array: _ArrayLikeOrScalar[NumberType], /, *, name: str = 'Array') -> None: |
| 278 |
"""Check if an array has finite values, i.e. no NaN or Inf values. |
| 279 |
|
| 280 |
Parameters |
| 281 |
---------- |
| 282 |
array : float | ArrayLike[float] |
| 283 |
Number or array to check. |
| 284 |
|
| 285 |
name : str, default: "Array" |
| 286 |
Variable name to use in the error messages if any are raised. |
| 287 |
|
| 288 |
Raises |
| 289 |
------ |
| 290 |
ValueError |
| 291 |
If the array has any ``Inf`` or ``NaN`` values. |
| 292 |
|
| 293 |
See Also |
| 294 |
-------- |
| 295 |
check_real |
| 296 |
|
| 297 |
Examples |
| 298 |
-------- |
| 299 |
Check if an array's values are finite. |
| 300 |
|
| 301 |
>>> from pyvista import _validation |
| 302 |
>>> _validation.check_finite([1, 2, 3]) |
| 303 |
|
| 304 |
""" |
| 305 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 306 |
if not np.all(np.isfinite(array)): |
| 307 |
msg = f'{name} must have finite values.' |
| 308 |
raise ValueError(msg) |
| 309 |
|
| 310 |
|
| 311 |
def check_integer( |
| 312 |
array: _ArrayLikeOrScalar[NumberType], |
| 313 |
/, |
| 314 |
*, |
| 315 |
strict: bool = False, |
| 316 |
name: str = 'Array', |
| 317 |
) -> None: |
| 318 |
"""Check if an array has integer or integer-like float values. |
| 319 |
|
| 320 |
Parameters |
| 321 |
---------- |
| 322 |
array : float | ArrayLike[float] |
| 323 |
Number or array to check. |
| 324 |
|
| 325 |
strict : bool, default: False |
| 326 |
If ``True``, the array's data must be a subtype of `int` or |
| 327 |
``np.integer``. Otherwise, floats are allowed but must be |
| 328 |
whole numbers. |
| 329 |
|
| 330 |
name : str, default: "Array" |
| 331 |
Variable name to use in the error messages if any are raised. |
| 332 |
|
| 333 |
Raises |
| 334 |
------ |
| 335 |
ValueError |
| 336 |
If any element's value differs from its floor. |
| 337 |
|
| 338 |
TypeError |
| 339 |
If ``strict=True`` and the array's dtype is not integral. |
| 340 |
|
| 341 |
See Also |
| 342 |
-------- |
| 343 |
check_nonnegative |
| 344 |
check_subdtype |
| 345 |
|
| 346 |
Examples |
| 347 |
-------- |
| 348 |
Check if an array has integer-like values. |
| 349 |
|
| 350 |
>>> from pyvista import _validation |
| 351 |
>>> _validation.check_integer([1.0, 2.0]) |
| 352 |
|
| 353 |
""" |
| 354 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 355 |
if strict: |
| 356 |
check_subdtype(array, np.integer) |
| 357 |
elif not np.array_equal(array, np.floor(array)): |
| 358 |
msg = f'{name} must have integer-like values.' |
| 359 |
raise ValueError(msg) |
| 360 |
|
| 361 |
|
| 362 |
def check_nonnegative(array: _ArrayLikeOrScalar[NumberType], /, *, name: str = 'Array') -> None: |
| 363 |
"""Check if an array's elements are all nonnegative. |
| 364 |
|
| 365 |
Parameters |
| 366 |
---------- |
| 367 |
array : float | ArrayLike[float] |
| 368 |
Number or array to check. |
| 369 |
|
| 370 |
name : str, default: "Array" |
| 371 |
Variable name to use in the error messages if any are raised. |
| 372 |
|
| 373 |
Raises |
| 374 |
------ |
| 375 |
ValueError |
| 376 |
If the array has any negative values. |
| 377 |
|
| 378 |
See Also |
| 379 |
-------- |
| 380 |
check_greater_than |
| 381 |
check_less_than |
| 382 |
|
| 383 |
Examples |
| 384 |
-------- |
| 385 |
Check if an array's values are non-negative. |
| 386 |
|
| 387 |
>>> from pyvista import _validation |
| 388 |
>>> _validation.check_nonnegative([1, 2, 3]) |
| 389 |
|
| 390 |
""" |
| 391 |
check_greater_than(array, 0, strict=False, name=name) |
| 392 |
|
| 393 |
|
| 394 |
def _validate_real_value(scalar: float, name: str = 'Value') -> NumpyArray[float]: |
| 395 |
valid_scalar = _cast_to_numpy(scalar) |
| 396 |
check_shape(valid_scalar, (), name=name) |
| 397 |
check_real(valid_scalar, name=name) |
| 398 |
return valid_scalar |
| 399 |
|
| 400 |
|
| 401 |
def check_greater_than( |
| 402 |
array: _ArrayLikeOrScalar[NumberType], |
| 403 |
/, |
| 404 |
value: float, |
| 405 |
*, |
| 406 |
strict: bool = True, |
| 407 |
name: str = 'Array', |
| 408 |
) -> None: |
| 409 |
"""Check if an array's elements are all greater than some value. |
| 410 |
|
| 411 |
Parameters |
| 412 |
---------- |
| 413 |
array : float | ArrayLike[float] |
| 414 |
Number or array to check. |
| 415 |
|
| 416 |
value : float |
| 417 |
Value which the array's elements must be greater than. |
| 418 |
|
| 419 |
strict : bool, default: True |
| 420 |
If ``True``, the array's value must be strictly greater than ``value``. |
| 421 |
Otherwise, values must be greater than or equal to ``value``. |
| 422 |
|
| 423 |
name : str, default: "Array" |
| 424 |
Variable name to use in the error messages if any are raised. |
| 425 |
|
| 426 |
Raises |
| 427 |
------ |
| 428 |
ValueError |
| 429 |
If not all array elements are greater than (or equal to if |
| 430 |
``strict=True``) the specified value. |
| 431 |
|
| 432 |
See Also |
| 433 |
-------- |
| 434 |
check_less_than |
| 435 |
check_range |
| 436 |
check_nonnegative |
| 437 |
|
| 438 |
Examples |
| 439 |
-------- |
| 440 |
Check if an array's values are greater than 0. |
| 441 |
|
| 442 |
>>> from pyvista import _validation |
| 443 |
>>> _validation.check_greater_than([1, 2, 3], value=0) |
| 444 |
|
| 445 |
""" |
| 446 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 447 |
valid_value = _validate_real_value(value) |
| 448 |
if strict and not np.all(array > valid_value): |
| 449 |
msg = f'{name} values must all be greater than {value}.' |
| 450 |
raise ValueError(msg) |
| 451 |
elif not np.all(array >= valid_value): |
| 452 |
msg = f'{name} values must all be greater than or equal to {value}.' |
| 453 |
raise ValueError(msg) |
| 454 |
|
| 455 |
|
| 456 |
def check_less_than( |
| 457 |
array: _ArrayLikeOrScalar[NumberType], |
| 458 |
/, |
| 459 |
value: float, |
| 460 |
*, |
| 461 |
strict: bool = True, |
| 462 |
name: str = 'Array', |
| 463 |
) -> None: |
| 464 |
"""Check if an array's elements are all less than some value. |
| 465 |
|
| 466 |
Parameters |
| 467 |
---------- |
| 468 |
array : float | ArrayLike[float] |
| 469 |
Number or array to check. |
| 470 |
|
| 471 |
value : float |
| 472 |
Value which the array's elements must be less than. |
| 473 |
|
| 474 |
strict : bool, default: True |
| 475 |
If ``True``, the array's value must be strictly less than |
| 476 |
``value``. Otherwise, values must be less than or equal to |
| 477 |
``value``. |
| 478 |
|
| 479 |
name : str, default: "Array" |
| 480 |
Variable name to use in the error messages if any are raised. |
| 481 |
|
| 482 |
Raises |
| 483 |
------ |
| 484 |
ValueError |
| 485 |
If not all array elements are less than (or equal to if |
| 486 |
``strict=True``) the specified value. |
| 487 |
|
| 488 |
See Also |
| 489 |
-------- |
| 490 |
check_greater_than |
| 491 |
check_range |
| 492 |
check_nonnegative |
| 493 |
|
| 494 |
Examples |
| 495 |
-------- |
| 496 |
Check if an array's values are less than 0. |
| 497 |
|
| 498 |
>>> from pyvista import _validation |
| 499 |
>>> _validation.check_less_than([-1, -2, -3], value=0) |
| 500 |
|
| 501 |
""" |
| 502 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 503 |
valid_value = _validate_real_value(value) |
| 504 |
if strict and not np.all(array < valid_value): |
| 505 |
msg = f'{name} values must all be less than {value}.' |
| 506 |
raise ValueError(msg) |
| 507 |
elif not np.all(array <= valid_value): |
| 508 |
msg = f'{name} values must all be less than or equal to {value}.' |
| 509 |
raise ValueError(msg) |
| 510 |
|
| 511 |
|
| 512 |
def check_range( |
| 513 |
array: _ArrayLikeOrScalar[NumberType], |
| 514 |
/, |
| 515 |
rng: VectorLike[_NumberType], |
| 516 |
*, |
| 517 |
strict_lower: bool = False, |
| 518 |
strict_upper: bool = False, |
| 519 |
name: str = 'Array', |
| 520 |
) -> None: |
| 521 |
"""Check if an array's values are all within a specific range. |
| 522 |
|
| 523 |
Parameters |
| 524 |
---------- |
| 525 |
array : float | ArrayLike[float] |
| 526 |
Number or array to check. |
| 527 |
|
| 528 |
rng : VectorLike[float], optional |
| 529 |
Vector with two elements ``[min, max]`` specifying the minimum |
| 530 |
and maximum data values allowed, respectively. By default, the |
| 531 |
range endpoints are inclusive, i.e. values must be >= min |
| 532 |
and <= max. Use ``strict_lower`` and/or ``strict_upper`` |
| 533 |
to further restrict the allowable range. Use ``np.inf`` or |
| 534 |
``-np.inf`` to specify open intervals, e.g. ``[0, np.inf]``. |
| 535 |
|
| 536 |
strict_lower : bool, default: False |
| 537 |
Enforce a strict lower bound for the range, i.e. array values |
| 538 |
must be strictly greater than the minimum. |
| 539 |
|
| 540 |
strict_upper : bool, default: False |
| 541 |
Enforce a strict upper bound for the range, i.e. array values |
| 542 |
must be strictly less than the maximum. |
| 543 |
|
| 544 |
name : str, default: "Array" |
| 545 |
Variable name to use in the error messages if any are raised. |
| 546 |
|
| 547 |
Raises |
| 548 |
------ |
| 549 |
ValueError |
| 550 |
If any array value is outside the specified range. |
| 551 |
|
| 552 |
See Also |
| 553 |
-------- |
| 554 |
check_less_than |
| 555 |
check_greater_than |
| 556 |
|
| 557 |
Examples |
| 558 |
-------- |
| 559 |
Check if `an array's values are in the range ``[0, 1]``. |
| 560 |
|
| 561 |
>>> from pyvista import _validation |
| 562 |
>>> _validation.check_range([0, 0.5, 1], rng=[0, 1]) |
| 563 |
|
| 564 |
""" |
| 565 |
rng = rng if isinstance(rng, np.ndarray) else _cast_to_numpy(rng) |
| 566 |
check_shape(rng, 2, name='Range') |
| 567 |
check_sorted(rng, name='Range') |
| 568 |
|
| 569 |
array = array if isinstance(array, np.ndarray) else _cast_to_numpy(array) |
| 570 |
check_greater_than(array, rng[0], strict=strict_lower, name=name) |
| 571 |
check_less_than(array, rng[1], strict=strict_upper, name=name) |
| 572 |
|
| 573 |
|
| 574 |
def check_shape( |
| 575 |
array: _ArrayLikeOrScalar[NumberType], |
| 576 |
/, |
| 577 |
shape: _ShapeLike | list[_ShapeLike], |
| 578 |
*, |
| 579 |
name: str = 'Array', |
| 580 |
) -> None: |
| 581 |
"""Check if an array has the specified shape. |
| 582 |
|
| 583 |
Parameters |
| 584 |
---------- |
| 585 |
array : float | ArrayLike[float] |
| 586 |
Number or array to check. |
| 587 |
|
| 588 |
shape : ShapeLike | list[ShapeLike] |
| 589 |
A single shape or a list of any allowable shapes. If an integer, |
| 590 |
``i``, the shape is interpreted as ``(i,)``. Use a value of |
| 591 |
-1 for any dimension where its size is allowed to vary, e.g. |
| 592 |
``(-1,3)`` if any Nx3 array is allowed. Use ``()`` for the |
| 593 |
shape of scalar values (i.e. 0-dimensional). If a list, the |
| 594 |
array must have at least one of the specified shapes. |
| 595 |
|
| 596 |
name : str, default: "Array" |
| 597 |
Variable name to use in the error messages if any are raised. |
| 598 |
|
| 599 |
Raises |
| 600 |
------ |
| 601 |
ValueError |
| 602 |
If the array does not have any of the specified shape(s). |
| 603 |
|
| 604 |
See Also |
| 605 |
-------- |
| 606 |
check_length |
| 607 |
check_ndim |
| 608 |
|
| 609 |
Examples |
| 610 |
-------- |
| 611 |
Check if an array is one-dimensional. |
| 612 |
|
| 613 |
>>> import numpy as np |
| 614 |
>>> from pyvista import _validation |
| 615 |
>>> _validation.check_shape([1, 2, 3], shape=(-1)) |
| 616 |
|
| 617 |
Check if an array is one-dimensional or a scalar. |
| 618 |
|
| 619 |
>>> _validation.check_shape(1, shape=[(), (-1)]) |
| 620 |
|
| 621 |
Check if an array is 3x3 or 4x4. |
| 622 |
|
| 623 |
>>> _validation.check_shape(np.eye(3), shape=[(3, 3), (4, 4)]) |
| 624 |
|
| 625 |
""" |
| 626 |
|
| 627 |
def _shape_is_allowed(a: _Shape, b: _Shape) -> bool: |
| 628 |
# a: array's actual shape |
| 629 |
# b: allowed shape (may have -1) |
| 630 |
return len(a) == len(b) and all(map(lambda x, y: True if x == y else y == -1, a, b)) |
| 631 |
|
| 632 |
if not isinstance(shape, list): |
| 633 |
shape = [shape] |
| 634 |
|
| 635 |
array_shape = np.shape(array) # type: ignore[arg-type] |
| 636 |
for input_shape in shape: |
| 637 |
valid_shape = _validate_shape_value(input_shape) |
| 638 |
if _shape_is_allowed(array_shape, valid_shape): |
| 639 |
return |
| 640 |
|
| 641 |
msg = f'{name} has shape {array_shape} which is not allowed. ' |
| 642 |
if len(shape) == 1: |
| 643 |
msg += f'Shape must be {shape[0]}.' |
| 644 |
else: |
| 645 |
msg += f'Shape must be one of {shape}.' |
| 646 |
raise ValueError(msg) |
| 647 |
|
| 648 |
|
| 649 |
def check_ndim( |
| 650 |
array: _ArrayLikeOrScalar[NumberType], |
| 651 |
/, |
| 652 |
ndim: int | VectorLike[int], |
| 653 |
*, |
| 654 |
name: str = 'Array', |
| 655 |
) -> None: |
| 656 |
"""Check if an array has the specified number of dimensions. |
| 657 |
|
| 658 |
.. note:: |
| 659 |
Scalar values have a dimension of ``0``. |
| 660 |
|
| 661 |
Parameters |
| 662 |
---------- |
| 663 |
array : float | ArrayLike[float] |
| 664 |
Number or array to check. |
| 665 |
|
| 666 |
ndim : int | Sequence[int], optional |
| 667 |
A single dimension or a sequence of allowable dimensions. If an |
| 668 |
integer, the array must have this number of dimension(s). If a |
| 669 |
sequence, the array must have at least one of the specified number |
| 670 |
of dimensions. |
| 671 |
|
| 672 |
name : str, default: "Array" |
| 673 |
Variable name to use in the error messages if any are raised. |
| 674 |
|
| 675 |
Raises |
| 676 |
------ |
| 677 |
ValueError |
| 678 |
If the array does not have the required number of dimensions. |
| 679 |
|
| 680 |
See Also |
| 681 |
-------- |
| 682 |
check_length |
| 683 |
check_shape |
| 684 |
|
| 685 |
Examples |
| 686 |
-------- |
| 687 |
Check if an array is one-dimensional |
| 688 |
|
| 689 |
>>> import numpy as np |
| 690 |
>>> from pyvista import _validation |
| 691 |
>>> _validation.check_ndim([1, 2, 3], ndim=1) |
| 692 |
|
| 693 |
Check if an array is two-dimensional or a scalar. |
| 694 |
|
| 695 |
>>> _validation.check_ndim(1, ndim=(0, 2)) |
| 696 |
|
| 697 |
""" |
| 698 |
ndim_ = np.atleast_1d(ndim) |
| 699 |
|
| 700 |
array_ndim = _cast_to_numpy(array).ndim |
| 701 |
if array_ndim not in ndim_: |
| 702 |
check_ndim(ndim, [0, 1], name='ndim') |
| 703 |
|
| 704 |
if len(ndim_) == 1: |
| 705 |
check_integer(ndim_[0], strict=True, name='ndim') |
| 706 |
expected = f'{ndim}' |
| 707 |
else: |
| 708 |
check_integer(ndim, strict=True, name='ndim') |
| 709 |
expected = f'one of {ndim}' |
| 710 |
msg = ( |
| 711 |
f'{name} has the incorrect number of dimensions. ' |
| 712 |
f'Got {array_ndim}, expected {expected}.' |
| 713 |
) |
| 714 |
raise ValueError(msg) |
| 715 |
|
| 716 |
|
| 717 |
def check_number(num: float, /, *, name: str = 'Object') -> None: |
| 718 |
"""Check if an object is an instance of ``Number``. |
| 719 |
|
| 720 |
A number is any instance of ``numbers.Number``, e.g. ``int``, |
| 721 |
``float``, and ``complex``. |
| 722 |
|
| 723 |
Notes |
| 724 |
----- |
| 725 |
A NumPy ndarray is not an instance of ``Number``. |
| 726 |
|
| 727 |
Parameters |
| 728 |
---------- |
| 729 |
num : numbers.Number |
| 730 |
Number to check. |
| 731 |
|
| 732 |
name : str, default: "Object" |
| 733 |
Variable name to use in the error messages if any are raised. |
| 734 |
|
| 735 |
Raises |
| 736 |
------ |
| 737 |
TypeError |
| 738 |
If input is not an instance of ``Number``. |
| 739 |
|
| 740 |
Examples |
| 741 |
-------- |
| 742 |
Check if a complex number is an instance of ``Number``. |
| 743 |
|
| 744 |
>>> from pyvista import _validation |
| 745 |
>>> _validation.check_number(1 + 2j) |
| 746 |
|
| 747 |
""" |
| 748 |
check_instance(num, Number, allow_subclass=True, name=name) |
| 749 |
|
| 750 |
|
| 751 |
def check_string(obj: str, /, *, allow_subclass: bool = True, name: str = 'Object') -> None: |
| 752 |
"""Check if an object is an instance of ``str``. |
| 753 |
|
| 754 |
Parameters |
| 755 |
---------- |
| 756 |
obj : str |
| 757 |
Object to check. |
| 758 |
|
| 759 |
allow_subclass : bool, default: True |
| 760 |
If ``True``, the object's type must be ``str`` or a subclass of |
| 761 |
``str``. Otherwise, subclasses are not allowed. |
| 762 |
|
| 763 |
name : str, default: "Object" |
| 764 |
Variable name to use in the error messages if any are raised. |
| 765 |
|
| 766 |
Raises |
| 767 |
------ |
| 768 |
TypeError |
| 769 |
If input is not an instance of ``str``. |
| 770 |
|
| 771 |
See Also |
| 772 |
-------- |
| 773 |
check_contains |
| 774 |
check_iterable_items |
| 775 |
check_sequence |
| 776 |
check_instance |
| 777 |
|
| 778 |
Examples |
| 779 |
-------- |
| 780 |
Check if an object is a string. |
| 781 |
|
| 782 |
>>> from pyvista import _validation |
| 783 |
>>> _validation.check_string('eggs') |
| 784 |
|
| 785 |
""" |
| 786 |
check_instance(obj, str, allow_subclass=allow_subclass, name=name) |
| 787 |
|
| 788 |
|
| 789 |
def check_sequence(obj: Sequence[Any], /, *, name: str = 'Object') -> None: |
| 790 |
"""Check if an object is an instance of ``Sequence``. |
| 791 |
|
| 792 |
Parameters |
| 793 |
---------- |
| 794 |
obj : Sequence |
| 795 |
Object to check. |
| 796 |
|
| 797 |
name : str, default: "Object" |
| 798 |
Variable name to use in the error messages if any are raised. |
| 799 |
|
| 800 |
Raises |
| 801 |
------ |
| 802 |
TypeError |
| 803 |
If input is not an instance of ``Sequence``. |
| 804 |
|
| 805 |
See Also |
| 806 |
-------- |
| 807 |
check_iterable |
| 808 |
check_instance |
| 809 |
|
| 810 |
Examples |
| 811 |
-------- |
| 812 |
Check if an object is a sequence. |
| 813 |
|
| 814 |
>>> import numpy as np |
| 815 |
>>> from pyvista import _validation |
| 816 |
>>> _validation.check_sequence([1, 2, 3]) |
| 817 |
>>> _validation.check_sequence('A') |
| 818 |
|
| 819 |
""" |
| 820 |
check_instance(obj, Sequence, allow_subclass=True, name=name) |
| 821 |
|
| 822 |
|
| 823 |
def check_iterable(obj: Iterable[Any], /, *, name: str = 'Object') -> None: |
| 824 |
"""Check if an object is an instance of ``Iterable``. |
| 825 |
|
| 826 |
Parameters |
| 827 |
---------- |
| 828 |
obj : Iterable |
| 829 |
Iterable object to check. |
| 830 |
|
| 831 |
name : str, default: "Object" |
| 832 |
Variable name to use in the error messages if any are raised. |
| 833 |
|
| 834 |
Raises |
| 835 |
------ |
| 836 |
TypeError |
| 837 |
If input is not an instance of ``Iterable``. |
| 838 |
|
| 839 |
See Also |
| 840 |
-------- |
| 841 |
check_sequence |
| 842 |
check_instance |
| 843 |
check_iterable_items |
| 844 |
|
| 845 |
Examples |
| 846 |
-------- |
| 847 |
Check if an object is iterable. |
| 848 |
|
| 849 |
>>> import numpy as np |
| 850 |
>>> from pyvista import _validation |
| 851 |
>>> _validation.check_iterable([1, 2, 3]) |
| 852 |
>>> _validation.check_iterable(np.array((4, 5, 6))) |
| 853 |
|
| 854 |
""" |
| 855 |
check_instance(obj, Iterable, allow_subclass=True, name=name) |
| 856 |
|
| 857 |
|
| 858 |
def check_instance( |
| 859 |
obj: object, |
| 860 |
/, |
| 861 |
classinfo: type | tuple[type, ...], |
| 862 |
*, |
| 863 |
allow_subclass: bool = True, |
| 864 |
name: str = 'Object', |
| 865 |
) -> None: |
| 866 |
"""Check if an object is an instance of the given type or types. |
| 867 |
|
| 868 |
Parameters |
| 869 |
---------- |
| 870 |
obj : Any |
| 871 |
Object to check. |
| 872 |
|
| 873 |
classinfo : type | tuple[type, ...] |
| 874 |
``type`` or tuple of types. Object must be an instance of one of |
| 875 |
the types. |
| 876 |
|
| 877 |
allow_subclass : bool, default: True |
| 878 |
If ``True``, the object's type must be specified by ``classinfo`` |
| 879 |
or any of its subclasses. Otherwise, subclasses are not allowed. |
| 880 |
|
| 881 |
name : str, default: "Object" |
| 882 |
Variable name to use in the error messages if any are raised. |
| 883 |
|
| 884 |
Raises |
| 885 |
------ |
| 886 |
TypeError |
| 887 |
If object is not an instance of any of the given types. |
| 888 |
|
| 889 |
See Also |
| 890 |
-------- |
| 891 |
check_type |
| 892 |
check_number |
| 893 |
check_string |
| 894 |
check_iterable |
| 895 |
check_sequence |
| 896 |
|
| 897 |
Examples |
| 898 |
-------- |
| 899 |
Check if an object is an instance of ``complex``. |
| 900 |
|
| 901 |
>>> from pyvista import _validation |
| 902 |
>>> _validation.check_instance(1 + 2j, complex) |
| 903 |
|
| 904 |
Check if an object is an instance of one of several types. |
| 905 |
|
| 906 |
>>> _validation.check_instance('eggs', (int, str)) |
| 907 |
|
| 908 |
""" |
| 909 |
if not isinstance(name, str): |
| 910 |
msg = f'Name must be a string, got {type(name)} instead.' # type: ignore[unreachable] |
| 911 |
raise TypeError(msg) |
| 912 |
|
| 913 |
# Get class info from generics |
| 914 |
origin = get_origin(classinfo) |
| 915 |
if origin is Union or origin is types.UnionType: |
| 916 |
classinfo = get_args(classinfo) |
| 917 |
|
| 918 |
# Count num classes |
| 919 |
num_classes = len(classinfo) if isinstance(classinfo, tuple) else 1 |
| 920 |
|
| 921 |
# Check if is instance |
| 922 |
is_instance = isinstance(obj, classinfo) |
| 923 |
|
| 924 |
# Set flag to raise error if not instance |
| 925 |
is_error = False |
| 926 |
if allow_subclass and not is_instance: |
| 927 |
is_error = True |
| 928 |
if num_classes == 1: |
| 929 |
msg_body = 'must be an instance of' |
| 930 |
else: |
| 931 |
msg_body = 'must be an instance of any type' |
| 932 |
|
| 933 |
# Set flag to raise error if not type |
| 934 |
elif not allow_subclass: |
| 935 |
if isinstance(classinfo, tuple): |
| 936 |
if type(obj) not in classinfo: |
| 937 |
is_error = True |
| 938 |
msg_body = 'must have one of the following types' |
| 939 |
elif type(obj) is not classinfo: |
| 940 |
is_error = True |
| 941 |
msg_body = 'must have type' |
| 942 |
|
| 943 |
if is_error: |
| 944 |
msg = f'{name} {msg_body} {classinfo}. Got {type(obj)} instead.' |
| 945 |
raise TypeError(msg) |
| 946 |
|
| 947 |
|
| 948 |
def check_type( |
| 949 |
obj: object, /, classinfo: type | tuple[type, ...], *, name: str = 'Object' |
| 950 |
) -> None: |
| 951 |
"""Check if an object is one of the given type or types. |
| 952 |
|
| 953 |
Notes |
| 954 |
----- |
| 955 |
The use of :func:`check_instance` is generally preferred as it |
| 956 |
allows subclasses. Use :func:`check_type` only for cases where |
| 957 |
exact types are necessary. |
| 958 |
|
| 959 |
Parameters |
| 960 |
---------- |
| 961 |
obj : Any |
| 962 |
Object to check. |
| 963 |
|
| 964 |
classinfo : type | tuple[type, ...] |
| 965 |
``type`` or tuple of types. Object must be one of the types. |
| 966 |
|
| 967 |
name : str, default: "Object" |
| 968 |
Variable name to use in the error messages if any are raised. |
| 969 |
|
| 970 |
Raises |
| 971 |
------ |
| 972 |
TypeError |
| 973 |
If object is not any of the given types. |
| 974 |
|
| 975 |
See Also |
| 976 |
-------- |
| 977 |
check_instance |
| 978 |
|
| 979 |
Examples |
| 980 |
-------- |
| 981 |
Check if an object is type ``dict`` or ``set``. |
| 982 |
|
| 983 |
>>> from pyvista import _validation |
| 984 |
>>> _validation.check_type({'spam': 'eggs'}, (dict, set)) |
| 985 |
|
| 986 |
""" |
| 987 |
check_instance(obj, classinfo, allow_subclass=False, name=name) |
| 988 |
|
| 989 |
|
| 990 |
def check_iterable_items( |
| 991 |
iterable_obj: Iterable[Any], |
| 992 |
/, |
| 993 |
item_type: type | tuple[type, ...], |
| 994 |
*, |
| 995 |
allow_subclass: bool = True, |
| 996 |
name: str = 'Iterable', |
| 997 |
) -> None: |
| 998 |
"""Check if an iterable's items all have a specified type. |
| 999 |
|
| 1000 |
Parameters |
| 1001 |
---------- |
| 1002 |
iterable_obj : Iterable |
| 1003 |
Iterable to check. |
| 1004 |
|
| 1005 |
item_type : type | tuple[type, ...] |
| 1006 |
Class type(s) to check for. Each element of the sequence must |
| 1007 |
have the type or one of the types specified. |
| 1008 |
|
| 1009 |
allow_subclass : bool, default: True |
| 1010 |
If ``True``, the type of the iterable items must be any of the |
| 1011 |
given types or a subclass thereof. Otherwise, subclasses are not |
| 1012 |
allowed. |
| 1013 |
|
| 1014 |
name : str, default: "Iterable" |
| 1015 |
Variable name to use in the error messages if any are raised. |
| 1016 |
|
| 1017 |
Raises |
| 1018 |
------ |
| 1019 |
TypeError |
| 1020 |
If any of the items in the iterable have an incorrect type. |
| 1021 |
|
| 1022 |
See Also |
| 1023 |
-------- |
| 1024 |
check_instance |
| 1025 |
check_iterable |
| 1026 |
check_iterable_items |
| 1027 |
|
| 1028 |
Examples |
| 1029 |
-------- |
| 1030 |
Check if a ``tuple`` only has ``int`` or ``float`` elements. |
| 1031 |
|
| 1032 |
>>> from pyvista import _validation |
| 1033 |
>>> _validation.check_iterable_items((1, 2, 3.0), (int, float)) |
| 1034 |
|
| 1035 |
Check if a ``list`` only has ``list`` elements. |
| 1036 |
|
| 1037 |
>>> from pyvista import _validation |
| 1038 |
>>> _validation.check_iterable_items([[1], [2], [3]], list) |
| 1039 |
|
| 1040 |
""" |
| 1041 |
check_iterable(iterable_obj, name=name) |
| 1042 |
any( |
| 1043 |
check_instance( # type: ignore[func-returns-value] |
| 1044 |
item, |
| 1045 |
item_type, |
| 1046 |
allow_subclass=allow_subclass, |
| 1047 |
name=f'All items of {name}', |
| 1048 |
) |
| 1049 |
for item in iterable_obj |
| 1050 |
) |
| 1051 |
|
| 1052 |
|
| 1053 |
def check_contains( |
| 1054 |
container: Container[Any], /, must_contain: Any, *, name: str = 'Input' |
| 1055 |
) -> None: |
| 1056 |
"""Check if an item is in a container. |
| 1057 |
|
| 1058 |
Parameters |
| 1059 |
---------- |
| 1060 |
container : Any |
| 1061 |
Container to check. |
| 1062 |
|
| 1063 |
must_contain : Any |
| 1064 |
Item which must be in the container. |
| 1065 |
|
| 1066 |
name : str, default: "Input" |
| 1067 |
Variable name to use in the error messages if any are raised. |
| 1068 |
|
| 1069 |
Raises |
| 1070 |
------ |
| 1071 |
ValueError |
| 1072 |
If the item is not in the container. |
| 1073 |
|
| 1074 |
See Also |
| 1075 |
-------- |
| 1076 |
check_iterable |
| 1077 |
check_iterable_items |
| 1078 |
|
| 1079 |
Examples |
| 1080 |
-------- |
| 1081 |
Check if ``"A"`` is in a list of strings. |
| 1082 |
|
| 1083 |
>>> from pyvista import _validation |
| 1084 |
>>> _validation.check_contains(['A', 'B', 'C'], must_contain='A') |
| 1085 |
|
| 1086 |
""" |
| 1087 |
if must_contain not in container: |
| 1088 |
qualifier = 'one of' if isinstance(container, (list, tuple)) else 'in' |
| 1089 |
msg = f"{name} '{must_contain}' is not valid. {name} must be {qualifier}: \n\t{container}" |
| 1090 |
raise ValueError(msg) |
| 1091 |
|
| 1092 |
|
| 1093 |
def check_length( |
| 1094 |
sized_input: float | Sized, |
| 1095 |
/, |
| 1096 |
exact_length: int | VectorLike[int] | None = None, |
| 1097 |
*, |
| 1098 |
min_length: int | None = None, |
| 1099 |
max_length: int | None = None, |
| 1100 |
must_be_1d: bool = False, |
| 1101 |
allow_scalar: bool = False, |
| 1102 |
name: str = 'Array', |
| 1103 |
) -> None: |
| 1104 |
"""Check if the length of an array meets specific requirements. |
| 1105 |
|
| 1106 |
Notes |
| 1107 |
----- |
| 1108 |
By default, this function operates on multidimensional arrays, |
| 1109 |
where ``len(arr)`` may differ from the number of elements in the |
| 1110 |
array. For one-dimensional cases (where ``len(arr) == arr.size``), |
| 1111 |
set ``must_be_1D=True``. |
| 1112 |
|
| 1113 |
Parameters |
| 1114 |
---------- |
| 1115 |
sized_input : float | Sized |
| 1116 |
Number or array to check. |
| 1117 |
|
| 1118 |
exact_length : int | VectorLike[int], optional |
| 1119 |
Check if the array has the given length. If multiple |
| 1120 |
numbers are given, the array's length must match one of the |
| 1121 |
numbers. |
| 1122 |
|
| 1123 |
min_length : int, optional |
| 1124 |
Check if the array has this length or greater. |
| 1125 |
|
| 1126 |
max_length : int, optional |
| 1127 |
Check if the array has this length or less. |
| 1128 |
|
| 1129 |
must_be_1d : bool, default: False |
| 1130 |
If ``True``, check if the shape of the array is one-dimensional, |
| 1131 |
i.e. that the array's shape is ``(1,)``. |
| 1132 |
|
| 1133 |
allow_scalar : bool, default: False |
| 1134 |
If ``True``, a scalar input will be reshaped to have a length |
| 1135 |
of 1. Otherwise, the check will fail since a scalar does not |
| 1136 |
have a length. |
| 1137 |
|
| 1138 |
name : str, default: "Array" |
| 1139 |
Variable name to use in the error messages if any are raised. |
| 1140 |
|
| 1141 |
Raises |
| 1142 |
------ |
| 1143 |
ValueError |
| 1144 |
If the array's length is outside the specified range. |
| 1145 |
|
| 1146 |
See Also |
| 1147 |
-------- |
| 1148 |
check_shape |
| 1149 |
check_ndim |
| 1150 |
|
| 1151 |
Examples |
| 1152 |
-------- |
| 1153 |
Check if an array has a length of 2 or 3. |
| 1154 |
|
| 1155 |
>>> from pyvista import _validation |
| 1156 |
>>> _validation.check_length([1, 2], exact_length=[2, 3]) |
| 1157 |
|
| 1158 |
Check if an array has a minimum length of 3. |
| 1159 |
|
| 1160 |
>>> _validation.check_length((1, 2, 3), min_length=3) |
| 1161 |
|
| 1162 |
Check if a multidimensional array has a maximum length of 2. |
| 1163 |
|
| 1164 |
>>> _validation.check_length([[1, 2, 3], [4, 5, 6]], max_length=2) |
| 1165 |
|
| 1166 |
""" |
| 1167 |
if allow_scalar: |
| 1168 |
# Reshape to 1D |
| 1169 |
if isinstance(sized_input, np.ndarray) and sized_input.ndim == 0: |
| 1170 |
sized_input = [sized_input.tolist()] |
| 1171 |
elif isinstance(sized_input, (float, int)): |
| 1172 |
sized_input = [sized_input] |
| 1173 |
|
| 1174 |
if must_be_1d: |
| 1175 |
check_shape(sized_input, shape=(-1)) # type: ignore[arg-type] |
| 1176 |
|
| 1177 |
array_len = len(sized_input) # type: ignore[arg-type] |
| 1178 |
if exact_length is not None: |
| 1179 |
check_integer(exact_length, name="'exact_length'") |
| 1180 |
if array_len not in np.atleast_1d(exact_length): |
| 1181 |
msg = ( |
| 1182 |
f'{name} must have a length equal to any of: {exact_length}. ' |
| 1183 |
f'Got length {array_len} instead.' |
| 1184 |
) |
| 1185 |
raise ValueError(msg) |
| 1186 |
|
| 1187 |
# Validate min/max length |
| 1188 |
if min_length is not None: |
| 1189 |
check_finite(min_length, name='Min length') |
| 1190 |
if max_length is not None: |
| 1191 |
check_finite(max_length, name='Max length') |
| 1192 |
if min_length is not None and max_length is not None: |
| 1193 |
check_sorted((min_length, max_length), name='Range') |
| 1194 |
|
| 1195 |
if min_length is not None and array_len < min_length: |
| 1196 |
msg = f'{name} must have a minimum length of {min_length}. Got length {array_len} instead.' |
| 1197 |
raise ValueError(msg) |
| 1198 |
if max_length is not None and array_len > max_length: |
| 1199 |
msg = f'{name} must have a maximum length of {max_length}. Got length {array_len} instead.' |
| 1200 |
raise ValueError(msg) |
| 1201 |
|
| 1202 |
|
| 1203 |
def _validate_shape_value(shape: _ShapeLike) -> _Shape: |
| 1204 |
"""Validate shape-like input and return its tuple representation.""" |
| 1205 |
if shape is None: |
| 1206 |
# `None` is used to mean `any shape is allowed` by the array |
| 1207 |
# validation methods, so raise an error here. |
| 1208 |
# Also, setting `None` as a shape is deprecated by NumPy. |
| 1209 |
msg = '`None` is not a valid shape. Use `()` instead.' # type: ignore[unreachable] |
| 1210 |
raise TypeError(msg) |
| 1211 |
|
| 1212 |
# Return early for common inputs |
| 1213 |
if shape in [(), (-1,), (1,), (3,), (2,), (1, 3), (-1, 3)]: |
| 1214 |
return shape |
| 1215 |
|
| 1216 |
def _is_valid_dim(d: Any) -> bool: |
| 1217 |
return isinstance(d, int) and d >= -1 |
| 1218 |
|
| 1219 |
if _is_valid_dim(shape): |
| 1220 |
return (cast('int', shape),) |
| 1221 |
if isinstance(shape, tuple) and all(map(_is_valid_dim, shape)): |
| 1222 |
return shape |
| 1223 |
|
| 1224 |
# Input is not valid at this point. Use checks to raise an |
| 1225 |
# appropriate error |
| 1226 |
check_instance(shape, (int, tuple), name='Shape') |
| 1227 |
if isinstance(shape, int): |
| 1228 |
shape = (shape,) |
| 1229 |
else: |
| 1230 |
check_iterable_items(shape, int, name='Shape') |
| 1231 |
check_greater_than(shape, -1, name='Shape', strict=False) |
| 1232 |
msg = 'This line should not be reachable.' # pragma: no cover |
| 1233 |
raise RuntimeError(msg) # pragma: no cover |