Debian Codegraph @

hypothesis-python/src/hypothesis/extra/_array_helpers.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 re
12 from types import EllipsisType
13 from typing import NamedTuple
14
15 from hypothesis import assume, strategies as st
16 from hypothesis.errors import InvalidArgument
17 from hypothesis.internal.conjecture.utils import _calc_p_continue
18 from hypothesis.internal.coverage import check_function
19 from hypothesis.internal.validation import check_type, check_valid_interval
20 from hypothesis.strategies._internal.utils import defines_strategy
21 from hypothesis.utils.conventions import UniqueIdentifier, not_set
22
23 __all__ = [
24 "NDIM_MAX",
25 "_BIE",
26 "BasicIndex",
27 "BasicIndexStrategy",
28 "BroadcastableShapes",
29 "MutuallyBroadcastableShapesStrategy",
30 "Shape",
31 "_BIENoEllipsis",
32 "_BIENoEllipsisNoNewaxis",
33 "_BIENoNewaxis",
34 "array_shapes",
35 "broadcastable_shapes",
36 "check_argument",
37 "check_valid_dims",
38 "mutually_broadcastable_shapes",
39 "order_check",
40 "valid_tuple_axes",
41 ]
42
43
44 Shape = tuple[int, ...]
45
46 # Type aliases for basic array index elements. Variants exist to accurately
47 # type the return value of basic_indices() based on allow_ellipsis/allow_newaxis.
48 _BIE = int | slice | None | EllipsisType
49 _BIENoEllipsis = int | slice | None
50 _BIENoNewaxis = int | slice | EllipsisType
51 _BIENoEllipsisNoNewaxis = int | slice
52
53 BasicIndex = _BIE | tuple[_BIE, ...]
54
55
56 class BroadcastableShapes(NamedTuple):
57 input_shapes: tuple[Shape, ...]
58 result_shape: Shape
59
60
61 @check_function
62 def check_argument(condition, fail_message, *f_args, **f_kwargs):
63 if not condition:
64 raise InvalidArgument(fail_message.format(*f_args, **f_kwargs))
65
66
67 @check_function
68 def order_check(name, floor, min_, max_):
69 if floor > min_:
70 raise InvalidArgument(f"min_{name} must be at least {floor} but was {min_}")
71 if min_ > max_:
72 raise InvalidArgument(f"min_{name}={min_} is larger than max_{name}={max_}")
73
74
75 # 32 is a dimension limit specific to NumPy, and does not necessarily apply to
76 # other array/tensor libraries. Historically these strategies were built for the
77 # NumPy extra, so it's nice to keep these limits, and it's seemingly unlikely
78 # someone would want to generate >32 dim arrays anyway.
79 # See https://github.com/HypothesisWorks/hypothesis/pull/3067.
80 NDIM_MAX = 32
81
82
83 @check_function
84 def check_valid_dims(dims, name):
85 if dims > NDIM_MAX:
86 raise InvalidArgument(
87 f"{name}={dims}, but Hypothesis does not support arrays with "
88 f"more than {NDIM_MAX} dimensions"
89 )
90
91
92 @defines_strategy()
93 def array_shapes(
94 *,
95 min_dims: int = 1,
96 max_dims: int | None = None,
97 min_side: int = 1,
98 max_side: int | None = None,
99 ) -> st.SearchStrategy[Shape]:
100 """Return a strategy for array shapes (tuples of int >= 1).
101
102 * ``min_dims`` is the smallest length that the generated shape can possess.
103 * ``max_dims`` is the largest length that the generated shape can possess,
104 defaulting to ``min_dims + 2``.
105 * ``min_side`` is the smallest size that a dimension can possess.
106 * ``max_side`` is the largest size that a dimension can possess,
107 defaulting to ``min_side + 5``.
108 """
109 check_type(int, min_dims, "min_dims")
110 check_type(int, min_side, "min_side")
111 check_valid_dims(min_dims, "min_dims")
112
113 if max_dims is None:
114 max_dims = min(min_dims + 2, NDIM_MAX)
115 check_type(int, max_dims, "max_dims")
116 check_valid_dims(max_dims, "max_dims")
117
118 if max_side is None:
119 max_side = min_side + 5
120 check_type(int, max_side, "max_side")
121
122 order_check("dims", 0, min_dims, max_dims)
123 order_check("side", 0, min_side, max_side)
124
125 return st.lists(
126 st.integers(min_side, max_side), min_size=min_dims, max_size=max_dims
127 ).map(tuple)
128
129
130 @defines_strategy()
131 def valid_tuple_axes(
132 ndim: int,
133 *,
134 min_size: int = 0,
135 max_size: int | None = None,
136 ) -> st.SearchStrategy[tuple[int, ...]]:
137 """
138 All tuples will have a length >= ``min_size`` and <= ``max_size``. The default
139 value for ``max_size`` is ``ndim``.
140
141 Examples from this strategy shrink towards an empty tuple, which render most
142 sequential functions as no-ops.
143
144 The following are some examples drawn from this strategy.
145
146 .. code-block:: pycon
147
148 >>> [valid_tuple_axes(3).example() for i in range(4)]
149 [(-3, 1), (0, 1, -1), (0, 2), (0, -2, 2)]
150
151 ``valid_tuple_axes`` can be joined with other strategies to generate
152 any type of valid axis object, i.e. integers, tuples, and ``None``:
153
154 .. code-block:: python
155
156 any_axis_strategy = none() | integers(-ndim, ndim - 1) | valid_tuple_axes(ndim)
157 """
158 check_type(int, ndim, "ndim")
159 check_type(int, min_size, "min_size")
160 if max_size is None:
161 max_size = ndim
162 check_type(int, max_size, "max_size")
163 order_check("size", 0, min_size, max_size)
164 check_valid_interval(max_size, ndim, "max_size", "ndim")
165
166 axes = st.integers(0, max(0, 2 * ndim - 1)).map(
167 lambda x: x if x < ndim else x - 2 * ndim
168 )
169
170 return st.lists(
171 axes, min_size=min_size, max_size=max_size, unique_by=lambda x: x % ndim
172 ).map(tuple)
173
174
175 @defines_strategy()
176 def broadcastable_shapes(
177 shape: Shape,
178 *,
179 min_dims: int = 0,
180 max_dims: int | None = None,
181 min_side: int = 1,
182 max_side: int | None = None,
183 ) -> st.SearchStrategy[Shape]:
184 """Return a strategy for shapes that are broadcast-compatible with the
185 provided shape.
186
187 Examples from this strategy shrink towards a shape with length ``min_dims``.
188 The size of an aligned dimension shrinks towards size ``1``. The size of an
189 unaligned dimension shrink towards ``min_side``.
190
191 * ``shape`` is a tuple of integers.
192 * ``min_dims`` is the smallest length that the generated shape can possess.
193 * ``max_dims`` is the largest length that the generated shape can possess,
194 defaulting to ``max(len(shape), min_dims) + 2``.
195 * ``min_side`` is the smallest size that an unaligned dimension can possess.
196 * ``max_side`` is the largest size that an unaligned dimension can possess,
197 defaulting to 2 plus the size of the largest aligned dimension.
198
199 The following are some examples drawn from this strategy.
200
201 .. code-block:: pycon
202
203 >>> [broadcastable_shapes(shape=(2, 3)).example() for i in range(5)]
204 [(1, 3), (), (2, 3), (2, 1), (4, 1, 3), (3, )]
205
206 """
207 check_type(tuple, shape, "shape")
208 check_type(int, min_side, "min_side")
209 check_type(int, min_dims, "min_dims")
210 check_valid_dims(min_dims, "min_dims")
211
212 strict_check = max_side is None or max_dims is None
213
214 if max_dims is None:
215 max_dims = min(max(len(shape), min_dims) + 2, NDIM_MAX)
216 check_type(int, max_dims, "max_dims")
217 check_valid_dims(max_dims, "max_dims")
218
219 if max_side is None:
220 max_side = max(shape[-max_dims:] + (min_side,)) + 2
221 check_type(int, max_side, "max_side")
222
223 order_check("dims", 0, min_dims, max_dims)
224 order_check("side", 0, min_side, max_side)
225
226 if strict_check:
227 dims = max_dims
228 bound_name = "max_dims"
229 else:
230 dims = min_dims
231 bound_name = "min_dims"
232
233 # check for unsatisfiable min_side
234 if not all(min_side <= s for s in shape[::-1][:dims] if s != 1):
235 raise InvalidArgument(
236 f"Given shape={shape}, there are no broadcast-compatible "
237 f"shapes that satisfy: {bound_name}={dims} and min_side={min_side}"
238 )
239
240 # check for unsatisfiable [min_side, max_side]
241 if not (
242 min_side <= 1 <= max_side or all(s <= max_side for s in shape[::-1][:dims])
243 ):
244 raise InvalidArgument(
245 f"Given base_shape={shape}, there are no broadcast-compatible "
246 f"shapes that satisfy all of {bound_name}={dims}, "
247 f"min_side={min_side}, and max_side={max_side}"
248 )
249
250 if not strict_check:
251 # reduce max_dims to exclude unsatisfiable dimensions
252 for n, s in zip(range(max_dims), shape[::-1], strict=False):
253 if s < min_side and s != 1:
254 max_dims = n
255 break
256 if not (min_side <= 1 <= max_side or s <= max_side):
257 max_dims = n
258 break
259
260 return MutuallyBroadcastableShapesStrategy(
261 num_shapes=1,
262 base_shape=shape,
263 min_dims=min_dims,
264 max_dims=max_dims,
265 min_side=min_side,
266 max_side=max_side,
267 ).map(lambda x: x.input_shapes[0])
268
269
270 # See https://numpy.org/doc/stable/reference/c-api/generalized-ufuncs.html
271 # Implementation based on numpy.lib.function_base._parse_gufunc_signature
272 # with minor upgrades to handle numeric and optional dimensions. Examples:
273 #
274 # add (),()->() binary ufunc
275 # sum1d (i)->() reduction
276 # inner1d (i),(i)->() vector-vector multiplication
277 # matmat (m,n),(n,p)->(m,p) matrix multiplication
278 # vecmat (n),(n,p)->(p) vector-matrix multiplication
279 # matvec (m,n),(n)->(m) matrix-vector multiplication
280 # matmul (m?,n),(n,p?)->(m?,p?) combination of the four above
281 # cross1d (3),(3)->(3) cross product with frozen dimensions
282 #
283 # Note that while no examples of such usage are given, Numpy does allow
284 # generalised ufuncs that have *multiple output arrays*. This is not
285 # currently supported by Hypothesis - please contact us if you would use it!
286 #
287 # We are unsure if gufuncs allow frozen dimensions to be optional, but it's
288 # easy enough to support here - and so we will unless we learn otherwise.
289 _DIMENSION = r"\w+\??" # Note that \w permits digits too!
290 _SHAPE = rf"\((?:{_DIMENSION}(?:,{_DIMENSION}){{0,31}})?\)"
291 _ARGUMENT_LIST = f"{_SHAPE}(?:,{_SHAPE})*"
292 _SIGNATURE = rf"^{_ARGUMENT_LIST}->{_SHAPE}$"
293 _SIGNATURE_MULTIPLE_OUTPUT = rf"^{_ARGUMENT_LIST}->{_ARGUMENT_LIST}$"
294
295
296 class _GUfuncSig(NamedTuple):
297 input_shapes: tuple[Shape, ...]
298 result_shape: Shape
299
300
301 def _hypothesis_parse_gufunc_signature(signature):
302 # Disable all_checks to better match the Numpy version, for testing
303 if not re.match(_SIGNATURE, signature):
304 if re.match(_SIGNATURE_MULTIPLE_OUTPUT, signature):
305 raise InvalidArgument(
306 "Hypothesis does not yet support generalised ufunc signatures "
307 "with multiple output arrays - mostly because we don't know of "
308 "anyone who uses them! Please get in touch with us to fix that."
309 f"\n ({signature=})"
310 )
311 if re.match(
312 (
313 # Taken from np.lib.function_base._SIGNATURE
314 r"^\((?:\w+(?:,\w+)*)?\)(?:,\((?:\w+(?:,\w+)*)?\))*->"
315 r"\((?:\w+(?:,\w+)*)?\)(?:,\((?:\w+(?:,\w+)*)?\))*$"
316 ),
317 signature,
318 ):
319 raise InvalidArgument(
320 f"{signature=} matches Numpy's regex for gufunc signatures, "
321 f"but contains shapes with more than {NDIM_MAX} dimensions and is thus invalid."
322 )
323 raise InvalidArgument(f"{signature!r} is not a valid gufunc signature")
324 input_shapes, output_shapes = (
325 tuple(tuple(re.findall(_DIMENSION, a)) for a in re.findall(_SHAPE, arg_list))
326 for arg_list in signature.split("->")
327 )
328 assert len(output_shapes) == 1
329 result_shape = output_shapes[0]
330 # Check that there are no names in output shape that do not appear in inputs.
331 # (kept out of parser function for easier generation of test values)
332 # We also disallow frozen optional dimensions - this is ambiguous as there is
333 # no way to share an un-named dimension between shapes. Maybe just padding?
334 # Anyway, we disallow it pending clarification from upstream.
335 for shape in (*input_shapes, result_shape):
336 for name in shape:
337 try:
338 int(name.strip("?"))
339 if "?" in name:
340 raise InvalidArgument(
341 f"Got dimension {name!r}, but handling of frozen optional dimensions "
342 "is ambiguous. If you known how this should work, please "
343 f"contact us to get this fixed and documented ({signature=})."
344 )
345 except ValueError:
346 names_in = {n.strip("?") for shp in input_shapes for n in shp}
347 names_out = {n.strip("?") for n in result_shape}
348 if name.strip("?") in (names_out - names_in):
349 raise InvalidArgument(
350 f"The {name!r} dimension only appears in the output shape, and is "
351 f"not frozen, so the size is not determined ({signature=})."
352 ) from None
353 return _GUfuncSig(input_shapes=input_shapes, result_shape=result_shape)
354
355
356 @defines_strategy()
357 def mutually_broadcastable_shapes(
358 *,
359 num_shapes: UniqueIdentifier | int = not_set,
360 signature: UniqueIdentifier | str = not_set,
361 base_shape: Shape = (),
362 min_dims: int = 0,
363 max_dims: int | None = None,
364 min_side: int = 1,
365 max_side: int | None = None,
366 ) -> st.SearchStrategy[BroadcastableShapes]:
367 """
368 Return a strategy for a specified number of shapes N that are
369 mutually-broadcastable with one another and with the provided base shape.
370
371 * ``num_shapes`` is the number of mutually broadcast-compatible shapes to generate.
372 * ``base_shape`` is the shape against which all generated shapes can broadcast.
373 The default shape is empty, which corresponds to a scalar and thus does
374 not constrain broadcasting at all.
375 * ``min_dims`` is the smallest length that the generated shape can possess.
376 * ``max_dims`` is the largest length that the generated shape can possess,
377 defaulting to ``max(len(shape), min_dims) + 2``.
378 * ``min_side`` is the smallest size that an unaligned dimension can possess.
379 * ``max_side`` is the largest size that an unaligned dimension can possess,
380 defaulting to 2 plus the size of the largest aligned dimension.
381
382 The strategy will generate a :obj:`python:typing.NamedTuple` containing:
383
384 * ``input_shapes`` as a tuple of the N generated shapes.
385 * ``result_shape`` as the resulting shape produced by broadcasting the N shapes
386 with the base shape.
387
388 The following are some examples drawn from this strategy.
389
390 .. code-block:: pycon
391
392 >>> # Draw three shapes where each shape is broadcast-compatible with (2, 3)
393 ... strat = mutually_broadcastable_shapes(num_shapes=3, base_shape=(2, 3))
394 >>> for _ in range(5):
395 ... print(strat.example())
396 BroadcastableShapes(input_shapes=((4, 1, 3), (4, 2, 3), ()), result_shape=(4, 2, 3))
397 BroadcastableShapes(input_shapes=((3,), (1, 3), (2, 3)), result_shape=(2, 3))
398 BroadcastableShapes(input_shapes=((), (), ()), result_shape=())
399 BroadcastableShapes(input_shapes=((3,), (), (3,)), result_shape=(3,))
400 BroadcastableShapes(input_shapes=((1, 2, 3), (3,), ()), result_shape=(1, 2, 3))
401 """
402 arg_msg = "Pass either the `num_shapes` or the `signature` argument, but not both."
403 if num_shapes is not not_set:
404 check_argument(signature is not_set, arg_msg)
405 check_type(int, num_shapes, "num_shapes")
406 assert isinstance(num_shapes, int) # for mypy
407 parsed_signature = None
408 sig_dims = 0
409 else:
410 check_argument(signature is not not_set, arg_msg)
411 if signature is None:
412 raise InvalidArgument(
413 "Expected a string, but got invalid signature=None. "
414 "(maybe .signature attribute of an element-wise ufunc?)"
415 )
416 check_type(str, signature, "signature")
417 parsed_signature = _hypothesis_parse_gufunc_signature(signature)
418 all_shapes = (*parsed_signature.input_shapes, parsed_signature.result_shape)
419 sig_dims = min(len(s) for s in all_shapes)
420 num_shapes = len(parsed_signature.input_shapes)
421
422 if num_shapes < 1:
423 raise InvalidArgument(f"num_shapes={num_shapes} must be at least 1")
424
425 check_type(tuple, base_shape, "base_shape")
426 check_type(int, min_side, "min_side")
427 check_type(int, min_dims, "min_dims")
428 check_valid_dims(min_dims, "min_dims")
429
430 strict_check = max_dims is not None
431
432 if max_dims is None:
433 max_dims = min(max(len(base_shape), min_dims) + 2, NDIM_MAX - sig_dims)
434 check_type(int, max_dims, "max_dims")
435 check_valid_dims(max_dims, "max_dims")
436
437 if max_side is None:
438 max_side = max(base_shape[-max_dims:] + (min_side,)) + 2
439 check_type(int, max_side, "max_side")
440
441 order_check("dims", 0, min_dims, max_dims)
442 order_check("side", 0, min_side, max_side)
443
444 if signature is not None and max_dims > NDIM_MAX - sig_dims:
445 raise InvalidArgument(
446 f"max_dims={signature!r} would exceed the {NDIM_MAX}-dimension"
447 "limit Hypothesis imposes on array shapes, "
448 f"given signature={parsed_signature!r}"
449 )
450
451 if strict_check:
452 dims = max_dims
453 bound_name = "max_dims"
454 else:
455 dims = min_dims
456 bound_name = "min_dims"
457
458 # check for unsatisfiable min_side
459 if not all(min_side <= s for s in base_shape[::-1][:dims] if s != 1):
460 raise InvalidArgument(
461 f"Given base_shape={base_shape}, there are no broadcast-compatible "
462 f"shapes that satisfy: {bound_name}={dims} and min_side={min_side}"
463 )
464
465 # check for unsatisfiable [min_side, max_side]
466 if not (
467 min_side <= 1 <= max_side or all(s <= max_side for s in base_shape[::-1][:dims])
468 ):
469 raise InvalidArgument(
470 f"Given base_shape={base_shape}, there are no broadcast-compatible "
471 f"shapes that satisfy all of {bound_name}={dims}, "
472 f"min_side={min_side}, and max_side={max_side}"
473 )
474
475 if not strict_check:
476 # reduce max_dims to exclude unsatisfiable dimensions
477 for n, s in zip(range(max_dims), base_shape[::-1], strict=False):
478 if s < min_side and s != 1:
479 max_dims = n
480 break
481 if not (min_side <= 1 <= max_side or s <= max_side):
482 max_dims = n
483 break
484
485 return MutuallyBroadcastableShapesStrategy(
486 num_shapes=num_shapes,
487 signature=parsed_signature,
488 base_shape=base_shape,
489 min_dims=min_dims,
490 max_dims=max_dims,
491 min_side=min_side,
492 max_side=max_side,
493 )
494
495
496 class MutuallyBroadcastableShapesStrategy(st.SearchStrategy):
497 def __init__(
498 self,
499 num_shapes,
500 signature=None,
501 base_shape=(),
502 min_dims=0,
503 max_dims=None,
504 min_side=1,
505 max_side=None,
506 ):
507 super().__init__()
508 self.base_shape = base_shape
509 self.side_strat = st.integers(min_side, max_side)
510 self.num_shapes = num_shapes
511 self.signature = signature
512 self.min_dims = min_dims
513 self.max_dims = max_dims
514 self.min_side = min_side
515 self.max_side = max_side
516
517 self.size_one_allowed = self.min_side <= 1 <= self.max_side
518
519 def do_draw(self, data):
520 # We don't usually have a gufunc signature; do the common case first & fast.
521 if self.signature is None:
522 return self._draw_loop_dimensions(data)
523
524 # When we *do*, draw the core dims, then draw loop dims, and finally combine.
525 core_in, core_res = self._draw_core_dimensions(data)
526
527 # If some core shape has omitted optional dimensions, it's an error to add
528 # loop dimensions to it. We never omit core dims if min_dims >= 1.
529 # This ensures that we respect Numpy's gufunc broadcasting semantics and user
530 # constraints without needing to check whether the loop dims will be
531 # interpreted as an invalid substitute for the omitted core dims.
532 # We may implement this check later!
533 use = [None not in shp for shp in core_in]
534 loop_in, loop_res = self._draw_loop_dimensions(data, use=use)
535
536 def add_shape(loop, core):
537 return tuple(x for x in (loop + core)[-NDIM_MAX:] if x is not None)
538
539 return BroadcastableShapes(
540 input_shapes=tuple(
541 add_shape(l_in, c) for l_in, c in zip(loop_in, core_in, strict=True)
542 ),
543 result_shape=add_shape(loop_res, core_res),
544 )
545
546 def _draw_core_dimensions(self, data):
547 # Draw gufunc core dimensions, with None standing for optional dimensions
548 # that will not be present in the final shape. We track omitted dims so
549 # that we can do an accurate per-shape length cap.
550 dims = {}
551 shapes = []
552 for shape in (*self.signature.input_shapes, self.signature.result_shape):
553 shapes.append([])
554 for name in shape:
555 if name.isdigit():
556 shapes[-1].append(int(name))
557 continue
558 if name not in dims:
559 dim = name.strip("?")
560 dims[dim] = data.draw(self.side_strat)
561 if self.min_dims == 0 and not data.draw_boolean(7 / 8):
562 dims[dim + "?"] = None
563 else:
564 dims[dim + "?"] = dims[dim]
565 shapes[-1].append(dims[name])
566 return tuple(tuple(s) for s in shapes[:-1]), tuple(shapes[-1])
567
568 def _draw_loop_dimensions(self, data, use=None):
569 # All shapes are handled in column-major order; i.e. they are reversed
570 base_shape = self.base_shape[::-1]
571 result_shape = list(base_shape)
572 shapes = [[] for _ in range(self.num_shapes)]
573 if use is None:
574 use = [True for _ in range(self.num_shapes)]
575 else:
576 assert len(use) == self.num_shapes
577 assert all(isinstance(x, bool) for x in use)
578
579 _gap = self.max_dims - self.min_dims
580 p_keep_extending_shape = _calc_p_continue(desired_avg=_gap / 2, max_size=_gap)
581
582 for dim_count in range(1, self.max_dims + 1):
583 dim = dim_count - 1
584
585 # We begin by drawing a valid dimension-size for the given
586 # dimension. This restricts the variability across the shapes
587 # at this dimension such that they can only choose between
588 # this size and a singleton dimension.
589 if len(base_shape) < dim_count or base_shape[dim] == 1:
590 # dim is unrestricted by the base-shape: shrink to min_side
591 dim_side = data.draw(self.side_strat)
592 elif base_shape[dim] <= self.max_side:
593 # dim is aligned with non-singleton base-dim
594 dim_side = base_shape[dim]
595 else:
596 # only a singleton is valid in alignment with the base-dim
597 dim_side = 1
598
599 allowed_sides = sorted([1, dim_side]) # shrink to 0 when available
600 for shape_id, shape in enumerate(shapes):
601 # Populating this dimension-size for each shape, either
602 # the drawn size is used or, if permitted, a singleton
603 # dimension.
604 if dim <= len(result_shape) and self.size_one_allowed:
605 # aligned: shrink towards size 1
606 side = data.draw(st.sampled_from(allowed_sides))
607 else:
608 side = dim_side
609
610 # Use a trick where a biased coin is queried to see
611 # if the given shape-tuple will continue to be grown. All
612 # of the relevant draws will still be made for the given
613 # shape-tuple even if it is no longer being added to.
614 # This helps to ensure more stable shrinking behavior.
615 if self.min_dims < dim_count:
616 use[shape_id] &= data.draw_boolean(p_keep_extending_shape)
617
618 if use[shape_id]:
619 shape.append(side)
620 if len(result_shape) < len(shape):
621 result_shape.append(shape[-1])
622 elif shape[-1] != 1 and result_shape[dim] == 1:
623 result_shape[dim] = shape[-1]
624 if not any(use):
625 break
626
627 result_shape = result_shape[: max(map(len, [self.base_shape, *shapes]))]
628
629 assert len(shapes) == self.num_shapes
630 assert all(self.min_dims <= len(s) <= self.max_dims for s in shapes)
631 assert all(self.min_side <= s <= self.max_side for side in shapes for s in side)
632
633 return BroadcastableShapes(
634 input_shapes=tuple(tuple(reversed(shape)) for shape in shapes),
635 result_shape=tuple(reversed(result_shape)),
636 )
637
638
639 class BasicIndexStrategy(st.SearchStrategy):
640 def __init__(
641 self,
642 shape,
643 min_dims,
644 max_dims,
645 allow_ellipsis,
646 allow_newaxis,
647 allow_fewer_indices_than_dims,
648 ):
649 super().__init__()
650 self.shape = shape
651 self.min_dims = min_dims
652 self.max_dims = max_dims
653 self.allow_ellipsis = allow_ellipsis
654 self.allow_newaxis = allow_newaxis
655 # allow_fewer_indices_than_dims=False will disable generating indices
656 # that don't cover all axes, i.e. indices that will flat index arrays.
657 # This is necessary for the Array API as such indices are not supported.
658 self.allow_fewer_indices_than_dims = allow_fewer_indices_than_dims
659
660 def do_draw(self, data):
661 # General plan: determine the actual selection up front with a straightforward
662 # approach that shrinks well, then complicate it by inserting other things.
663 result = []
664 for dim_size in self.shape:
665 if dim_size == 0:
666 result.append(slice(None))
667 continue
668 strategy = st.integers(-dim_size, dim_size - 1) | st.slices(dim_size)
669 result.append(data.draw(strategy))
670 # Insert some number of new size-one dimensions if allowed
671 result_dims = sum(isinstance(idx, slice) for idx in result)
672 while (
673 self.allow_newaxis
674 and result_dims < self.max_dims
675 and (result_dims < self.min_dims or data.draw(st.booleans()))
676 ):
677 i = data.draw(st.integers(0, len(result)))
678 result.insert(i, None) # Note that `np.newaxis is None`
679 result_dims += 1
680 # Check that we'll have the right number of dimensions; reject if not.
681 # It's easy to do this by construction if you don't care about shrinking,
682 # which is really important for array shapes. So we filter instead.
683 assume(self.min_dims <= result_dims <= self.max_dims)
684 # This is a quick-and-dirty way to insert ..., xor shorten the indexer,
685 # but it means we don't have to do any structural analysis.
686 if self.allow_ellipsis and data.draw(st.booleans()):
687 # Choose an index; then replace all adjacent whole-dimension slices.
688 i = j = data.draw(st.integers(0, len(result)))
689 while i > 0 and result[i - 1] == slice(None):
690 i -= 1
691 while j < len(result) and result[j] == slice(None):
692 j += 1
693 result[i:j] = [Ellipsis]
694 elif self.allow_fewer_indices_than_dims: # pragma: no cover
695 while result[-1:] == [slice(None, None)] and data.draw(st.integers(0, 7)):
696 result.pop()
697 if len(result) == 1 and data.draw(st.booleans()):
698 # Sometimes generate bare element equivalent to a length-one tuple
699 return result[0]
700 return tuple(result)