Debian Codegraph @

hypothesis-python/src/hypothesis/extra/numpy.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 importlib
12 import math
13 import types
14 from collections.abc import Mapping, Sequence
15 from typing import (
16 TYPE_CHECKING,
17 Any,
18 Literal,
19 TypeVar,
20 Union,
21 cast,
22 get_args,
23 get_origin,
24 overload,
25 )
26
27 import numpy as np
28
29 from hypothesis import strategies as st
30 from hypothesis.errors import HypothesisException, InvalidArgument
31 from hypothesis.extra._array_helpers import (
32 _BIE,
33 NDIM_MAX,
34 BasicIndex,
35 BasicIndexStrategy,
36 BroadcastableShapes,
37 Shape,
38 _BIENoEllipsis,
39 _BIENoEllipsisNoNewaxis,
40 _BIENoNewaxis,
41 array_shapes,
42 broadcastable_shapes,
43 check_argument,
44 check_valid_dims,
45 mutually_broadcastable_shapes as _mutually_broadcastable_shapes,
46 order_check,
47 valid_tuple_axes as _valid_tuple_axes,
48 )
49 from hypothesis.internal.conjecture import utils as cu
50 from hypothesis.internal.coverage import check_function
51 from hypothesis.internal.reflection import proxies
52 from hypothesis.internal.validation import check_type
53 from hypothesis.strategies._internal.lazy import unwrap_strategies
54 from hypothesis.strategies._internal.numbers import Real
55 from hypothesis.strategies._internal.strategies import (
56 Ex,
57 MappedStrategy,
58 T,
59 check_strategy,
60 )
61 from hypothesis.strategies._internal.utils import defines_strategy
62 from hypothesis.utils.deprecation import note_deprecation
63
64
65 def _try_import(mod_name: str, attr_name: str) -> Any:
66 assert "." not in attr_name
67 try:
68 mod = importlib.import_module(mod_name)
69 return getattr(mod, attr_name, None)
70 except ImportError:
71 return None
72
73
74 if TYPE_CHECKING:
75 from numpy.typing import DTypeLike, NDArray
76 else:
77 NDArray = _try_import("numpy.typing", "NDArray")
78
79 ArrayLike = _try_import("numpy.typing", "ArrayLike")
80 _NestedSequence = _try_import("numpy._typing._nested_sequence", "_NestedSequence")
81 _SupportsArray = _try_import("numpy._typing._array_like", "_SupportsArray")
82
83 __all__ = [
84 "BroadcastableShapes",
85 "array_dtypes",
86 "array_shapes",
87 "arrays",
88 "basic_indices",
89 "boolean_dtypes",
90 "broadcastable_shapes",
91 "byte_string_dtypes",
92 "complex_number_dtypes",
93 "datetime64_dtypes",
94 "floating_dtypes",
95 "from_dtype",
96 "integer_array_indices",
97 "integer_dtypes",
98 "mutually_broadcastable_shapes",
99 "nested_dtypes",
100 "scalar_dtypes",
101 "timedelta64_dtypes",
102 "unicode_string_dtypes",
103 "unsigned_integer_dtypes",
104 "valid_tuple_axes",
105 ]
106
107 TIME_RESOLUTIONS = ("Y", "M", "D", "h", "m", "s", "ms", "us", "ns", "ps", "fs", "as")
108
109 # See https://github.com/HypothesisWorks/hypothesis/pull/3394 and linked discussion.
110 NP_FIXED_UNICODE = tuple(int(x) for x in np.__version__.split(".")[:2]) >= (1, 19)
111
112
113 @defines_strategy(force_reusable_values=True)
114 def from_dtype(
115 dtype: np.dtype,
116 *,
117 alphabet: st.SearchStrategy[str] | None = None,
118 min_size: int = 0,
119 max_size: int | None = None,
120 min_value: int | float | None = None,
121 max_value: int | float | None = None,
122 allow_nan: bool | None = None,
123 allow_infinity: bool | None = None,
124 allow_subnormal: bool | None = None,
125 exclude_min: bool | None = None,
126 exclude_max: bool | None = None,
127 min_magnitude: Real = 0,
128 max_magnitude: Real | None = None,
129 ) -> st.SearchStrategy[Any]:
130 """Creates a strategy which can generate any value of the given dtype.
131
132 Compatible parameters are passed to the inferred strategy function while
133 inapplicable ones are ignored.
134 This allows you, for example, to customise the min and max values,
135 control the length or contents of strings, or exclude non-finite
136 numbers. This is particularly useful when kwargs are passed through from
137 :func:`arrays` which allow a variety of numeric dtypes, as it seamlessly
138 handles the ``width`` or representable bounds for you.
139 """
140 check_type(np.dtype, dtype, "dtype")
141 kwargs = {k: v for k, v in locals().items() if k != "dtype" and v is not None}
142
143 # Compound datatypes, eg 'f4,f4,f4'
144 if dtype.names is not None and dtype.fields is not None:
145 # mapping np.void.type over a strategy is nonsense, so return now.
146 subs = [from_dtype(dtype.fields[name][0], **kwargs) for name in dtype.names]
147 return st.tuples(*subs)
148
149 # Subarray datatypes, eg '(2, 3)i4'
150 if dtype.subdtype is not None:
151 subtype, shape = dtype.subdtype
152 return arrays(subtype, shape, elements=kwargs)
153
154 def compat_kw(*args, **kw):
155 """Update default args to the strategy with user-supplied keyword args."""
156 assert {"min_value", "max_value", "max_size"}.issuperset(kw)
157 for key in set(kwargs).intersection(kw):
158 msg = f"dtype {dtype!r} requires {key}={kwargs[key]!r} to be %s {kw[key]!r}"
159 if kw[key] is not None:
160 if key.startswith("min_") and kw[key] > kwargs[key]:
161 raise InvalidArgument(msg % ("at least",))
162 elif key.startswith("max_") and kw[key] < kwargs[key]:
163 raise InvalidArgument(msg % ("at most",))
164 kw.update({k: v for k, v in kwargs.items() if k in args or k in kw})
165 return kw
166
167 # Scalar datatypes
168 if dtype.kind == "b":
169 result: st.SearchStrategy[Any] = st.booleans()
170 elif dtype.kind == "f":
171 result = st.floats(
172 width=cast(Literal[16, 32, 64], min(8 * dtype.itemsize, 64)),
173 **compat_kw(
174 "min_value",
175 "max_value",
176 "allow_nan",
177 "allow_infinity",
178 "allow_subnormal",
179 "exclude_min",
180 "exclude_max",
181 ),
182 )
183 elif dtype.kind == "c":
184 result = st.complex_numbers(
185 width=cast(
186 Literal[32, 64, 128], min(8 * dtype.itemsize, 128)
187 ), # convert from bytes to bits
188 **compat_kw(
189 "min_magnitude",
190 "max_magnitude",
191 "allow_nan",
192 "allow_infinity",
193 "allow_subnormal",
194 ),
195 )
196 elif dtype.kind in ("S", "a"):
197 # Numpy strings are null-terminated; only allow round-trippable values.
198 # `itemsize == 0` means 'fixed length determined at array creation'
199 max_size = dtype.itemsize or None
200 result = st.binary(**compat_kw("min_size", max_size=max_size)).filter(
201 lambda b: b[-1:] != b"\0"
202 )
203 elif dtype.kind == "u":
204 kw = compat_kw(min_value=0, max_value=2 ** (8 * dtype.itemsize) - 1)
205 result = st.integers(**kw)
206 elif dtype.kind == "i":
207 overflow = 2 ** (8 * dtype.itemsize - 1)
208 result = st.integers(**compat_kw(min_value=-overflow, max_value=overflow - 1))
209 elif dtype.kind == "U":
210 # Encoded in UTF-32 (four bytes/codepoint) and null-terminated
211 max_size = (dtype.itemsize or 0) // 4 or None
212 if NP_FIXED_UNICODE and "alphabet" not in kwargs:
213 kwargs["alphabet"] = st.characters()
214 result = st.text(**compat_kw("alphabet", "min_size", max_size=max_size)).filter(
215 lambda b: b[-1:] != "\0"
216 )
217 elif dtype.kind in ("m", "M"):
218 if "[" in dtype.str:
219 res = st.just(dtype.str.split("[")[-1][:-1])
220 else:
221 # Note that this case isn't valid to pass to arrays(), but we support
222 # it here because we'd have to guard against equivalents in arrays()
223 # regardless and drawing scalars is a valid use-case.
224 res = st.sampled_from(TIME_RESOLUTIONS)
225 if allow_nan is not False:
226 elems = st.integers(-(2**63), 2**63 - 1) | st.just("NaT")
227 else: # NEP-7 defines the NaT value as integer -(2**63)
228 elems = st.integers(-(2**63) + 1, 2**63 - 1)
229 result = st.builds(dtype.type, elems, res)
230 elif dtype.kind == "O":
231 return st.from_type(object)
232 else:
233 raise InvalidArgument(f"No strategy inference for {dtype}")
234 return result.map(dtype.type)
235
236
237 class ArrayStrategy(st.SearchStrategy):
238 def __init__(self, element_strategy, shape, dtype, fill, unique):
239 super().__init__()
240 self.shape = tuple(shape)
241 self.fill = fill
242 self.array_size = int(np.prod(shape))
243 self.dtype = dtype
244 self.element_strategy = element_strategy
245 self.unique = unique
246 self._check_elements = dtype.kind not in ("O", "V")
247
248 def __repr__(self):
249 return (
250 f"ArrayStrategy({self.element_strategy!r}, shape={self.shape}, "
251 f"dtype={self.dtype!r}, fill={self.fill!r}, unique={self.unique!r})"
252 )
253
254 def set_element(self, val, result, idx, *, fill=False):
255 # `val` is either an arbitrary object (for dtype="O"), or otherwise an
256 # instance of a numpy dtype. This means we can *usually* expect e.g.
257 # val.dtype to be present, but can only guarantee it if
258 # `self.dtype != "O"`.
259
260 try:
261 result[idx] = val
262 except TypeError as err:
263 raise InvalidArgument(
264 f"Could not add element={val!r} of "
265 f"{getattr(val, 'dtype', type(val))} to array of "
266 f"{result.dtype!r} - possible mismatch of time units in dtypes?"
267 ) from err
268
269 try:
270 elem_changed = self._check_elements and val != result[idx] and val == val
271 except Exception as err: # pragma: no cover
272 # This branch only exists to help debug weird behaviour in Numpy,
273 # such as the string problems we had a while back.
274 raise HypothesisException(
275 f"Internal error when checking element={val!r} of "
276 f"{getattr(val, 'dtype', type(val))!r} to array of "
277 f"{result.dtype!r}"
278 ) from err
279
280 if elem_changed:
281 strategy = self.fill if fill else self.element_strategy
282 if self.dtype.kind == "f": # pragma: no cover
283 # This logic doesn't trigger in our coverage tests under Numpy 1.24+,
284 # with built-in checks for overflow, but we keep it for good error
285 # messages and compatibility with older versions of Numpy.
286 try:
287 is_subnormal = 0 < abs(val) < np.finfo(self.dtype).tiny
288 except Exception:
289 # val may be a non-float that does not support the
290 # operations __lt__ and __abs__
291 is_subnormal = False
292 if is_subnormal:
293 raise InvalidArgument(
294 f"Generated subnormal float {val} from strategy "
295 f"{strategy} resulted in {result[idx]!r}, probably "
296 "as a result of NumPy being built with flush-to-zero "
297 "compiler options. Consider passing "
298 "allow_subnormal=False."
299 )
300 raise InvalidArgument(
301 f"Generated array element {val!r} from {strategy!r} cannot be "
302 f"represented as dtype {self.dtype!r} - instead it becomes "
303 f"{result[idx]!r} (type {type(result[idx])!r}). Consider using "
304 "a more precise strategy, for example passing the `width` argument "
305 "to `floats()`."
306 )
307
308 def do_draw(self, data):
309 if 0 in self.shape:
310 return np.zeros(dtype=self.dtype, shape=self.shape)
311
312 # Because Numpy allocates memory for strings at array creation, if we have
313 # an unsized string dtype we'll fill an object array and then cast it back.
314 unsized_string_dtype = (
315 self.dtype.kind in ("S", "a", "U") and self.dtype.itemsize == 0
316 )
317
318 # This could legitimately be a np.empty, but the performance gains for
319 # that would be so marginal that there's really not much point risking
320 # undefined behaviour shenanigans.
321 result = np.zeros(
322 shape=self.array_size, dtype=object if unsized_string_dtype else self.dtype
323 )
324
325 if self.fill.is_empty:
326 # We have no fill value (either because the user explicitly
327 # disabled it or because the default behaviour was used and our
328 # elements strategy does not produce reusable values), so we must
329 # generate a fully dense array with a freshly drawn value for each
330 # entry.
331 if self.unique:
332 elems = st.lists(
333 self.element_strategy,
334 min_size=self.array_size,
335 max_size=self.array_size,
336 unique=True,
337 )
338 for i, v in enumerate(data.draw(elems)):
339 self.set_element(v, result, i)
340 else:
341 for i in range(len(result)):
342 self.set_element(data.draw(self.element_strategy), result, i)
343 else:
344 # We draw numpy arrays as "sparse with an offset". We draw a
345 # collection of index assignments within the array and assign
346 # fresh values from our elements strategy to those indices. If at
347 # the end we have not assigned every element then we draw a single
348 # value from our fill strategy and use that to populate the
349 # remaining positions with that strategy.
350
351 elements = cu.many(
352 data,
353 min_size=0,
354 max_size=self.array_size,
355 # sqrt isn't chosen for any particularly principled reason. It
356 # just grows reasonably quickly but sublinearly, and for small
357 # arrays it represents a decent fraction of the array size.
358 average_size=min(
359 0.9 * self.array_size, # ensure small arrays sometimes use fill
360 max(10, math.sqrt(self.array_size)), # ...but *only* sometimes
361 ),
362 )
363
364 needs_fill = np.full(self.array_size, True)
365 seen = set()
366
367 while elements.more():
368 i = data.draw_integer(0, self.array_size - 1)
369 if not needs_fill[i]:
370 elements.reject()
371 continue
372 self.set_element(data.draw(self.element_strategy), result, i)
373 if self.unique:
374 if result[i] in seen:
375 elements.reject()
376 continue
377 seen.add(result[i])
378
379 needs_fill[i] = False
380 if needs_fill.any():
381 # We didn't fill all of the indices in the early loop, so we
382 # put a fill value into the rest.
383
384 # We have to do this hilarious little song and dance to work
385 # around numpy's special handling of iterable values. If the
386 # value here were e.g. a tuple then neither array creation
387 # nor putmask would do the right thing. But by creating an
388 # array of size one and then assigning the fill value as a
389 # single element, we both get an array with the right value in
390 # it and putmask will do the right thing by repeating the
391 # values of the array across the mask.
392 one_element = np.zeros(
393 shape=1, dtype=object if unsized_string_dtype else self.dtype
394 )
395 self.set_element(data.draw(self.fill), one_element, 0, fill=True)
396 if unsized_string_dtype:
397 one_element = one_element.astype(self.dtype)
398 fill_value = one_element[0]
399 if self.unique:
400 try:
401 is_nan = np.isnan(fill_value)
402 except TypeError:
403 is_nan = False
404
405 if not is_nan:
406 raise InvalidArgument(
407 f"Cannot fill unique array with non-NaN value {fill_value!r}"
408 )
409
410 np.putmask(result, needs_fill, one_element)
411
412 if unsized_string_dtype:
413 out = result.astype(self.dtype)
414 mismatch = out != result
415 if mismatch.any():
416 raise InvalidArgument(
417 f"Array elements {result[mismatch]!r} cannot be represented "
418 f"as dtype {self.dtype!r} - instead they become "
419 f"{out[mismatch]!r}. Use a more precise strategy, e.g. without "
420 "trailing null bytes, as this will be an error future versions."
421 )
422 result = out
423
424 result = result.reshape(self.shape).copy()
425
426 assert result.base is None
427
428 return result
429
430
431 def fill_for(elements, unique, fill, name=""):
432 if fill is None:
433 if unique or not elements.has_reusable_values:
434 fill = st.nothing()
435 else:
436 fill = elements
437 else:
438 check_strategy(fill, f"{name}.fill" if name else "fill")
439 return fill
440
441
442 D = TypeVar("D", bound="DTypeLike")
443 G = TypeVar("G", bound="np.generic")
444
445
446 @overload
447 def arrays(
448 dtype: Union["np.dtype[G]", st.SearchStrategy["np.dtype[G]"]],
449 shape: int | st.SearchStrategy[int] | Shape | st.SearchStrategy[Shape],
450 *,
451 elements: st.SearchStrategy[Any] | Mapping[str, Any] | None = None,
452 fill: st.SearchStrategy[Any] | None = None,
453 unique: bool = False,
454 ) -> "st.SearchStrategy[NDArray[G]]": ...
455
456
457 @overload
458 def arrays(
459 dtype: D | st.SearchStrategy[D],
460 shape: int | st.SearchStrategy[int] | Shape | st.SearchStrategy[Shape],
461 *,
462 elements: st.SearchStrategy[Any] | Mapping[str, Any] | None = None,
463 fill: st.SearchStrategy[Any] | None = None,
464 unique: bool = False,
465 ) -> "st.SearchStrategy[NDArray[Any]]": ...
466
467
468 @defines_strategy(force_reusable_values=True)
469 def arrays(
470 dtype: D | st.SearchStrategy[D],
471 shape: int | st.SearchStrategy[int] | Shape | st.SearchStrategy[Shape],
472 *,
473 elements: st.SearchStrategy[Any] | Mapping[str, Any] | None = None,
474 fill: st.SearchStrategy[Any] | None = None,
475 unique: bool = False,
476 ) -> "st.SearchStrategy[NDArray[Any]]":
477 r"""Returns a strategy for generating :class:`numpy:numpy.ndarray`\ s.
478
479 * ``dtype`` may be any valid input to :class:`~numpy:numpy.dtype`
480 (this includes :class:`~numpy:numpy.dtype` objects), or a strategy that
481 generates such values.
482 * ``shape`` may be an integer >= 0, a tuple of such integers, or a
483 strategy that generates such values.
484 * ``elements`` is a strategy for generating values to put in the array.
485 If it is None a suitable value will be inferred based on the dtype,
486 which may give any legal value (including eg NaN for floats).
487 If a mapping, it will be passed as ``**kwargs`` to ``from_dtype()``
488 * ``fill`` is a strategy that may be used to generate a single background
489 value for the array. If None, a suitable default will be inferred
490 based on the other arguments. If set to
491 :func:`~hypothesis.strategies.nothing` then filling
492 behaviour will be disabled entirely and every element will be generated
493 independently.
494 * ``unique`` specifies if the elements of the array should all be
495 distinct from one another. Note that in this case multiple NaN values
496 may still be allowed. If fill is also set, the only valid values for
497 it to return are NaN values (anything for which :obj:`numpy:numpy.isnan`
498 returns True. So e.g. for complex numbers ``nan+1j`` is also a valid fill).
499 Note that if ``unique`` is set to ``True`` the generated values must be
500 hashable.
501
502 Arrays of specified ``dtype`` and ``shape`` are generated for example
503 like this:
504
505 .. code-block:: pycon
506
507 >>> import numpy as np
508 >>> arrays(np.int8, (2, 3)).example()
509 array([[-8, 6, 3],
510 [-6, 4, 6]], dtype=int8)
511 >>> arrays(np.float, 3, elements=st.floats(0, 1)).example()
512 array([ 0.88974794, 0.77387938, 0.1977879 ])
513
514 Array values are generated in two parts:
515
516 1. Some subset of the coordinates of the array are populated with a value
517 drawn from the elements strategy (or its inferred form).
518 2. If any coordinates were not assigned in the previous step, a single
519 value is drawn from the ``fill`` strategy and is assigned to all remaining
520 places.
521
522 You can set :func:`fill=nothing() <hypothesis.strategies.nothing>` to
523 disable this behaviour and draw a value for every element.
524
525 If ``fill=None``, then it will attempt to infer the correct behaviour
526 automatically. If ``unique`` is ``True``, no filling will occur by default.
527 Otherwise, if it looks safe to reuse the values of elements across
528 multiple coordinates (this will be the case for any inferred strategy, and
529 for most of the builtins, but is not the case for mutable values or
530 strategies built with flatmap, map, composite, etc) then it will use the
531 elements strategy as the fill, else it will default to having no fill.
532
533 Having a fill helps Hypothesis craft high quality examples, but its
534 main importance is when the array generated is large: Hypothesis is
535 primarily designed around testing small examples. If you have arrays with
536 hundreds or more elements, having a fill value is essential if you want
537 your tests to run in reasonable time.
538 """
539 # Our dtype argument might be a union, e.g. `np.float64 | np.complex64`; we handle
540 # that by turning it into a strategy up-front.
541 if type(dtype) in (getattr(types, "UnionType", object()), Union):
542 dtype = st.one_of(*(from_dtype(np.dtype(d)) for d in dtype.__args__)) # type: ignore
543
544 # We support passing strategies as arguments for convenience, or at least
545 # for legacy reasons, but don't want to pay the perf cost of a composite
546 # strategy (i.e. repeated argument handling and validation) when it's not
547 # needed. So we get the best of both worlds by recursing with flatmap,
548 # but only when it's actually needed.
549 if isinstance(dtype, st.SearchStrategy):
550 return dtype.flatmap(
551 lambda d: arrays(d, shape, elements=elements, fill=fill, unique=unique)
552 )
553 if isinstance(shape, st.SearchStrategy):
554 return shape.flatmap(
555 lambda s: arrays(dtype, s, elements=elements, fill=fill, unique=unique)
556 )
557 # From here on, we're only dealing with values and it's relatively simple.
558 dtype = np.dtype(dtype) # type: ignore[arg-type]
559 assert isinstance(dtype, np.dtype) # help mypy out a bit...
560 if elements is None or isinstance(elements, Mapping):
561 if dtype.kind in ("m", "M") and "[" not in dtype.str:
562 # For datetime and timedelta dtypes, we have a tricky situation -
563 # because they *may or may not* specify a unit as part of the dtype.
564 # If not, we flatmap over the various resolutions so that array
565 # elements have consistent units but units may vary between arrays.
566 return (
567 st.sampled_from(TIME_RESOLUTIONS)
568 .map((dtype.str + "[{}]").format)
569 .flatmap(lambda d: arrays(d, shape=shape, fill=fill, unique=unique))
570 )
571 elements = from_dtype(dtype, **(elements or {}))
572 check_strategy(elements, "elements")
573 # If there's a redundant cast to the requested dtype, remove it. This unlocks
574 # optimizations such as fast unique sampled_from, and saves some time directly too.
575 unwrapped = unwrap_strategies(elements)
576 if isinstance(unwrapped, MappedStrategy) and unwrapped.pack == dtype.type:
577 elements = unwrapped.mapped_strategy
578 if getattr(unwrapped, "force_has_reusable_values", False):
579 elements.force_has_reusable_values = True # type: ignore
580 if isinstance(shape, int):
581 shape = (shape,)
582 shape = tuple(shape)
583 check_argument(
584 all(isinstance(s, int) for s in shape),
585 "Array shape must be integer in each dimension, provided shape was {}",
586 shape,
587 )
588 fill = fill_for(elements=elements, unique=unique, fill=fill)
589 return ArrayStrategy(elements, shape, dtype, fill, unique)
590
591
592 @defines_strategy()
593 def scalar_dtypes() -> st.SearchStrategy[np.dtype]:
594 """Return a strategy that can return any non-flexible scalar dtype."""
595 return st.one_of(
596 boolean_dtypes(),
597 integer_dtypes(),
598 unsigned_integer_dtypes(),
599 floating_dtypes(),
600 complex_number_dtypes(),
601 datetime64_dtypes(),
602 timedelta64_dtypes(),
603 )
604
605
606 def defines_dtype_strategy(strat: T) -> T:
607 @defines_strategy()
608 @proxies(strat)
609 def inner(*args, **kwargs):
610 return strat(*args, **kwargs).map(np.dtype)
611
612 return inner
613
614
615 @defines_dtype_strategy
616 def boolean_dtypes() -> st.SearchStrategy["np.dtype[np.bool_]"]:
617 """Return a strategy for boolean dtypes."""
618 return st.just("?") # type: ignore[arg-type]
619
620
621 def dtype_factory(kind, sizes, valid_sizes, endianness):
622 # Utility function, shared logic for most integer and string types
623 valid_endian = ("?", "<", "=", ">")
624 check_argument(
625 endianness in valid_endian,
626 "Unknown endianness: was {}, must be in {}",
627 endianness,
628 valid_endian,
629 )
630 if valid_sizes is not None:
631 if isinstance(sizes, int):
632 sizes = (sizes,)
633 check_argument(sizes, "Dtype must have at least one possible size.")
634 check_argument(
635 all(s in valid_sizes for s in sizes),
636 "Invalid sizes: was {} must be an item or sequence in {}",
637 sizes,
638 valid_sizes,
639 )
640 if all(isinstance(s, int) for s in sizes):
641 sizes = sorted({s // 8 for s in sizes})
642 strat = st.sampled_from(sizes)
643 if "{}" not in kind:
644 kind += "{}"
645 if endianness == "?":
646 return strat.map(("<" + kind).format) | strat.map((">" + kind).format)
647 return strat.map((endianness + kind).format)
648
649
650 @overload
651 def unsigned_integer_dtypes(
652 *,
653 endianness: str = "?",
654 sizes: Literal[8],
655 ) -> st.SearchStrategy["np.dtype[np.uint8]"]: ...
656
657
658 @overload
659 def unsigned_integer_dtypes(
660 *,
661 endianness: str = "?",
662 sizes: Literal[16],
663 ) -> st.SearchStrategy["np.dtype[np.uint16]"]: ...
664
665
666 @overload
667 def unsigned_integer_dtypes(
668 *,
669 endianness: str = "?",
670 sizes: Literal[32],
671 ) -> st.SearchStrategy["np.dtype[np.uint32]"]: ...
672
673
674 @overload
675 def unsigned_integer_dtypes(
676 *,
677 endianness: str = "?",
678 sizes: Literal[64],
679 ) -> st.SearchStrategy["np.dtype[np.uint64]"]: ...
680
681
682 @overload
683 def unsigned_integer_dtypes(
684 *,
685 endianness: str = "?",
686 sizes: Sequence[Literal[8, 16, 32, 64]] = (8, 16, 32, 64),
687 ) -> st.SearchStrategy["np.dtype[np.unsignedinteger[Any]]"]: ...
688
689
690 @defines_dtype_strategy
691 def unsigned_integer_dtypes(
692 *,
693 endianness: str = "?",
694 sizes: Literal[8, 16, 32, 64] | Sequence[Literal[8, 16, 32, 64]] = (
695 8,
696 16,
697 32,
698 64,
699 ),
700 ) -> st.SearchStrategy["np.dtype[np.unsignedinteger[Any]]"]:
701 """Return a strategy for unsigned integer dtypes.
702
703 endianness may be ``<`` for little-endian, ``>`` for big-endian,
704 ``=`` for native byte order, or ``?`` to allow either byte order.
705 This argument only applies to dtypes of more than one byte.
706
707 sizes must be a collection of integer sizes in bits. The default
708 (8, 16, 32, 64) covers the full range of sizes.
709 """
710 return dtype_factory("u", sizes, (8, 16, 32, 64), endianness)
711
712
713 @overload
714 def integer_dtypes(
715 *,
716 endianness: str = "?",
717 sizes: Literal[8],
718 ) -> st.SearchStrategy["np.dtype[np.int8]"]: ...
719
720
721 @overload
722 def integer_dtypes(
723 *,
724 endianness: str = "?",
725 sizes: Literal[16],
726 ) -> st.SearchStrategy["np.dtype[np.int16]"]: ...
727
728
729 @overload
730 def integer_dtypes(
731 *,
732 endianness: str = "?",
733 sizes: Literal[32],
734 ) -> st.SearchStrategy["np.dtype[np.int32]"]: ...
735
736
737 @overload
738 def integer_dtypes(
739 *,
740 endianness: str = "?",
741 sizes: Literal[64],
742 ) -> st.SearchStrategy["np.dtype[np.int64]"]: ...
743
744
745 @overload
746 def integer_dtypes(
747 *,
748 endianness: str = "?",
749 sizes: Sequence[Literal[8, 16, 32, 64]] = (8, 16, 32, 64),
750 ) -> st.SearchStrategy["np.dtype[np.signedinteger[Any]]"]: ...
751
752
753 @defines_dtype_strategy
754 def integer_dtypes(
755 *,
756 endianness: str = "?",
757 sizes: Literal[8, 16, 32, 64] | Sequence[Literal[8, 16, 32, 64]] = (
758 8,
759 16,
760 32,
761 64,
762 ),
763 ) -> st.SearchStrategy["np.dtype[np.signedinteger[Any]]"]:
764 """Return a strategy for signed integer dtypes.
765
766 endianness and sizes are treated as for
767 :func:`unsigned_integer_dtypes`.
768 """
769 return dtype_factory("i", sizes, (8, 16, 32, 64), endianness)
770
771
772 @overload
773 def floating_dtypes(
774 *,
775 endianness: str = "?",
776 sizes: Literal[16],
777 ) -> st.SearchStrategy["np.dtype[np.float16]"]: ...
778
779
780 @overload
781 def floating_dtypes(
782 *,
783 endianness: str = "?",
784 sizes: Literal[32],
785 ) -> st.SearchStrategy["np.dtype[np.float32]"]: ...
786
787
788 @overload
789 def floating_dtypes(
790 *,
791 endianness: str = "?",
792 sizes: Literal[64],
793 ) -> st.SearchStrategy["np.dtype[np.float64]"]: ...
794
795
796 @overload
797 def floating_dtypes(
798 *,
799 endianness: str = "?",
800 sizes: Literal[128],
801 ) -> st.SearchStrategy["np.dtype[np.float128]"]: ...
802
803
804 @overload
805 def floating_dtypes(
806 *,
807 endianness: str = "?",
808 sizes: Sequence[Literal[16, 32, 64, 96, 128]] = (16, 32, 64),
809 ) -> st.SearchStrategy["np.dtype[np.floating[Any]]"]: ...
810
811
812 @defines_dtype_strategy
813 def floating_dtypes(
814 *,
815 endianness: str = "?",
816 sizes: Literal[16, 32, 64, 96, 128] | Sequence[Literal[16, 32, 64, 96, 128]] = (
817 16,
818 32,
819 64,
820 ),
821 ) -> st.SearchStrategy["np.dtype[np.floating[Any]]"]:
822 """Return a strategy for floating-point dtypes.
823
824 sizes is the size in bits of floating-point number. Some machines support
825 96- or 128-bit floats, but these are not generated by default.
826
827 Larger floats (96 and 128 bit real parts) are not supported on all
828 platforms and therefore disabled by default. To generate these dtypes,
829 include these values in the sizes argument.
830 """
831 return dtype_factory("f", sizes, (16, 32, 64, 96, 128), endianness)
832
833
834 @overload
835 def complex_number_dtypes(
836 *,
837 endianness: str = "?",
838 sizes: Literal[64],
839 ) -> st.SearchStrategy["np.dtype[np.complex64]"]: ...
840
841
842 @overload
843 def complex_number_dtypes(
844 *,
845 endianness: str = "?",
846 sizes: Literal[128],
847 ) -> st.SearchStrategy["np.dtype[np.complex128]"]: ...
848
849
850 @overload
851 def complex_number_dtypes(
852 *,
853 endianness: str = "?",
854 sizes: Literal[256],
855 ) -> st.SearchStrategy["np.dtype[np.complex256]"]: ...
856
857
858 @overload
859 def complex_number_dtypes(
860 *,
861 endianness: str = "?",
862 sizes: Sequence[Literal[64, 128, 192, 256]] = (64, 128),
863 ) -> st.SearchStrategy["np.dtype[np.complexfloating[Any, Any]]"]: ...
864
865
866 @defines_dtype_strategy
867 def complex_number_dtypes(
868 *,
869 endianness: str = "?",
870 sizes: Literal[64, 128, 192, 256] | Sequence[Literal[64, 128, 192, 256]] = (
871 64,
872 128,
873 ),
874 ) -> st.SearchStrategy["np.dtype[np.complexfloating[Any, Any]]"]:
875 """Return a strategy for complex-number dtypes.
876
877 sizes is the total size in bits of a complex number, which consists
878 of two floats. Complex halves (a 16-bit real part) are not supported
879 by numpy and will not be generated by this strategy.
880 """
881 return dtype_factory("c", sizes, (64, 128, 192, 256), endianness)
882
883
884 @check_function
885 def validate_time_slice(max_period, min_period):
886 check_argument(
887 max_period in TIME_RESOLUTIONS,
888 "max_period {} must be a valid resolution in {}",
889 max_period,
890 TIME_RESOLUTIONS,
891 )
892 check_argument(
893 min_period in TIME_RESOLUTIONS,
894 "min_period {} must be a valid resolution in {}",
895 min_period,
896 TIME_RESOLUTIONS,
897 )
898 start = TIME_RESOLUTIONS.index(max_period)
899 end = TIME_RESOLUTIONS.index(min_period) + 1
900 check_argument(
901 start < end,
902 "max_period {} must be earlier in sequence {} than min_period {}",
903 max_period,
904 TIME_RESOLUTIONS,
905 min_period,
906 )
907 return TIME_RESOLUTIONS[start:end]
908
909
910 @defines_dtype_strategy
911 def datetime64_dtypes(
912 *, max_period: str = "Y", min_period: str = "ns", endianness: str = "?"
913 ) -> st.SearchStrategy["np.dtype[np.datetime64]"]:
914 """Return a strategy for datetime64 dtypes, with various precisions from
915 year to attosecond."""
916 return dtype_factory(
917 "datetime64[{}]",
918 validate_time_slice(max_period, min_period),
919 TIME_RESOLUTIONS,
920 endianness,
921 )
922
923
924 @defines_dtype_strategy
925 def timedelta64_dtypes(
926 *, max_period: str = "Y", min_period: str = "ns", endianness: str = "?"
927 ) -> st.SearchStrategy["np.dtype[np.timedelta64]"]:
928 """Return a strategy for timedelta64 dtypes, with various precisions from
929 year to attosecond."""
930 return dtype_factory(
931 "timedelta64[{}]",
932 validate_time_slice(max_period, min_period),
933 TIME_RESOLUTIONS,
934 endianness,
935 )
936
937
938 @defines_dtype_strategy
939 def byte_string_dtypes(
940 *, endianness: str = "?", min_len: int = 1, max_len: int = 16
941 ) -> st.SearchStrategy["np.dtype[np.bytes_]"]:
942 """Return a strategy for generating bytestring dtypes, of various lengths
943 and byteorder.
944
945 While Hypothesis' string strategies can generate empty strings, string
946 dtypes with length 0 indicate that size is still to be determined, so
947 the minimum length for string dtypes is 1.
948 """
949 order_check("len", 1, min_len, max_len)
950 return dtype_factory("S", list(range(min_len, max_len + 1)), None, endianness)
951
952
953 @defines_dtype_strategy
954 def unicode_string_dtypes(
955 *, endianness: str = "?", min_len: int = 1, max_len: int = 16
956 ) -> st.SearchStrategy["np.dtype[np.str_]"]:
957 """Return a strategy for generating unicode string dtypes, of various
958 lengths and byteorder.
959
960 While Hypothesis' string strategies can generate empty strings, string
961 dtypes with length 0 indicate that size is still to be determined, so
962 the minimum length for string dtypes is 1.
963 """
964 order_check("len", 1, min_len, max_len)
965 return dtype_factory("U", list(range(min_len, max_len + 1)), None, endianness)
966
967
968 def _no_title_is_name_of_a_titled_field(ls):
969 seen = set()
970 for title_and_name, *_ in ls:
971 if isinstance(title_and_name, tuple):
972 if seen.intersection(title_and_name): # pragma: no cover
973 # Our per-element filters below make this as rare as possible,
974 # so it's not always covered.
975 return False
976 seen.update(title_and_name)
977 return True
978
979
980 @defines_dtype_strategy
981 def array_dtypes(
982 subtype_strategy: st.SearchStrategy[np.dtype] = scalar_dtypes(),
983 *,
984 min_size: int = 1,
985 max_size: int = 5,
986 allow_subarrays: bool = False,
987 ) -> st.SearchStrategy[np.dtype]:
988 """Return a strategy for generating array (compound) dtypes, with members
989 drawn from the given subtype strategy."""
990 order_check("size", 0, min_size, max_size)
991 # The empty string is replaced by f{idx}; see #1963 for details. Much easier to
992 # insist that field names be unique and just boost f{idx} strings manually.
993 field_names = st.integers(0, 127).map("f{}".format) | st.text(min_size=1)
994 name_titles = st.one_of(
995 field_names,
996 st.tuples(field_names, field_names).filter(lambda ns: ns[0] != ns[1]),
997 )
998 elements: st.SearchStrategy[tuple] = st.tuples(name_titles, subtype_strategy)
999 if allow_subarrays:
1000 elements |= st.tuples(
1001 name_titles, subtype_strategy, array_shapes(max_dims=2, max_side=2)
1002 )
1003 return st.lists( # type: ignore[return-value]
1004 elements=elements,
1005 min_size=min_size,
1006 max_size=max_size,
1007 unique_by=(
1008 # Deduplicate by both name and title for efficiency before filtering.
1009 # (Field names must be unique, as must titles, and no intersections)
1010 lambda d: d[0] if isinstance(d[0], str) else d[0][0],
1011 lambda d: d[0] if isinstance(d[0], str) else d[0][1],
1012 ),
1013 ).filter(_no_title_is_name_of_a_titled_field)
1014
1015
1016 @defines_strategy()
1017 def nested_dtypes(
1018 subtype_strategy: st.SearchStrategy[np.dtype] = scalar_dtypes(),
1019 *,
1020 max_leaves: int = 10,
1021 max_itemsize: int | None = None,
1022 ) -> st.SearchStrategy[np.dtype]:
1023 """Return the most-general dtype strategy.
1024
1025 Elements drawn from this strategy may be simple (from the
1026 subtype_strategy), or several such values drawn from
1027 :func:`array_dtypes` with ``allow_subarrays=True``. Subdtypes in an
1028 array dtype may be nested to any depth, subject to the max_leaves
1029 argument.
1030 """
1031 return st.recursive(
1032 subtype_strategy,
1033 lambda x: array_dtypes(x, allow_subarrays=True),
1034 max_leaves=max_leaves,
1035 ).filter(lambda d: max_itemsize is None or d.itemsize <= max_itemsize)
1036
1037
1038 @proxies(_valid_tuple_axes)
1039 def valid_tuple_axes(*args, **kwargs):
1040 return _valid_tuple_axes(*args, **kwargs)
1041
1042
1043 valid_tuple_axes.__doc__ = f"""
1044 Return a strategy for generating permissible tuple-values for the
1045 ``axis`` argument for a numpy sequential function (e.g.
1046 :func:`numpy:numpy.sum`), given an array of the specified
1047 dimensionality.
1048
1049 {_valid_tuple_axes.__doc__}
1050 """
1051
1052
1053 @proxies(_mutually_broadcastable_shapes)
1054 def mutually_broadcastable_shapes(*args, **kwargs):
1055 return _mutually_broadcastable_shapes(*args, **kwargs)
1056
1057
1058 mutually_broadcastable_shapes.__doc__ = f"""
1059 {_mutually_broadcastable_shapes.__doc__}
1060
1061 **Use with Generalised Universal Function signatures**
1062
1063 A :doc:`universal function <numpy:reference/ufuncs>` (or ufunc for short) is a function
1064 that operates on ndarrays in an element-by-element fashion, supporting array
1065 broadcasting, type casting, and several other standard features.
1066 A :doc:`generalised ufunc <numpy:reference/c-api/generalized-ufuncs>` operates on
1067 sub-arrays rather than elements, based on the "signature" of the function.
1068 Compare e.g. :obj:`numpy.add() <numpy:numpy.add>` (ufunc) to
1069 :obj:`numpy.matmul() <numpy:numpy.matmul>` (gufunc).
1070
1071 To generate shapes for a gufunc, you can pass the ``signature`` argument instead of
1072 ``num_shapes``. This must be a gufunc signature string; which you can write by
1073 hand or access as e.g. ``np.matmul.signature`` on generalised ufuncs.
1074
1075 In this case, the ``side`` arguments are applied to the 'core dimensions' as well,
1076 ignoring any frozen dimensions. ``base_shape`` and the ``dims`` arguments are
1077 applied to the 'loop dimensions', and if necessary, the dimensionality of each
1078 shape is silently capped to respect the 32-dimension limit.
1079
1080 The generated ``result_shape`` is the real result shape of applying the gufunc
1081 to arrays of the generated ``input_shapes``, even where this is different to
1082 broadcasting the loop dimensions.
1083
1084 gufunc-compatible shapes shrink their loop dimensions as above, towards omitting
1085 optional core dimensions, and smaller-size core dimensions.
1086
1087 .. code-block:: pycon
1088
1089 >>> # np.matmul.signature == "(m?,n),(n,p?)->(m?,p?)"
1090 >>> for _ in range(3):
1091 ... mutually_broadcastable_shapes(signature=np.matmul.signature).example()
1092 BroadcastableShapes(input_shapes=((2,), (2,)), result_shape=())
1093 BroadcastableShapes(input_shapes=((3, 4, 2), (1, 2)), result_shape=(3, 4))
1094 BroadcastableShapes(input_shapes=((4, 2), (1, 2, 3)), result_shape=(4, 3))
1095
1096 """
1097
1098
1099 @overload
1100 def basic_indices(
1101 shape: Shape,
1102 *,
1103 min_dims: int = 0,
1104 max_dims: int | None = None,
1105 allow_newaxis: Literal[False] = ...,
1106 allow_ellipsis: Literal[False],
1107 ) -> st.SearchStrategy[
1108 _BIENoEllipsisNoNewaxis | tuple[_BIENoEllipsisNoNewaxis, ...]
1109 ]: ...
1110
1111
1112 @overload
1113 def basic_indices(
1114 shape: Shape,
1115 *,
1116 min_dims: int = 0,
1117 max_dims: int | None = None,
1118 allow_newaxis: Literal[False] = ...,
1119 allow_ellipsis: Literal[True] = ...,
1120 ) -> st.SearchStrategy[_BIENoNewaxis | tuple[_BIENoNewaxis, ...]]: ...
1121
1122
1123 @overload
1124 def basic_indices(
1125 shape: Shape,
1126 *,
1127 min_dims: int = 0,
1128 max_dims: int | None = None,
1129 allow_newaxis: Literal[True],
1130 allow_ellipsis: Literal[False],
1131 ) -> st.SearchStrategy[_BIENoEllipsis | tuple[_BIENoEllipsis, ...]]: ...
1132
1133
1134 @overload
1135 def basic_indices(
1136 shape: Shape,
1137 *,
1138 min_dims: int = 0,
1139 max_dims: int | None = None,
1140 allow_newaxis: Literal[True],
1141 allow_ellipsis: Literal[True] = ...,
1142 ) -> st.SearchStrategy[_BIE | tuple[_BIE, ...]]: ...
1143
1144
1145 @defines_strategy()
1146 def basic_indices(
1147 shape: Shape,
1148 *,
1149 min_dims: int = 0,
1150 max_dims: int | None = None,
1151 allow_newaxis: bool = False,
1152 allow_ellipsis: bool = True,
1153 ) -> st.SearchStrategy[BasicIndex]:
1154 """Return a strategy for :doc:`basic indexes <numpy:reference/routines.indexing>` of
1155 arrays with the specified shape, which may include dimensions of size zero.
1156
1157 It generates tuples containing some mix of integers, :obj:`python:slice`
1158 objects, ``...`` (an ``Ellipsis``), and ``None``. When a length-one tuple
1159 would be generated, this strategy may instead return the element which will
1160 index the first axis, e.g. ``5`` instead of ``(5,)``.
1161
1162 * ``shape`` is the shape of the array that will be indexed, as a tuple of
1163 positive integers. This must be at least two-dimensional for a tuple to be
1164 a valid index; for one-dimensional arrays use
1165 :func:`~hypothesis.strategies.slices` instead.
1166 * ``min_dims`` is the minimum dimensionality of the resulting array from use
1167 of the generated index. When ``min_dims == 0``, scalars and zero-dimensional
1168 arrays are both allowed.
1169 * ``max_dims`` is the maximum dimensionality of the resulting array,
1170 defaulting to ``len(shape) if not allow_newaxis else
1171 max(len(shape), min_dims) + 2``.
1172 * ``allow_newaxis`` specifies whether ``None`` is allowed in the index.
1173 * ``allow_ellipsis`` specifies whether ``...`` is allowed in the index.
1174 """
1175 # Arguments to exclude scalars, zero-dim arrays, and dims of size zero were
1176 # all considered and rejected. We want users to explicitly consider those
1177 # cases if they're dealing in general indexers, and while it's fiddly we can
1178 # back-compatibly add them later (hence using kwonlyargs).
1179 check_type(tuple, shape, "shape")
1180 check_argument(
1181 all(isinstance(x, int) and x >= 0 for x in shape),
1182 f"{shape=}, but all dimensions must be non-negative integers.",
1183 )
1184 check_type(bool, allow_ellipsis, "allow_ellipsis")
1185 check_type(bool, allow_newaxis, "allow_newaxis")
1186 check_type(int, min_dims, "min_dims")
1187 if min_dims > len(shape) and not allow_newaxis:
1188 note_deprecation(
1189 f"min_dims={min_dims} is larger than len(shape)={len(shape)}, "
1190 "but allow_newaxis=False makes it impossible for an indexing "
1191 "operation to add dimensions.",
1192 since="2021-09-15",
1193 has_codemod=False,
1194 )
1195 check_valid_dims(min_dims, "min_dims")
1196
1197 if max_dims is None:
1198 if allow_newaxis:
1199 max_dims = min(max(len(shape), min_dims) + 2, NDIM_MAX)
1200 else:
1201 max_dims = min(len(shape), NDIM_MAX)
1202 else:
1203 check_type(int, max_dims, "max_dims")
1204 if max_dims > len(shape) and not allow_newaxis:
1205 note_deprecation(
1206 f"max_dims={max_dims} is larger than len(shape)={len(shape)}, "
1207 "but allow_newaxis=False makes it impossible for an indexing "
1208 "operation to add dimensions.",
1209 since="2021-09-15",
1210 has_codemod=False,
1211 )
1212 check_valid_dims(max_dims, "max_dims")
1213
1214 order_check("dims", 0, min_dims, max_dims)
1215
1216 return BasicIndexStrategy(
1217 shape,
1218 min_dims=min_dims,
1219 max_dims=max_dims,
1220 allow_ellipsis=allow_ellipsis,
1221 allow_newaxis=allow_newaxis,
1222 allow_fewer_indices_than_dims=True,
1223 )
1224
1225
1226 I = TypeVar("I", bound=np.integer)
1227
1228
1229 @overload
1230 def integer_array_indices(
1231 shape: Shape,
1232 *,
1233 result_shape: st.SearchStrategy[Shape] = array_shapes(),
1234 ) -> "st.SearchStrategy[tuple[NDArray[np.signedinteger[Any]], ...]]": ...
1235
1236
1237 @overload
1238 def integer_array_indices(
1239 shape: Shape,
1240 *,
1241 result_shape: st.SearchStrategy[Shape] = array_shapes(),
1242 dtype: "np.dtype[I]",
1243 ) -> "st.SearchStrategy[tuple[NDArray[I], ...]]": ...
1244
1245
1246 @defines_strategy()
1247 def integer_array_indices(
1248 shape: Shape,
1249 *,
1250 result_shape: st.SearchStrategy[Shape] = array_shapes(),
1251 dtype: "np.dtype[I] | np.dtype[np.signedinteger[Any] | np.bool[bool]]" = np.dtype(
1252 int
1253 ),
1254 ) -> "st.SearchStrategy[tuple[NDArray[I], ...]]":
1255 """Return a search strategy for tuples of integer-arrays that, when used
1256 to index into an array of shape ``shape``, given an array whose shape
1257 was drawn from ``result_shape``.
1258
1259 Examples from this strategy shrink towards the tuple of index-arrays::
1260
1261 len(shape) * (np.zeros(drawn_result_shape, dtype), )
1262
1263 * ``shape`` a tuple of integers that indicates the shape of the array,
1264 whose indices are being generated.
1265 * ``result_shape`` a strategy for generating tuples of integers, which
1266 describe the shape of the resulting index arrays. The default is
1267 :func:`~hypothesis.extra.numpy.array_shapes`. The shape drawn from
1268 this strategy determines the shape of the array that will be produced
1269 when the corresponding example from ``integer_array_indices`` is used
1270 as an index.
1271 * ``dtype`` the integer data type of the generated index-arrays. Negative
1272 integer indices can be generated if a signed integer type is specified.
1273
1274 Recall that an array can be indexed using a tuple of integer-arrays to
1275 access its members in an arbitrary order, producing an array with an
1276 arbitrary shape. For example:
1277
1278 .. code-block:: pycon
1279
1280 >>> from numpy import array
1281 >>> x = array([-0, -1, -2, -3, -4])
1282 >>> ind = (array([[4, 0], [0, 1]]),) # a tuple containing a 2D integer-array
1283 >>> x[ind] # the resulting array is commensurate with the indexing array(s)
1284 array([[-4, 0],
1285 [0, -1]])
1286
1287 Note that this strategy does not accommodate all variations of so-called
1288 'advanced indexing', as prescribed by NumPy's nomenclature. Combinations
1289 of basic and advanced indexes are too complex to usefully define in a
1290 standard strategy; we leave application-specific strategies to the user.
1291 Advanced-boolean indexing can be defined as ``arrays(shape=..., dtype=bool)``,
1292 and is similarly left to the user.
1293 """
1294 check_type(tuple, shape, "shape")
1295 check_argument(
1296 shape and all(isinstance(x, int) and x > 0 for x in shape),
1297 f"{shape=} must be a non-empty tuple of integers > 0",
1298 )
1299 check_strategy(result_shape, "result_shape")
1300 check_argument(
1301 np.issubdtype(dtype, np.integer), f"{dtype=} must be an integer dtype"
1302 )
1303 signed = np.issubdtype(dtype, np.signedinteger)
1304
1305 def array_for(index_shape, size):
1306 return arrays(
1307 dtype=dtype,
1308 shape=index_shape,
1309 elements=st.integers(-size if signed else 0, size - 1),
1310 )
1311
1312 return result_shape.flatmap(
1313 lambda index_shape: st.tuples(*(array_for(index_shape, size) for size in shape))
1314 )
1315
1316
1317 def _unpack_dtype(dtype):
1318 dtype_args = getattr(dtype, "__args__", ())
1319 if dtype_args and type(dtype) not in (getattr(types, "UnionType", object()), Union):
1320 assert len(dtype_args) == 1
1321 if isinstance(dtype_args[0], TypeVar):
1322 # numpy.dtype[+ScalarType]
1323 assert dtype_args[0].__bound__ == np.generic
1324 dtype = Any
1325 else:
1326 # plain dtype
1327 dtype = dtype_args[0]
1328 return dtype
1329
1330
1331 def _dtype_from_args(args):
1332 if len(args) <= 1:
1333 # Zero args: ndarray, _SupportsArray
1334 # One arg: ndarray[type], _SupportsArray[type]
1335 dtype = _unpack_dtype(args[0]) if args else Any
1336 else:
1337 # Two args: ndarray[shape, type], NDArray[*]
1338 assert len(args) == 2
1339 dtype = _unpack_dtype(args[1])
1340
1341 if dtype is Any:
1342 return scalar_dtypes()
1343 elif type(dtype) in (getattr(types, "UnionType", object()), Union):
1344 return dtype
1345 return np.dtype(dtype)
1346
1347
1348 def _from_type(thing: type[Ex]) -> st.SearchStrategy[Ex] | None:
1349 """Called by st.from_type to try to infer a strategy for thing using numpy.
1350
1351 If we can infer a numpy-specific strategy for thing, we return that; otherwise,
1352 we return None.
1353 """
1354
1355 base_strats = st.one_of(
1356 [
1357 st.booleans(),
1358 st.integers(),
1359 st.floats(),
1360 st.complex_numbers(),
1361 st.text(),
1362 st.binary(),
1363 ]
1364 )
1365 # don't mix strings and non-ascii bytestrings (ex: ['', b'\x80']). See
1366 # https://github.com/numpy/numpy/issues/23899.
1367 base_strats_ascii = st.one_of(
1368 [
1369 st.booleans(),
1370 st.integers(),
1371 st.floats(),
1372 st.complex_numbers(),
1373 st.text(),
1374 st.binary().filter(bytes.isascii),
1375 ]
1376 )
1377
1378 if thing == np.dtype:
1379 # Note: Parameterized dtypes and DTypeLike are not supported.
1380 return st.one_of(
1381 scalar_dtypes(),
1382 byte_string_dtypes(),
1383 unicode_string_dtypes(),
1384 array_dtypes(),
1385 nested_dtypes(),
1386 )
1387
1388 if thing == ArrayLike:
1389 # We override the default type resolution to ensure the "coercible to
1390 # array" contract is honoured. See
1391 # https://github.com/HypothesisWorks/hypothesis/pull/3670#issuecomment-1578140422.
1392 # The actual type is (as of np 1.24), with
1393 # scalars:=[bool, int, float, complex, str, bytes]:
1394 # Union[
1395 # _SupportsArray,
1396 # _NestedSequence[_SupportsArray],
1397 # *scalars,
1398 # _NestedSequence[Union[*scalars]]
1399 # ]
1400 return st.one_of(
1401 # *scalars
1402 base_strats,
1403 # The two recursive strategies below cover the following cases:
1404 # - _SupportsArray (using plain ndarrays)
1405 # - _NestedSequence[Union[*scalars]] (but excluding non-ascii binary)
1406 # - _NestedSequence[_SupportsArray] (but with a single leaf element
1407 # . to avoid the issue of unequally sized leaves)
1408 st.recursive(st.lists(base_strats_ascii), extend=st.tuples),
1409 st.recursive(st.from_type(np.ndarray), extend=st.tuples),
1410 )
1411
1412 if isinstance(thing, type) and issubclass(thing, np.generic):
1413 dtype = np.dtype(thing)
1414 return from_dtype(dtype) if dtype.kind not in "OV" else None
1415
1416 origin = get_origin(thing)
1417 # if origin is not generic-like, get_origin returns None. Fall back to thing.
1418 if origin is None:
1419 origin = thing
1420 args = get_args(thing)
1421
1422 if origin == _NestedSequence:
1423 # We have to override the default resolution to ensure sequences are of
1424 # equal length. Actually they are still not, if the arg specialization
1425 # returns arbitrary-shaped sequences or arrays - hence the even more special
1426 # resolution of ArrayLike, above.
1427 assert len(args) <= 1
1428 base_strat = st.from_type(args[0]) if args else base_strats
1429 return st.one_of(
1430 st.lists(base_strat),
1431 st.recursive(st.tuples(), st.tuples),
1432 st.recursive(st.tuples(base_strat), st.tuples),
1433 st.recursive(st.tuples(base_strat, base_strat), st.tuples),
1434 )
1435
1436 # note: get_origin(np.typing.NDArray[np.int64]) is np.ndarray in numpy < 2.5.0,
1437 # but is np.typing.NDArray in numpy >= 2.5.0. Support both here.
1438 if origin in [np.typing.NDArray, np.ndarray, _SupportsArray]:
1439 dtype = _dtype_from_args(args)
1440 return arrays(dtype, array_shapes(max_dims=2)) # type: ignore[return-value]
1441
1442 # We didn't find a type to resolve, continue
1443 return None