Debian Codegraph @

pyvista/core/_validation/_cast_array.py

raw
1 """Array casting functions."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6
7 import numpy as np
8 import numpy.typing as npt
9
10 if TYPE_CHECKING:
11 from pyvista.core._typing_core import ArrayLike
12 from pyvista.core._typing_core import NumberType
13 from pyvista.core._typing_core import NumpyArray
14 from pyvista.core._typing_core import _ArrayLikeOrScalar
15 from pyvista.core._typing_core import _FiniteNestedList
16 from pyvista.core._typing_core import _FiniteNestedTuple
17
18
19 def _cast_to_list(
20 arr: _ArrayLikeOrScalar[NumberType],
21 ) -> NumberType | _FiniteNestedList[NumberType]:
22 """Cast an array to a nested list.
23
24 Parameters
25 ----------
26 arr : float | ArrayLike[float]
27 Array to cast.
28
29 Returns
30 -------
31 list
32 List or nested list array.
33
34 """
35 return _cast_to_numpy(arr).tolist()
36
37
38 def _cast_to_tuple(
39 arr: ArrayLike[NumberType],
40 ) -> NumberType | _FiniteNestedTuple[NumberType]:
41 """Cast an array to a nested tuple.
42
43 Parameters
44 ----------
45 arr : float | ArrayLike[float]
46 Array to cast.
47
48 Returns
49 -------
50 tuple
51 Tuple or nested tuple array.
52
53 """
54 arr = _cast_to_numpy(arr).tolist()
55
56 def _to_tuple(s):
57 return tuple(_to_tuple(i) for i in s) if isinstance(s, list) else s
58
59 return _to_tuple(arr)
60
61
62 def _cast_to_numpy(
63 arr: _ArrayLikeOrScalar[NumberType],
64 /,
65 *,
66 as_any: bool = True,
67 dtype: npt.DTypeLike | None = None,
68 copy: bool = False,
69 must_be_real: bool = False,
70 ) -> NumpyArray[NumberType]:
71 """Cast array to a NumPy ndarray.
72
73 Object arrays are not allowed but the dtype is otherwise unchecked by default.
74 String arrays and complex numbers are therefore allowed.
75
76 .. warning::
77
78 Arrays intended for use with vtk should set ``must_be_real=True``
79 since ``numpy_to_vtk`` uses the array values directly without
80 checking for complex arrays.
81
82 Parameters
83 ----------
84 arr : float | ArrayLike[float]
85 Array to cast.
86
87 as_any : bool, default: True
88 Allow subclasses of ``np.ndarray`` to pass through without
89 making a copy.
90
91 dtype : npt.typing.DTypeLike, optional
92 The data-type of the returned array.
93
94 copy : bool, default: False
95 If ``True``, a copy of the array is returned. A copy is always
96 returned if the array:
97
98 * is a nested sequence
99 * is a subclass of ``np.ndarray`` and ``as_any`` is ``False``.
100
101 must_be_real : bool, default: True
102 Raise a ``TypeError`` if the array does not have real numbers, i.e.
103 its data type is not integer or floating.
104
105 Raises
106 ------
107 ValueError
108 If input cannot be cast as a NumPy ndarray.
109 TypeError
110 If an object array is created or if the data is not real numbers
111 and ``must_be_real`` is ``True``.
112
113 Returns
114 -------
115 np.ndarray
116 NumPy ndarray.
117
118 """
119 try:
120 out = np.asanyarray(arr, dtype=dtype) if as_any else np.asarray(arr, dtype=dtype)
121
122 if copy and out is arr:
123 # we requested a copy but didn't end up with one
124 out = out.copy()
125 except ValueError as e:
126 msg = f'Input cannot be cast as {np.ndarray}.'
127 raise ValueError(msg) from e
128 if must_be_real and not issubclass(out.dtype.type, (np.floating, np.integer)):
129 msg = f'Array must have real numbers. Got dtype {out.dtype.type}'
130 raise TypeError(msg)
131 elif out.dtype.name == 'object':
132 msg = f'Object arrays are not supported. Got {arr} when casting to a NumPy array.'
133 raise TypeError(msg)
134 return out