Debian Codegraph @

hypothesis-python/src/hypothesis/extra/array_api.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import math
12 import sys
13 from collections.abc import Iterable, Iterator, Mapping, Sequence
14 from numbers import Real
15 from types import SimpleNamespace
16 from typing import (
17 Any,
18 Literal,
19 NamedTuple,
20 TypeAlias,
21 TypeVar,
22 get_args,
23 )
24 from warnings import warn
25 from weakref import WeakValueDictionary
26
27 from hypothesis import strategies as st
28 from hypothesis.errors import HypothesisWarning, InvalidArgument
29 from hypothesis.extra._array_helpers import (
30 NDIM_MAX,
31 BasicIndex,
32 BasicIndexStrategy,
33 BroadcastableShapes,
34 Shape,
35 array_shapes,
36 broadcastable_shapes,
37 check_argument,
38 check_valid_dims,
39 mutually_broadcastable_shapes as _mutually_broadcastable_shapes,
40 order_check,
41 valid_tuple_axes as _valid_tuple_axes,
42 )
43 from hypothesis.internal.conjecture import utils as cu
44 from hypothesis.internal.coverage import check_function
45 from hypothesis.internal.floats import next_down
46 from hypothesis.internal.reflection import proxies
47 from hypothesis.internal.validation import (
48 check_type,
49 check_valid_bound,
50 check_valid_integer,
51 check_valid_interval,
52 )
53 from hypothesis.strategies._internal.strategies import check_strategy
54 from hypothesis.strategies._internal.utils import defines_strategy
55
56 __all__ = [
57 "make_strategies_namespace",
58 ]
59
60
61 RELEASED_VERSIONS = ("2021.12", "2022.12", "2023.12", "2024.12", "2025.12")
62 NOMINAL_VERSIONS = (*RELEASED_VERSIONS, "draft")
63 assert sorted(NOMINAL_VERSIONS) == list(NOMINAL_VERSIONS) # sanity check
64 NominalVersion = Literal["2021.12", "2022.12", "2023.12", "2024.12", "2025.12", "draft"]
65 assert get_args(NominalVersion) == NOMINAL_VERSIONS # sanity check
66
67
68 INT_NAMES = ("int8", "int16", "int32", "int64")
69 UINT_NAMES = ("uint8", "uint16", "uint32", "uint64")
70 ALL_INT_NAMES = INT_NAMES + UINT_NAMES
71 FLOAT_NAMES = ("float32", "float64")
72 REAL_NAMES = ALL_INT_NAMES + FLOAT_NAMES
73 COMPLEX_NAMES = ("complex64", "complex128")
74 NUMERIC_NAMES = REAL_NAMES + COMPLEX_NAMES
75 DTYPE_NAMES = ("bool", *NUMERIC_NAMES)
76
77 DataType = TypeVar("DataType")
78
79
80 @check_function
81 def check_xp_attributes(xp: Any, attributes: list[str]) -> None:
82 missing_attrs = [attr for attr in attributes if not hasattr(xp, attr)]
83 if len(missing_attrs) > 0:
84 f_attrs = ", ".join(missing_attrs)
85 raise InvalidArgument(
86 f"Array module {xp.__name__} does not have required attributes: {f_attrs}"
87 )
88
89
90 def partition_attributes_and_stubs(
91 xp: Any, attributes: Iterable[str]
92 ) -> tuple[list[Any], list[str]]:
93 non_stubs = []
94 stubs = []
95 for attr in attributes:
96 try:
97 non_stubs.append(getattr(xp, attr))
98 except AttributeError:
99 stubs.append(attr)
100
101 return non_stubs, stubs
102
103
104 def warn_on_missing_dtypes(xp: Any, stubs: list[str]) -> None:
105 f_stubs = ", ".join(stubs)
106 warn(
107 f"Array module {xp.__name__} does not have the following "
108 f"dtypes in its namespace: {f_stubs}",
109 HypothesisWarning,
110 stacklevel=3,
111 )
112
113
114 def find_castable_builtin_for_dtype(
115 xp: Any, api_version: NominalVersion, dtype: DataType
116 ) -> type[bool | int | float | complex]:
117 """Returns builtin type which can have values that are castable to the given
118 dtype, according to :xp-ref:`type promotion rules <type_promotion.html>`.
119
120 For floating dtypes we always return ``float``, even though ``int`` is also castable.
121 """
122 stubs = []
123
124 try:
125 bool_dtype = xp.bool
126 if dtype == bool_dtype:
127 return bool
128 except AttributeError:
129 stubs.append("bool")
130
131 int_dtypes, int_stubs = partition_attributes_and_stubs(xp, ALL_INT_NAMES)
132 if dtype in int_dtypes:
133 return int
134
135 float_dtypes, float_stubs = partition_attributes_and_stubs(xp, FLOAT_NAMES)
136 # None equals NumPy's xp.float64 object, so we specifically skip it here to
137 # ensure that InvalidArgument is still raised. xp.float64 is in fact an
138 # alias of np.dtype('float64'), and its equality with None is meant to be
139 # deprecated at some point. See https://github.com/numpy/numpy/issues/18434
140 if dtype is not None and dtype in float_dtypes:
141 return float
142
143 stubs.extend(int_stubs)
144 stubs.extend(float_stubs)
145
146 if api_version > "2021.12":
147 complex_dtypes, complex_stubs = partition_attributes_and_stubs(
148 xp, COMPLEX_NAMES
149 )
150 if dtype in complex_dtypes:
151 return complex
152 stubs.extend(complex_stubs)
153
154 if len(stubs) > 0:
155 warn_on_missing_dtypes(xp, stubs)
156 raise InvalidArgument(f"dtype={dtype} not recognised in {xp.__name__}")
157
158
159 @check_function
160 def dtype_from_name(xp: Any, name: str) -> Any:
161 if name in DTYPE_NAMES:
162 try:
163 return getattr(xp, name)
164 except AttributeError as e:
165 raise InvalidArgument(
166 f"Array module {xp.__name__} does not have dtype {name} in its namespace"
167 ) from e
168 else:
169 f_valid_dtypes = ", ".join(DTYPE_NAMES)
170 raise InvalidArgument(
171 f"{name} is not a valid Array API data type (pick from: {f_valid_dtypes})"
172 )
173
174
175 def _from_dtype(
176 xp: Any,
177 api_version: NominalVersion,
178 dtype: DataType | str,
179 *,
180 min_value: int | float | None = None,
181 max_value: int | float | None = None,
182 allow_nan: bool | None = None,
183 allow_infinity: bool | None = None,
184 allow_subnormal: bool | None = None,
185 exclude_min: bool | None = None,
186 exclude_max: bool | None = None,
187 ) -> st.SearchStrategy[bool | int | float | complex]:
188 """Return a strategy for any value of the given dtype.
189
190 Values generated are of the Python scalar which is
191 :xp-ref:`promotable <type_promotion.html>` to ``dtype``, where the values do
192 not exceed its bounds.
193
194 * ``dtype`` may be a dtype object or the string name of a
195 :xp-ref:`valid dtype <data_types.html>`.
196
197 Compatible ``**kwargs`` are passed to the inferred strategy function for
198 integers and floats. This allows you to customise the min and max values,
199 and exclude non-finite numbers. This is particularly useful when kwargs are
200 passed through from :func:`arrays()`, as it seamlessly handles the ``width``
201 or other representable bounds for you.
202 """
203 # TODO: for next released xp version, add note for complex dtype support
204 check_xp_attributes(xp, ["iinfo", "finfo"])
205
206 if isinstance(dtype, str):
207 dtype = dtype_from_name(xp, dtype)
208 builtin = find_castable_builtin_for_dtype(xp, api_version, dtype)
209
210 def check_valid_minmax(prefix, val, info_obj):
211 name = f"{prefix}_value"
212 check_valid_bound(val, name)
213 check_argument(
214 val >= info_obj.min,
215 f"dtype={dtype} requires {name}={val} to be at least {info_obj.min}",
216 )
217 check_argument(
218 val <= info_obj.max,
219 f"dtype={dtype} requires {name}={val} to be at most {info_obj.max}",
220 )
221
222 if builtin is bool:
223 return st.booleans()
224 elif builtin is int:
225 iinfo = xp.iinfo(dtype)
226 if min_value is None:
227 min_value = iinfo.min
228 if max_value is None:
229 max_value = iinfo.max
230 check_valid_integer(min_value, "min_value")
231 check_valid_integer(max_value, "max_value")
232 assert isinstance(min_value, int)
233 assert isinstance(max_value, int)
234 check_valid_minmax("min", min_value, iinfo)
235 check_valid_minmax("max", max_value, iinfo)
236 check_valid_interval(min_value, max_value, "min_value", "max_value")
237 return st.integers(min_value=min_value, max_value=max_value)
238 elif builtin is float:
239 finfo = xp.finfo(dtype)
240 kw = {}
241
242 # Whilst we know the boundary values of float dtypes from finfo, we do
243 # not assign them to the floats() strategy by default - passing min/max
244 # values will modify test case reduction behaviour so that simple bugs
245 # may become harder for users to identify. We plan to improve floats()
246 # behaviour in https://github.com/HypothesisWorks/hypothesis/issues/2907.
247 # Setting width should manage boundary values for us anyway.
248 if min_value is not None:
249 check_valid_bound(min_value, "min_value")
250 assert isinstance(min_value, Real)
251 check_valid_minmax("min", min_value, finfo)
252 kw["min_value"] = min_value
253 if max_value is not None:
254 check_valid_bound(max_value, "max_value")
255 assert isinstance(max_value, Real)
256 check_valid_minmax("max", max_value, finfo)
257 if min_value is not None:
258 check_valid_interval(min_value, max_value, "min_value", "max_value")
259 kw["max_value"] = max_value
260
261 # We infer whether an array module will flush subnormals to zero, as may
262 # be the case when libraries are built with compiler options that
263 # violate IEEE-754 (e.g. -ffast-math and -ftz=true). Note we do this for
264 # the specific dtype, as compilers may end up flushing subnormals for
265 # one float but supporting subnormals for the other.
266 #
267 # By default, floats() will generate subnormals if they are in the
268 # inferred values range. If we have detected that xp flushes to zero for
269 # the passed dtype, we ensure from_dtype() will not generate subnormals
270 # by default.
271 if allow_subnormal is not None:
272 kw["allow_subnormal"] = allow_subnormal
273 else:
274 subnormal = next_down(float(finfo.smallest_normal), width=finfo.bits)
275 ftz = bool(xp.asarray(subnormal, dtype=dtype) == 0)
276 if ftz:
277 kw["allow_subnormal"] = False
278
279 if allow_nan is not None:
280 kw["allow_nan"] = allow_nan
281 if allow_infinity is not None:
282 kw["allow_infinity"] = allow_infinity
283 if exclude_min is not None:
284 kw["exclude_min"] = exclude_min
285 if exclude_max is not None:
286 kw["exclude_max"] = exclude_max
287
288 return st.floats(width=finfo.bits, **kw)
289 else:
290 finfo = xp.finfo(dtype)
291 # See above comment on FTZ inference. We explicitly infer with a
292 # complex array, in case complex arrays have different FTZ behaviour
293 # than arrays of the respective composite float.
294 if allow_subnormal is None:
295 subnormal = next_down(float(finfo.smallest_normal), width=finfo.bits)
296 x = xp.asarray(complex(subnormal, subnormal), dtype=dtype)
297 builtin_x = complex(x)
298 allow_subnormal = builtin_x.real != 0 and builtin_x.imag != 0
299 return st.complex_numbers(
300 allow_nan=allow_nan,
301 allow_infinity=allow_infinity,
302 allow_subnormal=allow_subnormal,
303 width=finfo.bits * 2,
304 )
305
306
307 class ArrayStrategy(st.SearchStrategy):
308 def __init__(
309 self, *, xp, api_version, elements_strategy, dtype, shape, fill, unique
310 ):
311 super().__init__()
312 self.xp = xp
313 self.elements_strategy = elements_strategy
314 self.dtype = dtype
315 self.shape = shape
316 self.fill = fill
317 self.unique = unique
318 self.array_size = math.prod(shape)
319 self.builtin = find_castable_builtin_for_dtype(xp, api_version, dtype)
320 self.finfo = None if self.builtin is not float else xp.finfo(self.dtype)
321
322 def check_set_value(self, val, val_0d, strategy):
323 if val == val and self.builtin(val_0d) != val:
324 if self.builtin is float:
325 assert self.finfo is not None # for mypy
326 try:
327 is_subnormal = 0 < abs(val) < self.finfo.smallest_normal
328 except Exception:
329 # val may be a non-float that does not support the
330 # operations __lt__ and __abs__
331 is_subnormal = False
332 if is_subnormal:
333 raise InvalidArgument(
334 f"Generated subnormal float {val} from strategy "
335 f"{strategy} resulted in {val_0d!r}, probably "
336 f"as a result of array module {self.xp.__name__} "
337 "being built with flush-to-zero compiler options. "
338 "Consider passing allow_subnormal=False."
339 )
340 raise InvalidArgument(
341 f"Generated array element {val!r} from strategy {strategy} "
342 f"cannot be represented with dtype {self.dtype}. "
343 f"Array module {self.xp.__name__} instead "
344 f"represents the element as {val_0d}. "
345 "Consider using a more precise elements strategy, "
346 "for example passing the width argument to floats()."
347 )
348
349 def do_draw(self, data):
350 if 0 in self.shape:
351 return self.xp.zeros(self.shape, dtype=self.dtype)
352
353 if self.fill.is_empty:
354 # We have no fill value (either because the user explicitly
355 # disabled it or because the default behaviour was used and our
356 # elements strategy does not produce reusable values), so we must
357 # generate a fully dense array with a freshly drawn value for each
358 # entry.
359 elems = data.draw(
360 st.lists(
361 self.elements_strategy,
362 min_size=self.array_size,
363 max_size=self.array_size,
364 unique=self.unique,
365 )
366 )
367 try:
368 result = self.xp.asarray(elems, dtype=self.dtype)
369 except Exception as e:
370 if len(elems) <= 6:
371 f_elems = str(elems)
372 else:
373 f_elems = f"[{elems[0]}, {elems[1]}, ..., {elems[-2]}, {elems[-1]}]"
374 types = tuple(
375 sorted({type(e) for e in elems}, key=lambda t: t.__name__)
376 )
377 f_types = f"type {types[0]}" if len(types) == 1 else f"types {types}"
378 raise InvalidArgument(
379 f"Generated elements {f_elems} from strategy "
380 f"{self.elements_strategy} could not be converted "
381 f"to array of dtype {self.dtype}. "
382 f"Consider if elements of {f_types} "
383 f"are compatible with {self.dtype}."
384 ) from e
385 for i in range(self.array_size):
386 self.check_set_value(elems[i], result[i], self.elements_strategy)
387 else:
388 # We draw arrays as "sparse with an offset". We assume not every
389 # element will be assigned and so first draw a single value from our
390 # fill strategy to create a full array. We then draw a collection of
391 # index assignments within the array and assign fresh values from
392 # our elements strategy to those indices.
393
394 fill_val = data.draw(self.fill)
395 result_obj = [fill_val for _ in range(self.array_size)]
396 fill_mask = [True for _ in range(self.array_size)]
397
398 elements = cu.many(
399 data,
400 min_size=0,
401 max_size=self.array_size,
402 # sqrt isn't chosen for any particularly principled reason. It
403 # just grows reasonably quickly but sublinearly, and for small
404 # arrays it represents a decent fraction of the array size.
405 average_size=min(
406 0.9 * self.array_size, # ensure small arrays sometimes use fill
407 max(10, math.sqrt(self.array_size)), # ...but *only* sometimes
408 ),
409 )
410
411 assigned = set()
412 seen = set()
413
414 while elements.more():
415 i = data.draw_integer(0, self.array_size - 1)
416 if i in assigned:
417 elements.reject("chose an array index we've already used")
418 continue
419 val = data.draw(self.elements_strategy)
420 if self.unique:
421 if val in seen:
422 elements.reject("chose an element we've already used")
423 continue
424 seen.add(val)
425
426 result_obj[i] = val
427 assigned.add(i)
428 fill_mask[i] = False
429
430 try:
431 result = self.xp.asarray(result_obj, dtype=self.dtype)
432 except Exception as e:
433 f_expr = f"xp.asarray({result_obj}, dtype={self.dtype})"
434 raise InvalidArgument(f"Could not create array via {f_expr}") from e
435
436 for i, val in enumerate(result_obj):
437 val_0d = result[i]
438 if fill_mask[i] and self.unique:
439 if not self.xp.isnan(val_0d):
440 raise InvalidArgument(
441 f"Array module {self.xp.__name__} did not recognise fill "
442 f"value {fill_val!r} as NaN - instead got {val_0d!r}. "
443 "Cannot fill unique array with non-NaN values."
444 )
445 else:
446 self.check_set_value(val, val_0d, self.elements_strategy)
447
448 return self.xp.reshape(result, self.shape)
449
450
451 def _arrays(
452 xp: Any,
453 api_version: NominalVersion,
454 dtype: DataType | str | st.SearchStrategy[DataType] | st.SearchStrategy[str],
455 shape: int | Shape | st.SearchStrategy[Shape],
456 *,
457 elements: Mapping[str, Any] | st.SearchStrategy | None = None,
458 fill: st.SearchStrategy[Any] | None = None,
459 unique: bool = False,
460 ) -> st.SearchStrategy:
461 """Returns a strategy for :xp-ref:`arrays <array_object.html>`.
462
463 * ``dtype`` may be a :xp-ref:`valid dtype <data_types.html>` object or name,
464 or a strategy that generates such values.
465 * ``shape`` may be an integer >= 0, a tuple of such integers, or a strategy
466 that generates such values.
467 * ``elements`` is a strategy for values to put in the array. If ``None``
468 then a suitable value will be inferred based on the dtype, which may give
469 any legal value (including e.g. NaN for floats). If a mapping, it will be
470 passed as ``**kwargs`` to :func:`from_dtype()` when inferring based on the dtype.
471 * ``fill`` is a strategy that may be used to generate a single background
472 value for the array. If ``None``, a suitable default will be inferred
473 based on the other arguments. If set to
474 :func:`~hypothesis.strategies.nothing` then filling behaviour will be
475 disabled entirely and every element will be generated independently.
476 * ``unique`` specifies if the elements of the array should all be distinct
477 from one another; if fill is also set, the only valid values for fill to
478 return are NaN values.
479
480 Arrays of specified ``dtype`` and ``shape`` are generated for example
481 like this:
482
483 .. code-block:: pycon
484
485 >>> from numpy import array_api as xp
486 >>> xps.arrays(xp, xp.int8, (2, 3)).example()
487 Array([[-8, 6, 3],
488 [-6, 4, 6]], dtype=int8)
489
490 Specifying element boundaries by a :obj:`python:dict` of the kwargs to pass
491 to :func:`from_dtype` will ensure ``dtype`` bounds will be respected.
492
493 .. code-block:: pycon
494
495 >>> xps.arrays(xp, xp.int8, 3, elements={"min_value": 10}).example()
496 Array([125, 13, 79], dtype=int8)
497
498 .. code-block:: pycon
499
500 >>> xps.arrays(xp, xp.float32, 3, elements=floats(0, 1, width=32)).example()
501 Array([ 0.88974794, 0.77387938, 0.1977879 ], dtype=float32)
502
503 Array values are generated in two parts:
504
505 1. A single value is drawn from the fill strategy and is used to create a
506 filled array.
507 2. Some subset of the coordinates of the array are populated with a value
508 drawn from the elements strategy (or its inferred form).
509
510 You can set ``fill`` to :func:`~hypothesis.strategies.nothing` if you want
511 to disable this behaviour and draw a value for every element.
512
513 By default ``arrays`` will attempt to infer the correct fill behaviour: if
514 ``unique`` is also ``True``, no filling will occur. Otherwise, if it looks
515 safe to reuse the values of elements across multiple coordinates (this will
516 be the case for any inferred strategy, and for most of the builtins, but is
517 not the case for mutable values or strategies built with flatmap, map,
518 composite, etc.) then it will use the elements strategy as the fill, else it
519 will default to having no fill.
520
521 Having a fill helps Hypothesis craft high quality examples, but its
522 main importance is when the array generated is large: Hypothesis is
523 primarily designed around testing small examples. If you have arrays with
524 hundreds or more elements, having a fill value is essential if you want
525 your tests to run in reasonable time.
526 """
527 check_xp_attributes(
528 xp, ["finfo", "asarray", "zeros", "all", "isnan", "isfinite", "reshape"]
529 )
530
531 if isinstance(dtype, st.SearchStrategy):
532 return dtype.flatmap(
533 lambda d: _arrays(
534 xp, api_version, d, shape, elements=elements, fill=fill, unique=unique
535 )
536 )
537 elif isinstance(dtype, str):
538 dtype = dtype_from_name(xp, dtype)
539
540 if isinstance(shape, st.SearchStrategy):
541 return shape.flatmap(
542 lambda s: _arrays(
543 xp, api_version, dtype, s, elements=elements, fill=fill, unique=unique
544 )
545 )
546 elif isinstance(shape, int):
547 shape = (shape,)
548 elif not isinstance(shape, tuple):
549 raise InvalidArgument(f"shape={shape} is not a valid shape or strategy")
550 check_argument(
551 all(isinstance(x, int) and x >= 0 for x in shape),
552 f"{shape=}, but all dimensions must be non-negative integers.",
553 )
554
555 if elements is None:
556 elements = _from_dtype(xp, api_version, dtype)
557 elif isinstance(elements, Mapping):
558 elements = _from_dtype(xp, api_version, dtype, **elements)
559 check_strategy(elements, "elements")
560
561 if fill is None:
562 assert isinstance(elements, st.SearchStrategy) # for mypy
563 if unique or not elements.has_reusable_values:
564 fill = st.nothing()
565 else:
566 fill = elements
567 check_strategy(fill, "fill")
568
569 return ArrayStrategy(
570 xp=xp,
571 api_version=api_version,
572 elements_strategy=elements,
573 dtype=dtype,
574 shape=shape,
575 fill=fill,
576 unique=unique,
577 )
578
579
580 @check_function
581 def check_dtypes(xp: Any, dtypes: list[DataType], stubs: list[str]) -> None:
582 if len(dtypes) == 0:
583 assert len(stubs) > 0, "No dtypes passed but stubs is empty"
584 f_stubs = ", ".join(stubs)
585 raise InvalidArgument(
586 f"Array module {xp.__name__} does not have the following "
587 f"required dtypes in its namespace: {f_stubs}"
588 )
589 elif len(stubs) > 0:
590 warn_on_missing_dtypes(xp, stubs)
591
592
593 def _scalar_dtypes(xp: Any, api_version: NominalVersion) -> st.SearchStrategy[DataType]:
594 """Return a strategy for all :xp-ref:`valid dtype <data_types.html>` objects."""
595 return st.one_of(_boolean_dtypes(xp), _numeric_dtypes(xp, api_version))
596
597
598 def _boolean_dtypes(xp: Any) -> st.SearchStrategy[DataType]:
599 """Return a strategy for just the boolean dtype object."""
600 try:
601 return st.just(xp.bool)
602 except AttributeError:
603 raise InvalidArgument(
604 f"Array module {xp.__name__} does not have a bool dtype in its namespace"
605 ) from None
606
607
608 def _real_dtypes(xp: Any) -> st.SearchStrategy[DataType]:
609 """Return a strategy for all real-valued dtype objects."""
610 return st.one_of(
611 _integer_dtypes(xp),
612 _unsigned_integer_dtypes(xp),
613 _floating_dtypes(xp),
614 )
615
616
617 def _numeric_dtypes(
618 xp: Any, api_version: NominalVersion
619 ) -> st.SearchStrategy[DataType]:
620 """Return a strategy for all numeric dtype objects."""
621 strat: st.SearchStrategy[DataType] = _real_dtypes(xp)
622 if api_version > "2021.12":
623 strat |= _complex_dtypes(xp)
624 return strat
625
626
627 @check_function
628 def check_valid_sizes(
629 category: str, sizes: Sequence[int], valid_sizes: Sequence[int]
630 ) -> None:
631 check_argument(len(sizes) > 0, "No sizes passed")
632
633 invalid_sizes = [s for s in sizes if s not in valid_sizes]
634 f_valid_sizes = ", ".join(str(s) for s in valid_sizes)
635 f_invalid_sizes = ", ".join(str(s) for s in invalid_sizes)
636 check_argument(
637 len(invalid_sizes) == 0,
638 f"The following sizes are not valid for {category} dtypes: "
639 f"{f_invalid_sizes} (valid sizes: {f_valid_sizes})",
640 )
641
642
643 def numeric_dtype_names(base_name: str, sizes: Sequence[int]) -> Iterator[str]:
644 for size in sizes:
645 yield f"{base_name}{size}"
646
647
648 IntSize: TypeAlias = Literal[8, 16, 32, 64]
649 FltSize: TypeAlias = Literal[32, 64]
650 CpxSize: TypeAlias = Literal[64, 128]
651
652
653 def _integer_dtypes(
654 xp: Any, *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
655 ) -> st.SearchStrategy[DataType]:
656 """Return a strategy for signed integer dtype objects.
657
658 ``sizes`` contains the signed integer sizes in bits, defaulting to
659 ``(8, 16, 32, 64)`` which covers all valid sizes.
660 """
661 if isinstance(sizes, int):
662 sizes = (sizes,)
663 check_valid_sizes("int", sizes, (8, 16, 32, 64))
664 dtypes, stubs = partition_attributes_and_stubs(
665 xp, numeric_dtype_names("int", sizes)
666 )
667 check_dtypes(xp, dtypes, stubs)
668 return st.sampled_from(dtypes)
669
670
671 def _unsigned_integer_dtypes(
672 xp: Any, *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
673 ) -> st.SearchStrategy[DataType]:
674 """Return a strategy for unsigned integer dtype objects.
675
676 ``sizes`` contains the unsigned integer sizes in bits, defaulting to
677 ``(8, 16, 32, 64)`` which covers all valid sizes.
678 """
679 if isinstance(sizes, int):
680 sizes = (sizes,)
681 check_valid_sizes("int", sizes, (8, 16, 32, 64))
682
683 dtypes, stubs = partition_attributes_and_stubs(
684 xp, numeric_dtype_names("uint", sizes)
685 )
686 check_dtypes(xp, dtypes, stubs)
687
688 return st.sampled_from(dtypes)
689
690
691 def _floating_dtypes(
692 xp: Any, *, sizes: FltSize | Sequence[FltSize] = (32, 64)
693 ) -> st.SearchStrategy[DataType]:
694 """Return a strategy for real-valued floating-point dtype objects.
695
696 ``sizes`` contains the floating-point sizes in bits, defaulting to
697 ``(32, 64)`` which covers all valid sizes.
698 """
699 if isinstance(sizes, int):
700 sizes = (sizes,)
701 check_valid_sizes("int", sizes, (32, 64))
702 dtypes, stubs = partition_attributes_and_stubs(
703 xp, numeric_dtype_names("float", sizes)
704 )
705 check_dtypes(xp, dtypes, stubs)
706 return st.sampled_from(dtypes)
707
708
709 def _complex_dtypes(
710 xp: Any, *, sizes: CpxSize | Sequence[CpxSize] = (64, 128)
711 ) -> st.SearchStrategy[DataType]:
712 """Return a strategy for complex dtype objects.
713
714 ``sizes`` contains the complex sizes in bits, defaulting to ``(64, 128)``
715 which covers all valid sizes.
716 """
717 if isinstance(sizes, int):
718 sizes = (sizes,)
719 check_valid_sizes("complex", sizes, (64, 128))
720 dtypes, stubs = partition_attributes_and_stubs(
721 xp, numeric_dtype_names("complex", sizes)
722 )
723 check_dtypes(xp, dtypes, stubs)
724 return st.sampled_from(dtypes)
725
726
727 @proxies(_valid_tuple_axes)
728 def valid_tuple_axes(*args, **kwargs):
729 return _valid_tuple_axes(*args, **kwargs)
730
731
732 valid_tuple_axes.__doc__ = f"""
733 Return a strategy for permissible tuple-values for the ``axis``
734 argument in Array API sequential methods e.g. ``sum``, given the specified
735 dimensionality.
736
737 {_valid_tuple_axes.__doc__}
738 """
739
740
741 @defines_strategy()
742 def mutually_broadcastable_shapes(
743 num_shapes: int,
744 *,
745 base_shape: Shape = (),
746 min_dims: int = 0,
747 max_dims: int | None = None,
748 min_side: int = 1,
749 max_side: int | None = None,
750 ) -> st.SearchStrategy[BroadcastableShapes]:
751 return _mutually_broadcastable_shapes(
752 num_shapes=num_shapes,
753 base_shape=base_shape,
754 min_dims=min_dims,
755 max_dims=max_dims,
756 min_side=min_side,
757 max_side=max_side,
758 )
759
760
761 mutually_broadcastable_shapes.__doc__ = _mutually_broadcastable_shapes.__doc__
762
763
764 @defines_strategy()
765 def indices(
766 shape: Shape,
767 *,
768 min_dims: int = 0,
769 max_dims: int | None = None,
770 allow_newaxis: bool = False,
771 allow_ellipsis: bool = True,
772 ) -> st.SearchStrategy[BasicIndex]:
773 """Return a strategy for :xp-ref:`valid indices <indexing.html>` of
774 arrays with the specified shape, which may include dimensions of size zero.
775
776 It generates tuples containing some mix of integers, :obj:`python:slice`
777 objects, ``...`` (an ``Ellipsis``), and ``None``. When a length-one tuple
778 would be generated, this strategy may instead return the element which will
779 index the first axis, e.g. ``5`` instead of ``(5,)``.
780
781 * ``shape`` is the shape of the array that will be indexed, as a tuple of
782 integers >= 0. This must be at least two-dimensional for a tuple to be a
783 valid index; for one-dimensional arrays use
784 :func:`~hypothesis.strategies.slices` instead.
785 * ``min_dims`` is the minimum dimensionality of the resulting array from use
786 of the generated index.
787 * ``max_dims`` is the maximum dimensionality of the resulting array,
788 defaulting to ``len(shape) if not allow_newaxis else
789 max(len(shape), min_dims) + 2``.
790 * ``allow_ellipsis`` specifies whether ``None`` is allowed in the index.
791 * ``allow_ellipsis`` specifies whether ``...`` is allowed in the index.
792 """
793 check_type(tuple, shape, "shape")
794 check_argument(
795 all(isinstance(x, int) and x >= 0 for x in shape),
796 f"{shape=}, but all dimensions must be non-negative integers.",
797 )
798 check_type(bool, allow_newaxis, "allow_newaxis")
799 check_type(bool, allow_ellipsis, "allow_ellipsis")
800 check_type(int, min_dims, "min_dims")
801 if not allow_newaxis:
802 check_argument(
803 min_dims <= len(shape),
804 f"min_dims={min_dims} is larger than len(shape)={len(shape)}, "
805 "but it is impossible for an indexing operation to add dimensions ",
806 "when allow_newaxis=False.",
807 )
808 check_valid_dims(min_dims, "min_dims")
809
810 if max_dims is None:
811 if allow_newaxis:
812 max_dims = min(max(len(shape), min_dims) + 2, NDIM_MAX)
813 else:
814 max_dims = min(len(shape), NDIM_MAX)
815 check_type(int, max_dims, "max_dims")
816 assert isinstance(max_dims, int)
817 if not allow_newaxis:
818 check_argument(
819 max_dims <= len(shape),
820 f"max_dims={max_dims} is larger than len(shape)={len(shape)}, "
821 "but it is impossible for an indexing operation to add dimensions ",
822 "when allow_newaxis=False.",
823 )
824 check_valid_dims(max_dims, "max_dims")
825
826 order_check("dims", 0, min_dims, max_dims)
827
828 return BasicIndexStrategy(
829 shape,
830 min_dims=min_dims,
831 max_dims=max_dims,
832 allow_ellipsis=allow_ellipsis,
833 allow_newaxis=allow_newaxis,
834 allow_fewer_indices_than_dims=False,
835 )
836
837
838 # Cache for make_strategies_namespace()
839 _args_to_xps: WeakValueDictionary = WeakValueDictionary()
840
841
842 def make_strategies_namespace(
843 xp: Any, *, api_version: NominalVersion | None = None
844 ) -> SimpleNamespace:
845 """Creates a strategies namespace for the given array module.
846
847 * ``xp`` is the Array API library to automatically pass to the namespaced methods.
848 * ``api_version`` is the version of the Array API which the returned
849 strategies namespace should conform to. If ``None``, the latest API
850 version which ``xp`` supports will be inferred from ``xp.__array_api_version__``.
851 If a version string in the ``YYYY.MM`` format, the strategies namespace
852 will conform to that version if supported.
853
854 A :obj:`python:types.SimpleNamespace` is returned which contains all the
855 strategy methods in this module but without requiring the ``xp`` argument.
856 Creating and using a strategies namespace for NumPy's Array API
857 implementation would go like this:
858
859 .. code-block:: pycon
860
861 >>> xp.__array_api_version__ # xp is your desired array library
862 '2021.12'
863 >>> xps = make_strategies_namespace(xp)
864 >>> xps.api_version
865 '2021.12'
866 >>> x = xps.arrays(xp.int8, (2, 3)).example()
867 >>> x
868 Array([[-8, 6, 3],
869 [-6, 4, 6]], dtype=int8)
870 >>> x.__array_namespace__() is xp
871 True
872
873 """
874 not_available_msg = (
875 "If the standard version you want is not available, please ensure "
876 "you're using the latest version of Hypothesis, then open an issue if "
877 "one doesn't already exist."
878 )
879 if api_version is None:
880 check_argument(
881 hasattr(xp, "__array_api_version__"),
882 f"Array module {xp.__name__} has no attribute __array_api_version__, "
883 "which is required when inferring api_version. If you believe "
884 f"{xp.__name__} is indeed an Array API module, try explicitly "
885 "passing an api_version.",
886 )
887 check_argument(
888 isinstance(xp.__array_api_version__, str)
889 and xp.__array_api_version__ in RELEASED_VERSIONS,
890 f"{xp.__array_api_version__=}, but it must "
891 f"be a valid version string {RELEASED_VERSIONS}. {not_available_msg}",
892 )
893 api_version = xp.__array_api_version__
894 inferred_version = True
895 else:
896 check_argument(
897 isinstance(api_version, str) and api_version in NOMINAL_VERSIONS,
898 f"{api_version=}, but it must be None, or a valid version "
899 f"string in {RELEASED_VERSIONS}. {not_available_msg}",
900 )
901 inferred_version = False
902 try:
903 array = xp.zeros(1)
904 array.__array_namespace__()
905 except Exception:
906 warn(
907 f"Could not determine whether module {xp.__name__} is an Array API library",
908 HypothesisWarning,
909 stacklevel=2,
910 )
911
912 try:
913 namespace = _args_to_xps[(xp, api_version)]
914 except (KeyError, TypeError):
915 pass
916 else:
917 return namespace
918
919 @defines_strategy(force_reusable_values=True)
920 def from_dtype(
921 dtype: DataType | str,
922 *,
923 min_value: int | float | None = None,
924 max_value: int | float | None = None,
925 allow_nan: bool | None = None,
926 allow_infinity: bool | None = None,
927 allow_subnormal: bool | None = None,
928 exclude_min: bool | None = None,
929 exclude_max: bool | None = None,
930 ) -> st.SearchStrategy[bool | int | float | complex]:
931 return _from_dtype(
932 xp,
933 api_version,
934 dtype,
935 min_value=min_value,
936 max_value=max_value,
937 allow_nan=allow_nan,
938 allow_infinity=allow_infinity,
939 allow_subnormal=allow_subnormal,
940 exclude_min=exclude_min,
941 exclude_max=exclude_max,
942 )
943
944 @defines_strategy(force_reusable_values=True)
945 def arrays(
946 dtype: DataType | str | st.SearchStrategy[DataType] | st.SearchStrategy[str],
947 shape: int | Shape | st.SearchStrategy[Shape],
948 *,
949 elements: Mapping[str, Any] | st.SearchStrategy | None = None,
950 fill: st.SearchStrategy[Any] | None = None,
951 unique: bool = False,
952 ) -> st.SearchStrategy:
953 return _arrays(
954 xp,
955 api_version,
956 dtype,
957 shape,
958 elements=elements,
959 fill=fill,
960 unique=unique,
961 )
962
963 @defines_strategy()
964 def scalar_dtypes() -> st.SearchStrategy[DataType]:
965 return _scalar_dtypes(xp, api_version)
966
967 @defines_strategy()
968 def boolean_dtypes() -> st.SearchStrategy[DataType]:
969 return _boolean_dtypes(xp)
970
971 @defines_strategy()
972 def real_dtypes() -> st.SearchStrategy[DataType]:
973 return _real_dtypes(xp)
974
975 @defines_strategy()
976 def numeric_dtypes() -> st.SearchStrategy[DataType]:
977 return _numeric_dtypes(xp, api_version)
978
979 @defines_strategy()
980 def integer_dtypes(
981 *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
982 ) -> st.SearchStrategy[DataType]:
983 return _integer_dtypes(xp, sizes=sizes)
984
985 @defines_strategy()
986 def unsigned_integer_dtypes(
987 *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
988 ) -> st.SearchStrategy[DataType]:
989 return _unsigned_integer_dtypes(xp, sizes=sizes)
990
991 @defines_strategy()
992 def floating_dtypes(
993 *, sizes: FltSize | Sequence[FltSize] = (32, 64)
994 ) -> st.SearchStrategy[DataType]:
995 return _floating_dtypes(xp, sizes=sizes)
996
997 from_dtype.__doc__ = _from_dtype.__doc__
998 arrays.__doc__ = _arrays.__doc__
999 scalar_dtypes.__doc__ = _scalar_dtypes.__doc__
1000 boolean_dtypes.__doc__ = _boolean_dtypes.__doc__
1001 real_dtypes.__doc__ = _real_dtypes.__doc__
1002 numeric_dtypes.__doc__ = _numeric_dtypes.__doc__
1003 integer_dtypes.__doc__ = _integer_dtypes.__doc__
1004 unsigned_integer_dtypes.__doc__ = _unsigned_integer_dtypes.__doc__
1005 floating_dtypes.__doc__ = _floating_dtypes.__doc__
1006
1007 class StrategiesNamespace(SimpleNamespace):
1008 def __init__(self, **kwargs):
1009 for attr in ["name", "api_version"]:
1010 if attr not in kwargs:
1011 raise ValueError(f"'{attr}' kwarg required")
1012 super().__init__(**kwargs)
1013
1014 @property
1015 def complex_dtypes(self):
1016 try:
1017 return self.__dict__["complex_dtypes"]
1018 except KeyError as e:
1019 raise AttributeError(
1020 "You attempted to access 'complex_dtypes', but it is not "
1021 f"available for api_version='{self.api_version}' of "
1022 f"xp={self.name}."
1023 ) from e
1024
1025 def __repr__(self):
1026 f_args = self.name
1027 if not inferred_version:
1028 f_args += f", api_version='{self.api_version}'"
1029 return f"make_strategies_namespace({f_args})"
1030
1031 kwargs = {
1032 "name": xp.__name__,
1033 "api_version": api_version,
1034 "from_dtype": from_dtype,
1035 "arrays": arrays,
1036 "array_shapes": array_shapes,
1037 "scalar_dtypes": scalar_dtypes,
1038 "boolean_dtypes": boolean_dtypes,
1039 "real_dtypes": real_dtypes,
1040 "numeric_dtypes": numeric_dtypes,
1041 "integer_dtypes": integer_dtypes,
1042 "unsigned_integer_dtypes": unsigned_integer_dtypes,
1043 "floating_dtypes": floating_dtypes,
1044 "valid_tuple_axes": valid_tuple_axes,
1045 "broadcastable_shapes": broadcastable_shapes,
1046 "mutually_broadcastable_shapes": mutually_broadcastable_shapes,
1047 "indices": indices,
1048 }
1049
1050 if api_version > "2021.12":
1051
1052 @defines_strategy()
1053 def complex_dtypes(
1054 *, sizes: CpxSize | Sequence[CpxSize] = (64, 128)
1055 ) -> st.SearchStrategy[DataType]:
1056 return _complex_dtypes(xp, sizes=sizes)
1057
1058 complex_dtypes.__doc__ = _complex_dtypes.__doc__
1059 kwargs["complex_dtypes"] = complex_dtypes
1060
1061 namespace = StrategiesNamespace(**kwargs)
1062 try:
1063 _args_to_xps[(xp, api_version)] = namespace
1064 except TypeError:
1065 pass
1066
1067 return namespace
1068
1069
1070 try:
1071 import numpy as np
1072 except ImportError:
1073 if "sphinx" in sys.modules:
1074 # This is pretty awkward, but also the best way available
1075 from unittest.mock import Mock
1076
1077 np = Mock()
1078 else:
1079 np = None # type: ignore[assignment]
1080 if np is not None:
1081
1082 class FloatInfo(NamedTuple):
1083 bits: int
1084 eps: float
1085 max: float
1086 min: float
1087 smallest_normal: float
1088
1089 def mock_finfo(dtype: DataType) -> FloatInfo:
1090 """Returns a finfo object compliant with the Array API
1091
1092 Ensures all attributes are Python scalars and not NumPy scalars. This
1093 lets us ignore corner cases with how NumPy scalars operate, such as
1094 NumPy floats breaking our next_down() util.
1095
1096 Also ensures the finfo obj has the smallest_normal attribute. NumPy only
1097 introduced it in v1.21.1, so we just use the equivalent tiny attribute
1098 to keep mocking with older versions working.
1099 """
1100 _finfo = np.finfo(dtype) # type: ignore[call-overload]
1101 return FloatInfo(
1102 int(_finfo.bits),
1103 float(_finfo.eps),
1104 float(_finfo.max),
1105 float(_finfo.min),
1106 float(_finfo.tiny),
1107 )
1108
1109 mock_xp = SimpleNamespace(
1110 __name__="mock",
1111 __array_api_version__="2022.12",
1112 # Data types
1113 int8=np.int8,
1114 int16=np.int16,
1115 int32=np.int32,
1116 int64=np.int64,
1117 uint8=np.uint8,
1118 uint16=np.uint16,
1119 uint32=np.uint32,
1120 uint64=np.uint64,
1121 float32=np.float32,
1122 float64=np.float64,
1123 complex64=np.complex64,
1124 complex128=np.complex128,
1125 bool=np.bool_,
1126 # Constants
1127 nan=np.nan,
1128 # Data type functions
1129 astype=lambda x, d: x.astype(d),
1130 iinfo=np.iinfo,
1131 finfo=mock_finfo,
1132 broadcast_arrays=np.broadcast_arrays,
1133 # Creation functions
1134 arange=np.arange,
1135 asarray=np.asarray,
1136 empty=np.empty,
1137 zeros=np.zeros,
1138 ones=np.ones,
1139 # Manipulation functions
1140 reshape=np.reshape,
1141 # Element-wise functions
1142 isnan=np.isnan,
1143 isfinite=np.isfinite,
1144 logical_or=np.logical_or,
1145 # Statistical functions
1146 sum=np.sum,
1147 # Searching functions
1148 nonzero=np.nonzero,
1149 # Sorting functions
1150 sort=np.sort,
1151 # Set functions
1152 unique_values=np.unique,
1153 # Utility functions
1154 any=np.any,
1155 all=np.all,
1156 )