-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtyping.py
More file actions
361 lines (270 loc) · 11.9 KB
/
Copy pathtyping.py
File metadata and controls
361 lines (270 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
"""
.. currentmodule:: arraycontext
Types and Type Variables for Arrays and Containers
--------------------------------------------------
.. autoclass:: ScalarLike
A type alias of :data:`pymbolic.Scalar`.
.. autoclass:: Array
.. autoclass:: ArrayT
A type variable with a lower bound of :class:`Array`.
See also :class:`ArrayContainer` and :class:`ArrayOrContainerT`.
.. autoclass:: ArrayOrScalar
.. autoclass:: ArrayOrScalarT
.. autoclass:: ArrayOrContainer
.. autoclass:: ArrayOrContainerT
A type variable with a bound of :class:`ArrayOrContainer`.
.. autoclass:: ArrayOrArithContainer
.. autoclass:: ArrayOrArithContainerT
.. autoclass:: ContainerOrScalarT
.. autoclass:: ArrayOrArithContainerOrScalar
.. autoclass:: ArrayOrArithContainerOrScalarT
A type variable with a bound of :class:`ArrayOrContainerOrScalar`.
.. autoclass:: ArrayOrContainerOrScalar
.. autoclass:: ArrayOrContainerOrScalarT
A type variable with a bound of :class:`ArrayOrContainerOrScalar`.
Other locations
---------------
.. currentmodule:: arraycontext.typing
.. class:: ArrayContainerT
:canonical: :class:`arraycontext.ArrayContainerT`.
"""
from __future__ import annotations
__copyright__ = """
Copyright (C) 2025 University of Illinois Board of Trustees
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# The import of 'Union' is type-ignored below because we're specifically importing
# Union to pick apart old/deprecated type annotations.
from functools import partial
from types import GenericAlias, UnionType
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Literal,
Protocol,
SupportsInt,
TypeAlias,
TypeVar,
Union, # pyright: ignore[reportDeprecated]
cast,
get_args,
get_origin,
overload,
)
import numpy as np
from typing_extensions import Self, TypeIs
from pymbolic.typing import Integer, Scalar as _Scalar
from pytools import partition2
from pytools.obj_array import ObjectArrayND
if TYPE_CHECKING:
from collections.abc import Callable
from numpy.typing import DTypeLike
from pymbolic.typing import Integer
# deprecated, use ScalarLike instead
Scalar: TypeAlias = _Scalar
ScalarLike = Scalar
ScalarLikeT = TypeVar("ScalarLikeT", bound=ScalarLike)
# {{{ array
# We won't support 'A' and 'K', since they depend on in-memory order; that is
# not intended to be a meaningful concept for actx arrays.
OrderCF: TypeAlias = Literal["C", "F"]
class Array(Protocol):
"""A :class:`~typing.Protocol` for the array type supported by
:class:`ArrayContext`.
This is meant to aid in typing annotations. For a explicit list of
supported types see :attr:`ArrayContext.array_types`.
.. attribute:: shape
.. attribute:: size
.. attribute:: dtype
.. attribute:: __getitem__
In addition, arrays are expected to support basic arithmetic.
"""
@property
def shape(self) -> tuple[Array | Integer, ...]:
...
@property
def size(self) -> Array | Integer:
...
def __len__(self) -> int: ...
@property
def dtype(self) -> np.dtype[Any]:
...
# Covering all the possible index variations is hard and (kind of) futile.
# If you'd like to see how, try changing the Any to
# AxisIndex = slice | int | "Array"
# Index = AxisIndex |tuple[AxisIndex]
def __getitem__(self, index: Any) -> Array: # pyright: ignore[reportAny]
...
# Some basic arithmetic that's supposed to work
# Need to return Array instead of Self because for some array types, arithmetic
# operations on one subtype may result in a different subtype.
# For example, pytato arrays: <Placeholder> + 1 -> <IndexLambda>
def __neg__(self) -> Array: ...
def __abs__(self) -> Array: ...
def __add__(self, other: Self | ScalarLike, /) -> Array: ...
def __radd__(self, other: Self | ScalarLike, /) -> Array: ...
def __sub__(self, other: Self | ScalarLike, /) -> Array: ...
def __rsub__(self, other: Self | ScalarLike, /) -> Array: ...
def __mul__(self, other: Self | ScalarLike, /) -> Array: ...
def __rmul__(self, other: Self | ScalarLike, /) -> Array: ...
def __pow__(self, other: Self | ScalarLike, /) -> Array: ...
def __rpow__(self, other: Self | ScalarLike, /) -> Array: ...
def __truediv__(self, other: Self | ScalarLike, /) -> Array: ...
def __rtruediv__(self, other: Self | ScalarLike, /) -> Array: ...
def copy(self) -> Self: ...
@property
def real(self) -> Array: ...
@property
def imag(self) -> Array: ...
def conj(self) -> Array: ...
def astype(self, dtype: DTypeLike) -> Array: ...
# Annoyingly, numpy 2.3.1 (and likely earlier) treats these differently when
# reshaping to the empty shape (), so we need to expose both.
@overload
def reshape(self, *shape: int, order: OrderCF = "C") -> Array: ...
@overload
def reshape(self, shape: tuple[int, ...], /, *, order: OrderCF = "C") -> Array: ...
@property
def T(self) -> Array: ... # noqa: N802
def transpose(self, axes: tuple[int, ...]) -> Array: ...
# }}}
# {{{ array container
class _UserDefinedArrayContainer(Protocol):
# This is used as a type annotation in dataclasses that are processed
# by dataclass_array_container, where it's used to recognize attributes
# that are container-typed.
# This method prevents ArrayContainer from matching any object, while
# matching numpy object arrays and many array containers.
__array_ufunc__: ClassVar[None]
ArrayContainer: TypeAlias = (
ObjectArrayND["ArrayOrContainerOrScalar"]
| _UserDefinedArrayContainer
)
class _UserDefinedArithArrayContainer(_UserDefinedArrayContainer, Protocol):
# This is loose and permissive, assuming that any array can be added
# to any container. The alternative would be to plaster type-ignores
# on all those uses. Achieving typing precision on what broadcasting is
# allowable seems like a huge endeavor and is likely not feasible without
# a mypy plugin. Maybe some day? -AK, November 2024
def __neg__(self) -> Self: ...
def __abs__(self) -> Self: ...
def __add__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __radd__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __sub__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __rsub__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __mul__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __rmul__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __truediv__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __rtruediv__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __pow__(self, other: ArrayOrScalar | Self, /) -> Self: ...
def __rpow__(self, other: ArrayOrScalar | Self, /) -> Self: ...
ArithArrayContainer: TypeAlias = (
ObjectArrayND["ArrayOrArithContainerOrScalar"]
| _UserDefinedArithArrayContainer)
ArrayContainerT = TypeVar("ArrayContainerT", bound=ArrayContainer)
ArithArrayContainerT = TypeVar("ArithArrayContainerT", bound=ArithArrayContainer)
# }}}
ArrayT = TypeVar("ArrayT", bound=Array)
ArrayOrScalar: TypeAlias = Array | ScalarLike
ArrayOrScalarT = TypeVar("ArrayOrScalarT", bound=ArrayOrScalar)
ArrayOrContainer: TypeAlias = Array | ArrayContainer
ArrayOrArithContainer: TypeAlias = Array | ArithArrayContainer
ArrayOrArithContainerTc = TypeVar("ArrayOrArithContainerTc",
Array, "ArithArrayContainer")
ArrayOrContainerT = TypeVar("ArrayOrContainerT", bound=ArrayOrContainer)
ArrayOrArithContainerT = TypeVar("ArrayOrArithContainerT", bound=ArrayOrArithContainer)
ArrayOrContainerOrScalar: TypeAlias = Array | ArrayContainer | ScalarLike
ArrayOrArithContainerOrScalar: TypeAlias = Array | ArithArrayContainer | ScalarLike
ArrayOrContainerOrScalarT = TypeVar(
"ArrayOrContainerOrScalarT",
bound=ArrayOrContainerOrScalar)
ArrayOrArithContainerOrScalarT = TypeVar(
"ArrayOrArithContainerOrScalarT",
bound=ArrayOrArithContainerOrScalar)
ContainerOrScalarT = TypeVar("ContainerOrScalarT", bound="ArrayContainer | ScalarLike")
NumpyOrContainerOrScalar: TypeAlias = "np.ndarray | ArrayContainer | ScalarLike"
def is_scalar_type(tp: object, /) -> bool:
if not isinstance(tp, type):
tp = get_origin(tp)
if not isinstance(tp, type):
return False
if tp is int or tp is bool:
# int has loads of undesirable subclasses: enums, ...
# We're not going to tolerate them.
#
# bool has to be OK because arraycontext is expected to handle
# arrays of bools.
return True
return issubclass(tp, (np.generic, float, complex))
def is_scalar_like(x: object, /) -> TypeIs[Scalar]:
return np.isscalar(x)
def shape_is_int_only(shape: tuple[Array | Integer, ...], /) -> tuple[int, ...]:
res: list[int] = []
for i, s in enumerate(shape):
try:
res.append(int(cast("SupportsInt", s)))
except TypeError:
raise TypeError(
"only non-parametric shapes are allowed in this context, "
f"axis {i+1} is {type(s)}"
) from None
return tuple(res)
def all_type_leaves_satisfy_predicate(
predicate: Callable[[type], bool],
tp: type | GenericAlias | UnionType | TypeVar,
/, *,
require_homogeneity: bool = False,
allow_containers_with_satisfying_types: bool = False,
) -> bool:
# This is horrible and brittle. I'm sorry.
rec = partial(
all_type_leaves_satisfy_predicate,
predicate,
require_homogeneity=require_homogeneity,
allow_containers_with_satisfying_types=allow_containers_with_satisfying_types
)
origin = get_origin(tp)
args = get_args(tp)
tp_or_origin = tp if origin is None else origin
if isinstance(tp_or_origin, TypeVar):
bound = cast("type | None", tp_or_origin.__bound__)
if bound is None:
return False
else:
return rec(bound)
# NOTE: `UnionType` is returned when using `Type1 | Type2`
if origin in (Union, UnionType): # pyright: ignore[reportDeprecated]
yes_types, no_types = partition2(
(rec(arg), arg) for arg in args) # pyright: ignore[reportAny]
if require_homogeneity and yes_types and no_types:
raise TypeError(f"union '{tp}' is non-homogeneous "
f"in whether it satisfies '{predicate}'")
return not no_types
if not isinstance(tp_or_origin, type):
raise TypeError(f"encountered non-type '{type(tp_or_origin)!r}'")
if predicate(tp_or_origin):
return True
if args and not allow_containers_with_satisfying_types:
# assume these are containers
has_sat_types = any(rec(arg) for arg in args) # pyright: ignore[reportAny]
if has_sat_types:
raise TypeError(f"container '{tp}' has an element type "
f"satisfying '{predicate}'")
return False