| 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 |
from collections import OrderedDict, abc |
| 12 |
from collections.abc import Sequence |
| 13 |
from copy import copy |
| 14 |
from dataclasses import dataclass |
| 15 |
from datetime import datetime, timedelta |
| 16 |
from typing import Any, Generic, Union |
| 17 |
|
| 18 |
import numpy as np |
| 19 |
import pandas |
| 20 |
|
| 21 |
from hypothesis import strategies as st |
| 22 |
from hypothesis.control import reject |
| 23 |
from hypothesis.errors import InvalidArgument |
| 24 |
from hypothesis.extra import numpy as npst |
| 25 |
from hypothesis.internal.conjecture import utils as cu |
| 26 |
from hypothesis.internal.coverage import check, check_function |
| 27 |
from hypothesis.internal.validation import ( |
| 28 |
check_type, |
| 29 |
check_valid_interval, |
| 30 |
check_valid_size, |
| 31 |
try_convert, |
| 32 |
) |
| 33 |
from hypothesis.strategies._internal.strategies import Ex, check_strategy |
| 34 |
from hypothesis.strategies._internal.utils import cacheable, defines_strategy |
| 35 |
from hypothesis.utils.deprecation import note_deprecation |
| 36 |
|
| 37 |
try: |
| 38 |
from pandas.core.arrays.integer import IntegerDtype |
| 39 |
except ImportError: |
| 40 |
IntegerDtype = () |
| 41 |
|
| 42 |
|
| 43 |
def dtype_for_elements_strategy(s): |
| 44 |
return st.shared( |
| 45 |
s.map(lambda x: pandas.Series([x]).dtype), |
| 46 |
key=("hypothesis.extra.pandas.dtype_for_elements_strategy", s), |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
def infer_dtype_if_necessary(dtype, values, elements, draw): |
| 51 |
if dtype is None and not values: |
| 52 |
return draw(dtype_for_elements_strategy(elements)) |
| 53 |
return dtype |
| 54 |
|
| 55 |
|
| 56 |
@check_function |
| 57 |
def elements_and_dtype(elements, dtype, source=None): |
| 58 |
if source is None: |
| 59 |
prefix = "" |
| 60 |
else: |
| 61 |
prefix = f"{source}." |
| 62 |
|
| 63 |
if elements is not None: |
| 64 |
check_strategy(elements, f"{prefix}elements") |
| 65 |
else: |
| 66 |
with check("dtype is not None"): |
| 67 |
if dtype is None: |
| 68 |
raise InvalidArgument( |
| 69 |
f"At least one of {prefix}elements or {prefix}dtype must be provided." |
| 70 |
) |
| 71 |
|
| 72 |
with check("isinstance(dtype, CategoricalDtype)"): |
| 73 |
if pandas.api.types.CategoricalDtype.is_dtype(dtype): |
| 74 |
raise InvalidArgument( |
| 75 |
f"{prefix}dtype is categorical, which is currently unsupported" |
| 76 |
) |
| 77 |
|
| 78 |
if isinstance(dtype, type) and issubclass(dtype, IntegerDtype): |
| 79 |
raise InvalidArgument( |
| 80 |
f"Passed {dtype=} is a dtype class, please pass in an instance of this class." |
| 81 |
"Otherwise it would be treated as dtype=object" |
| 82 |
) |
| 83 |
|
| 84 |
if isinstance(dtype, type) and np.dtype(dtype).kind == "O" and dtype is not object: |
| 85 |
err_msg = f"Passed {dtype=} is not a valid Pandas dtype." |
| 86 |
if issubclass(dtype, datetime): |
| 87 |
err_msg += ' To generate valid datetimes, pass `dtype="datetime64[ns]"`' |
| 88 |
raise InvalidArgument(err_msg) |
| 89 |
elif issubclass(dtype, timedelta): |
| 90 |
err_msg += ' To generate valid timedeltas, pass `dtype="timedelta64[ns]"`' |
| 91 |
raise InvalidArgument(err_msg) |
| 92 |
note_deprecation( |
| 93 |
f"{err_msg} We'll treat it as " |
| 94 |
"dtype=object for now, but this will be an error in a future version.", |
| 95 |
since="2021-12-31", |
| 96 |
has_codemod=False, |
| 97 |
stacklevel=1, |
| 98 |
) |
| 99 |
|
| 100 |
if isinstance(dtype, st.SearchStrategy): |
| 101 |
raise InvalidArgument( |
| 102 |
f"Passed {dtype=} is a strategy, but we require a concrete dtype " |
| 103 |
"here. See https://stackoverflow.com/q/74355937 for workaround patterns." |
| 104 |
) |
| 105 |
|
| 106 |
_get_subclasses = getattr(IntegerDtype, "__subclasses__", list) |
| 107 |
dtype = {t.name: t() for t in _get_subclasses()}.get(dtype, dtype) |
| 108 |
|
| 109 |
is_na_dtype = False |
| 110 |
if isinstance(dtype, IntegerDtype): |
| 111 |
is_na_dtype = True |
| 112 |
dtype = np.dtype(dtype.name.lower()) |
| 113 |
elif dtype is not None: |
| 114 |
dtype = try_convert(np.dtype, dtype, "dtype") |
| 115 |
|
| 116 |
if elements is None: |
| 117 |
elements = npst.from_dtype(dtype) |
| 118 |
if is_na_dtype: |
| 119 |
elements = st.none() | elements |
| 120 |
# as an optimization, avoid converting object dtypes, which will always |
| 121 |
# remain unchanged. |
| 122 |
elif dtype is not None and dtype.kind != "O": |
| 123 |
|
| 124 |
def convert_element(value): |
| 125 |
if is_na_dtype and value is None: |
| 126 |
return None |
| 127 |
|
| 128 |
try: |
| 129 |
return np.array([value], dtype=dtype)[0] |
| 130 |
except (TypeError, ValueError, OverflowError): |
| 131 |
name = f"draw({prefix}elements)" |
| 132 |
raise InvalidArgument( |
| 133 |
f"Cannot convert {name}={value!r} of type " |
| 134 |
f"{type(value).__name__} to dtype {dtype.str}" |
| 135 |
) from None |
| 136 |
|
| 137 |
elements = elements.map(convert_element) |
| 138 |
assert elements is not None |
| 139 |
|
| 140 |
return elements, dtype |
| 141 |
|
| 142 |
|
| 143 |
class ValueIndexStrategy(st.SearchStrategy): |
| 144 |
def __init__(self, elements, dtype, min_size, max_size, unique, name): |
| 145 |
super().__init__() |
| 146 |
self.elements = elements |
| 147 |
self.dtype = dtype |
| 148 |
self.min_size = min_size |
| 149 |
self.max_size = max_size |
| 150 |
self.unique = unique |
| 151 |
self.name = name |
| 152 |
|
| 153 |
def do_draw(self, data): |
| 154 |
result = [] |
| 155 |
seen = set() |
| 156 |
|
| 157 |
iterator = cu.many( |
| 158 |
data, |
| 159 |
min_size=self.min_size, |
| 160 |
max_size=self.max_size, |
| 161 |
average_size=(self.min_size + self.max_size) / 2, |
| 162 |
) |
| 163 |
|
| 164 |
while iterator.more(): |
| 165 |
elt = data.draw(self.elements) |
| 166 |
|
| 167 |
if self.unique: |
| 168 |
if elt in seen: |
| 169 |
iterator.reject() |
| 170 |
continue |
| 171 |
seen.add(elt) |
| 172 |
result.append(elt) |
| 173 |
|
| 174 |
dtype = infer_dtype_if_necessary( |
| 175 |
dtype=self.dtype, values=result, elements=self.elements, draw=data.draw |
| 176 |
) |
| 177 |
return pandas.Index( |
| 178 |
result, dtype=dtype, tupleize_cols=False, name=data.draw(self.name) |
| 179 |
) |
| 180 |
|
| 181 |
|
| 182 |
DEFAULT_MAX_SIZE = 10 |
| 183 |
|
| 184 |
|
| 185 |
@cacheable |
| 186 |
@defines_strategy() |
| 187 |
def range_indexes( |
| 188 |
min_size: int = 0, |
| 189 |
max_size: int | None = None, |
| 190 |
name: st.SearchStrategy[str | None] = st.none(), |
| 191 |
) -> st.SearchStrategy[pandas.RangeIndex]: |
| 192 |
"""Provides a strategy which generates an :class:`~pandas.Index` whose |
| 193 |
values are 0, 1, ..., n for some n. |
| 194 |
|
| 195 |
Arguments: |
| 196 |
|
| 197 |
* min_size is the smallest number of elements the index can have. |
| 198 |
* max_size is the largest number of elements the index can have. If None |
| 199 |
it will default to some suitable value based on min_size. |
| 200 |
* name is the name of the index. If st.none(), the index will have no name. |
| 201 |
""" |
| 202 |
check_valid_size(min_size, "min_size") |
| 203 |
check_valid_size(max_size, "max_size") |
| 204 |
if max_size is None: |
| 205 |
max_size = min([min_size + DEFAULT_MAX_SIZE, 2**63 - 1]) |
| 206 |
check_valid_interval(min_size, max_size, "min_size", "max_size") |
| 207 |
check_strategy(name) |
| 208 |
|
| 209 |
return st.builds(pandas.RangeIndex, st.integers(min_size, max_size), name=name) |
| 210 |
|
| 211 |
|
| 212 |
@cacheable |
| 213 |
@defines_strategy() |
| 214 |
def indexes( |
| 215 |
*, |
| 216 |
elements: st.SearchStrategy[Ex] | None = None, |
| 217 |
dtype: Any = None, |
| 218 |
min_size: int = 0, |
| 219 |
max_size: int | None = None, |
| 220 |
unique: bool = True, |
| 221 |
name: st.SearchStrategy[str | None] = st.none(), |
| 222 |
) -> st.SearchStrategy[pandas.Index]: |
| 223 |
"""Provides a strategy for producing a :class:`pandas.Index`. |
| 224 |
|
| 225 |
Arguments: |
| 226 |
|
| 227 |
* elements is a strategy which will be used to generate the individual |
| 228 |
values of the index. If None, it will be inferred from the dtype. Note: |
| 229 |
even if the elements strategy produces tuples, the generated value |
| 230 |
will not be a MultiIndex, but instead be a normal index whose elements |
| 231 |
are tuples. |
| 232 |
* dtype is the dtype of the resulting index. If None, it will be inferred |
| 233 |
from the elements strategy. At least one of dtype or elements must be |
| 234 |
provided. |
| 235 |
* min_size is the minimum number of elements in the index. |
| 236 |
* max_size is the maximum number of elements in the index. If None then it |
| 237 |
will default to a suitable small size. If you want larger indexes you |
| 238 |
should pass a max_size explicitly. |
| 239 |
* unique specifies whether all of the elements in the resulting index |
| 240 |
should be distinct. |
| 241 |
* name is a strategy for strings or ``None``, which will be passed to |
| 242 |
the :class:`pandas.Index` constructor. |
| 243 |
""" |
| 244 |
check_valid_size(min_size, "min_size") |
| 245 |
check_valid_size(max_size, "max_size") |
| 246 |
check_valid_interval(min_size, max_size, "min_size", "max_size") |
| 247 |
check_type(bool, unique, "unique") |
| 248 |
|
| 249 |
elements, dtype = elements_and_dtype(elements, dtype) |
| 250 |
|
| 251 |
if max_size is None: |
| 252 |
max_size = min_size + DEFAULT_MAX_SIZE |
| 253 |
return ValueIndexStrategy(elements, dtype, min_size, max_size, unique, name) |
| 254 |
|
| 255 |
|
| 256 |
@defines_strategy() |
| 257 |
def series( |
| 258 |
*, |
| 259 |
elements: st.SearchStrategy[Ex] | None = None, |
| 260 |
dtype: Any = None, |
| 261 |
# new-style unions hit https://github.com/sphinx-doc/sphinx/issues/11211 during |
| 262 |
# doc builds. See related comment in django/_fields.py. Quote to prevent |
| 263 |
# shed/pyupgrade from changing it. |
| 264 |
index: ( |
| 265 |
st.SearchStrategy["Union[Sequence, pandas.Index]"] | None # noqa: UP007 |
| 266 |
) = None, |
| 267 |
fill: st.SearchStrategy[Ex] | None = None, |
| 268 |
unique: bool = False, |
| 269 |
name: st.SearchStrategy[str | None] = st.none(), |
| 270 |
) -> st.SearchStrategy[pandas.Series]: |
| 271 |
"""Provides a strategy for producing a :class:`pandas.Series`. |
| 272 |
|
| 273 |
Arguments: |
| 274 |
|
| 275 |
* elements: a strategy that will be used to generate the individual |
| 276 |
values in the series. If None, we will attempt to infer a suitable |
| 277 |
default from the dtype. |
| 278 |
|
| 279 |
* dtype: the dtype of the resulting series and may be any value |
| 280 |
that can be passed to :class:`numpy.dtype`. If None, will use |
| 281 |
pandas's standard behaviour to infer it from the type of the elements |
| 282 |
values. Note that if the type of values that comes out of your |
| 283 |
elements strategy varies, then so will the resulting dtype of the |
| 284 |
series. |
| 285 |
|
| 286 |
* index: If not None, a strategy for generating indexes for the |
| 287 |
resulting Series. This can generate either :class:`pandas.Index` |
| 288 |
objects or any sequence of values (which will be passed to the |
| 289 |
Index constructor). |
| 290 |
|
| 291 |
You will probably find it most convenient to use the |
| 292 |
:func:`~hypothesis.extra.pandas.indexes` or |
| 293 |
:func:`~hypothesis.extra.pandas.range_indexes` function to produce |
| 294 |
values for this argument. |
| 295 |
|
| 296 |
* name: is a strategy for strings or ``None``, which will be passed to |
| 297 |
the :class:`pandas.Series` constructor. |
| 298 |
|
| 299 |
Usage: |
| 300 |
|
| 301 |
.. code-block:: pycon |
| 302 |
|
| 303 |
>>> series(dtype=int).example() |
| 304 |
0 -2001747478 |
| 305 |
1 1153062837 |
| 306 |
""" |
| 307 |
if index is None: |
| 308 |
index = range_indexes() |
| 309 |
else: |
| 310 |
check_strategy(index, "index") |
| 311 |
|
| 312 |
elements, np_dtype = elements_and_dtype(elements, dtype) |
| 313 |
index_strategy = index |
| 314 |
|
| 315 |
# if it is converted to an object, use object for series type |
| 316 |
if ( |
| 317 |
np_dtype is not None |
| 318 |
and np_dtype.kind == "O" |
| 319 |
and not isinstance(dtype, IntegerDtype) |
| 320 |
): |
| 321 |
dtype = np_dtype |
| 322 |
|
| 323 |
@st.composite |
| 324 |
def result(draw): |
| 325 |
index = draw(index_strategy) |
| 326 |
|
| 327 |
if len(index) > 0: |
| 328 |
if dtype is not None: |
| 329 |
result_data = draw( |
| 330 |
npst.arrays( |
| 331 |
dtype=object, |
| 332 |
elements=elements, |
| 333 |
shape=len(index), |
| 334 |
fill=fill, |
| 335 |
unique=unique, |
| 336 |
) |
| 337 |
).tolist() |
| 338 |
else: |
| 339 |
result_data = list( |
| 340 |
draw( |
| 341 |
npst.arrays( |
| 342 |
dtype=object, |
| 343 |
elements=elements, |
| 344 |
shape=len(index), |
| 345 |
fill=fill, |
| 346 |
unique=unique, |
| 347 |
) |
| 348 |
).tolist() |
| 349 |
) |
| 350 |
return pandas.Series(result_data, index=index, dtype=dtype, name=draw(name)) |
| 351 |
else: |
| 352 |
return pandas.Series( |
| 353 |
(), |
| 354 |
index=index, |
| 355 |
dtype=( |
| 356 |
dtype |
| 357 |
if dtype is not None |
| 358 |
else draw(dtype_for_elements_strategy(elements)) |
| 359 |
), |
| 360 |
name=draw(name), |
| 361 |
) |
| 362 |
|
| 363 |
return result() |
| 364 |
|
| 365 |
|
| 366 |
@dataclass(slots=True, frozen=False) |
| 367 |
class column(Generic[Ex]): |
| 368 |
"""Data object for describing a column in a DataFrame. |
| 369 |
|
| 370 |
Arguments: |
| 371 |
|
| 372 |
* name: the column name, or None to default to the column position. Must |
| 373 |
be hashable, but can otherwise be any value supported as a pandas column |
| 374 |
name. |
| 375 |
* elements: the strategy for generating values in this column, or None |
| 376 |
to infer it from the dtype. |
| 377 |
* dtype: the dtype of the column, or None to infer it from the element |
| 378 |
strategy. At least one of dtype or elements must be provided. |
| 379 |
* fill: A default value for elements of the column. See |
| 380 |
:func:`~hypothesis.extra.numpy.arrays` for a full explanation. |
| 381 |
* unique: If all values in this column should be distinct. |
| 382 |
""" |
| 383 |
|
| 384 |
name: str | int | None = None |
| 385 |
elements: st.SearchStrategy[Ex] | None = None |
| 386 |
dtype: Any = None |
| 387 |
fill: st.SearchStrategy[Ex] | None = None |
| 388 |
unique: bool = False |
| 389 |
|
| 390 |
|
| 391 |
def columns( |
| 392 |
names_or_number: int | Sequence[str], |
| 393 |
*, |
| 394 |
dtype: Any = None, |
| 395 |
elements: st.SearchStrategy[Ex] | None = None, |
| 396 |
fill: st.SearchStrategy[Ex] | None = None, |
| 397 |
unique: bool = False, |
| 398 |
) -> list[column[Ex]]: |
| 399 |
"""A convenience function for producing a list of :class:`column` objects |
| 400 |
of the same general shape. |
| 401 |
|
| 402 |
The names_or_number argument is either a sequence of values, the |
| 403 |
elements of which will be used as the name for individual column |
| 404 |
objects, or a number, in which case that many unnamed columns will |
| 405 |
be created. All other arguments are passed through verbatim to |
| 406 |
create the columns. |
| 407 |
""" |
| 408 |
if isinstance(names_or_number, (int, float)): |
| 409 |
names: list[int | str | None] = [None] * names_or_number |
| 410 |
else: |
| 411 |
names = list(names_or_number) |
| 412 |
return [ |
| 413 |
column(name=n, dtype=dtype, elements=elements, fill=fill, unique=unique) |
| 414 |
for n in names |
| 415 |
] |
| 416 |
|
| 417 |
|
| 418 |
@defines_strategy() |
| 419 |
def data_frames( |
| 420 |
columns: Sequence[column] | None = None, |
| 421 |
*, |
| 422 |
rows: st.SearchStrategy[dict | Sequence[Any]] | None = None, |
| 423 |
index: st.SearchStrategy[Ex] | None = None, |
| 424 |
) -> st.SearchStrategy[pandas.DataFrame]: |
| 425 |
"""Provides a strategy for producing a :class:`pandas.DataFrame`. |
| 426 |
|
| 427 |
Arguments: |
| 428 |
|
| 429 |
* columns: An iterable of :class:`column` objects describing the shape |
| 430 |
of the generated DataFrame. |
| 431 |
|
| 432 |
* rows: A strategy for generating a row object. Should generate |
| 433 |
either dicts mapping column names to values or a sequence mapping |
| 434 |
column position to the value in that position (note that unlike the |
| 435 |
:class:`pandas.DataFrame` constructor, single values are not allowed |
| 436 |
here. Passing e.g. an integer is an error, even if there is only one |
| 437 |
column). |
| 438 |
|
| 439 |
At least one of rows and columns must be provided. If both are |
| 440 |
provided then the generated rows will be validated against the |
| 441 |
columns and an error will be raised if they don't match. |
| 442 |
|
| 443 |
Caveats on using rows: |
| 444 |
|
| 445 |
* In general you should prefer using columns to rows, and only use |
| 446 |
rows if the columns interface is insufficiently flexible to |
| 447 |
describe what you need - you will get better performance and |
| 448 |
example quality that way. |
| 449 |
* If you provide rows and not columns, then the shape and dtype of |
| 450 |
the resulting DataFrame may vary. e.g. if you have a mix of int |
| 451 |
and float in the values for one column in your row entries, the |
| 452 |
column will sometimes have an integral dtype and sometimes a float. |
| 453 |
|
| 454 |
* index: If not None, a strategy for generating indexes for the |
| 455 |
resulting DataFrame. This can generate either :class:`pandas.Index` |
| 456 |
objects or any sequence of values (which will be passed to the |
| 457 |
Index constructor). |
| 458 |
|
| 459 |
You will probably find it most convenient to use the |
| 460 |
:func:`~hypothesis.extra.pandas.indexes` or |
| 461 |
:func:`~hypothesis.extra.pandas.range_indexes` function to produce |
| 462 |
values for this argument. |
| 463 |
|
| 464 |
Usage: |
| 465 |
|
| 466 |
The expected usage pattern is that you use :class:`column` and |
| 467 |
:func:`columns` to specify a fixed shape of the DataFrame you want as |
| 468 |
follows. For example the following gives a two column data frame: |
| 469 |
|
| 470 |
.. code-block:: pycon |
| 471 |
|
| 472 |
>>> from hypothesis.extra.pandas import column, data_frames |
| 473 |
>>> data_frames([ |
| 474 |
... column('A', dtype=int), column('B', dtype=float)]).example() |
| 475 |
A B |
| 476 |
0 2021915903 1.793898e+232 |
| 477 |
1 1146643993 inf |
| 478 |
2 -2096165693 1.000000e+07 |
| 479 |
|
| 480 |
If you want the values in different columns to interact in some way you |
| 481 |
can use the rows argument. For example the following gives a two column |
| 482 |
DataFrame where the value in the first column is always at most the value |
| 483 |
in the second: |
| 484 |
|
| 485 |
.. code-block:: pycon |
| 486 |
|
| 487 |
>>> from hypothesis.extra.pandas import column, data_frames |
| 488 |
>>> import hypothesis.strategies as st |
| 489 |
>>> data_frames( |
| 490 |
... rows=st.tuples(st.floats(allow_nan=False), |
| 491 |
... st.floats(allow_nan=False)).map(sorted) |
| 492 |
... ).example() |
| 493 |
0 1 |
| 494 |
0 -3.402823e+38 9.007199e+15 |
| 495 |
1 -1.562796e-298 5.000000e-01 |
| 496 |
|
| 497 |
You can also combine the two: |
| 498 |
|
| 499 |
.. code-block:: pycon |
| 500 |
|
| 501 |
>>> from hypothesis.extra.pandas import columns, data_frames |
| 502 |
>>> import hypothesis.strategies as st |
| 503 |
>>> data_frames( |
| 504 |
... columns=columns(["lo", "hi"], dtype=float), |
| 505 |
... rows=st.tuples(st.floats(allow_nan=False), |
| 506 |
... st.floats(allow_nan=False)).map(sorted) |
| 507 |
... ).example() |
| 508 |
lo hi |
| 509 |
0 9.314723e-49 4.353037e+45 |
| 510 |
1 -9.999900e-01 1.000000e+07 |
| 511 |
2 -2.152861e+134 -1.069317e-73 |
| 512 |
|
| 513 |
(Note that the column dtype must still be specified and will not be |
| 514 |
inferred from the rows. This restriction may be lifted in future). |
| 515 |
|
| 516 |
Combining rows and columns has the following behaviour: |
| 517 |
|
| 518 |
* The column names and dtypes will be used. |
| 519 |
* If the column is required to be unique, this will be enforced. |
| 520 |
* Any values missing from the generated rows will be provided using the |
| 521 |
column's fill. |
| 522 |
* Any values in the row not present in the column specification (if |
| 523 |
dicts are passed, if there are keys with no corresponding column name, |
| 524 |
if sequences are passed if there are too many items) will result in |
| 525 |
InvalidArgument being raised. |
| 526 |
""" |
| 527 |
if index is None: |
| 528 |
index = range_indexes() |
| 529 |
else: |
| 530 |
check_strategy(index, "index") |
| 531 |
|
| 532 |
index_strategy = index |
| 533 |
|
| 534 |
if columns is None: |
| 535 |
if rows is None: |
| 536 |
raise InvalidArgument("At least one of rows and columns must be provided") |
| 537 |
else: |
| 538 |
|
| 539 |
@st.composite |
| 540 |
def rows_only(draw): |
| 541 |
index = draw(index_strategy) |
| 542 |
|
| 543 |
def row(): |
| 544 |
result = draw(rows) |
| 545 |
check_type(abc.Iterable, result, "draw(row)") |
| 546 |
return result |
| 547 |
|
| 548 |
if len(index) > 0: |
| 549 |
return pandas.DataFrame([row() for _ in index], index=index) |
| 550 |
else: |
| 551 |
# If we haven't drawn any rows we need to draw one row and |
| 552 |
# then discard it so that we get a consistent shape for the |
| 553 |
# DataFrame. |
| 554 |
base = pandas.DataFrame([row()]) |
| 555 |
return base.drop(0) |
| 556 |
|
| 557 |
return rows_only() |
| 558 |
|
| 559 |
assert columns is not None |
| 560 |
cols = try_convert(tuple, columns, "columns") |
| 561 |
|
| 562 |
rewritten_columns = [] |
| 563 |
column_names: set[str] = set() |
| 564 |
|
| 565 |
for i, c in enumerate(cols): |
| 566 |
check_type(column, c, f"columns[{i}]") |
| 567 |
|
| 568 |
c = copy(c) |
| 569 |
if c.name is None: |
| 570 |
label = f"columns[{i}]" |
| 571 |
c.name = i |
| 572 |
else: |
| 573 |
label = c.name |
| 574 |
try: |
| 575 |
hash(c.name) |
| 576 |
except TypeError: |
| 577 |
raise InvalidArgument( |
| 578 |
f"Column names must be hashable, but columns[{i}].name was " |
| 579 |
f"{c.name!r} of type {type(c.name).__name__}, which cannot be hashed." |
| 580 |
) from None |
| 581 |
|
| 582 |
if c.name in column_names: |
| 583 |
raise InvalidArgument(f"duplicate definition of column name {c.name!r}") |
| 584 |
|
| 585 |
column_names.add(c.name) |
| 586 |
c.elements, _ = elements_and_dtype(c.elements, c.dtype, label) |
| 587 |
|
| 588 |
if c.dtype is None and rows is not None: |
| 589 |
raise InvalidArgument( |
| 590 |
"Must specify a dtype for all columns when combining rows with columns." |
| 591 |
) |
| 592 |
|
| 593 |
c.fill = npst.fill_for( |
| 594 |
fill=c.fill, elements=c.elements, unique=c.unique, name=label |
| 595 |
) |
| 596 |
rewritten_columns.append(c) |
| 597 |
|
| 598 |
if rows is None: |
| 599 |
|
| 600 |
@st.composite |
| 601 |
def just_draw_columns(draw): |
| 602 |
index = draw(index_strategy) |
| 603 |
local_index_strategy = st.just(index) |
| 604 |
|
| 605 |
data = OrderedDict((c.name, None) for c in rewritten_columns) |
| 606 |
|
| 607 |
# Depending on how the columns are going to be generated we group |
| 608 |
# them differently to get better shrinking. For columns with fill |
| 609 |
# enabled, the elements can be shrunk independently of the size, |
| 610 |
# so we can just shrink by shrinking the index then shrinking the |
| 611 |
# length and are generally much more free to move data around. |
| 612 |
|
| 613 |
# For columns with no filling the problem is harder, and drawing |
| 614 |
# them like that would result in rows being very far apart from |
| 615 |
# each other in the choice sequence, which gets in the way |
| 616 |
# of shrinking. So what we do is reorder and draw those columns |
| 617 |
# row wise, so that the values of each row are next to each other. |
| 618 |
# This makes life easier for the shrinker when deleting choices. |
| 619 |
|
| 620 |
columns_without_fill = [c for c in rewritten_columns if c.fill.is_empty] |
| 621 |
if columns_without_fill: |
| 622 |
for c in columns_without_fill: |
| 623 |
data[c.name] = pandas.Series( |
| 624 |
np.zeros(shape=len(index), dtype=object), |
| 625 |
index=index, |
| 626 |
dtype=c.dtype, |
| 627 |
) |
| 628 |
seen = {c.name: set() for c in columns_without_fill if c.unique} |
| 629 |
|
| 630 |
for i in range(len(index)): |
| 631 |
for c in columns_without_fill: |
| 632 |
if c.unique: |
| 633 |
for _ in range(5): |
| 634 |
value = draw(c.elements) |
| 635 |
if value not in seen[c.name]: |
| 636 |
seen[c.name].add(value) |
| 637 |
break |
| 638 |
else: |
| 639 |
reject() |
| 640 |
else: |
| 641 |
value = draw(c.elements) |
| 642 |
|
| 643 |
try: |
| 644 |
data[c.name].iloc[i] = value |
| 645 |
except ValueError as err: # pragma: no cover |
| 646 |
# This just works in Pandas 1.4 and later, but gives |
| 647 |
# a confusing error on previous versions. |
| 648 |
if c.dtype is None and not isinstance( |
| 649 |
value, (float, int, str, bool, datetime, timedelta) |
| 650 |
): |
| 651 |
raise ValueError( |
| 652 |
f"Failed to add {value=} to column " |
| 653 |
f"{c.name} with dtype=None. Maybe passing " |
| 654 |
"dtype=object would help?" |
| 655 |
) from err |
| 656 |
# Unclear how this could happen, but users find a way... |
| 657 |
raise |
| 658 |
|
| 659 |
for c in rewritten_columns: |
| 660 |
if not c.fill.is_empty: |
| 661 |
data[c.name] = draw( |
| 662 |
series( |
| 663 |
index=local_index_strategy, |
| 664 |
dtype=c.dtype, |
| 665 |
elements=c.elements, |
| 666 |
fill=c.fill, |
| 667 |
unique=c.unique, |
| 668 |
) |
| 669 |
) |
| 670 |
|
| 671 |
return pandas.DataFrame(data, index=index) |
| 672 |
|
| 673 |
return just_draw_columns() |
| 674 |
else: |
| 675 |
|
| 676 |
@st.composite |
| 677 |
def assign_rows(draw): |
| 678 |
index = draw(index_strategy) |
| 679 |
|
| 680 |
result = pandas.DataFrame( |
| 681 |
OrderedDict( |
| 682 |
( |
| 683 |
c.name, |
| 684 |
pandas.Series( |
| 685 |
np.zeros(dtype=c.dtype, shape=len(index)), dtype=c.dtype |
| 686 |
), |
| 687 |
) |
| 688 |
for c in rewritten_columns |
| 689 |
), |
| 690 |
index=index, |
| 691 |
) |
| 692 |
|
| 693 |
fills = {} |
| 694 |
|
| 695 |
any_unique = any(c.unique for c in rewritten_columns) |
| 696 |
|
| 697 |
if any_unique: |
| 698 |
all_seen = [set() if c.unique else None for c in rewritten_columns] |
| 699 |
while all_seen[-1] is None: |
| 700 |
all_seen.pop() |
| 701 |
|
| 702 |
for row_index in range(len(index)): |
| 703 |
for _ in range(5): |
| 704 |
original_row = draw(rows) |
| 705 |
row = original_row |
| 706 |
if isinstance(row, dict): |
| 707 |
as_list = [None] * len(rewritten_columns) |
| 708 |
for i, c in enumerate(rewritten_columns): |
| 709 |
try: |
| 710 |
as_list[i] = row[c.name] |
| 711 |
except KeyError: |
| 712 |
try: |
| 713 |
as_list[i] = fills[i] |
| 714 |
except KeyError: |
| 715 |
if c.fill.is_empty: |
| 716 |
raise InvalidArgument( |
| 717 |
f"Empty fill strategy in {c!r} cannot " |
| 718 |
f"complete row {original_row!r}" |
| 719 |
) from None |
| 720 |
fills[i] = draw(c.fill) |
| 721 |
as_list[i] = fills[i] |
| 722 |
for k in row: |
| 723 |
if k not in column_names: |
| 724 |
raise InvalidArgument( |
| 725 |
f"Row {row!r} contains column {k!r} not in " |
| 726 |
f"columns {[c.name for c in rewritten_columns]!r})" |
| 727 |
) |
| 728 |
row = as_list |
| 729 |
if any_unique: |
| 730 |
has_duplicate = False |
| 731 |
for seen, value in zip(all_seen, row, strict=False): |
| 732 |
if seen is None: |
| 733 |
continue |
| 734 |
if value in seen: |
| 735 |
has_duplicate = True |
| 736 |
break |
| 737 |
seen.add(value) |
| 738 |
if has_duplicate: |
| 739 |
continue |
| 740 |
row = list(try_convert(tuple, row, "draw(rows)")) |
| 741 |
|
| 742 |
if len(row) > len(rewritten_columns): |
| 743 |
raise InvalidArgument( |
| 744 |
f"Row {original_row!r} contains too many entries. Has " |
| 745 |
f"{len(row)} but expected at most {len(rewritten_columns)}" |
| 746 |
) |
| 747 |
while len(row) < len(rewritten_columns): |
| 748 |
c = rewritten_columns[len(row)] |
| 749 |
if c.fill.is_empty: |
| 750 |
raise InvalidArgument( |
| 751 |
f"Empty fill strategy in {c!r} cannot " |
| 752 |
f"complete row {original_row!r}" |
| 753 |
) |
| 754 |
row.append(draw(c.fill)) |
| 755 |
result.iloc[row_index] = row |
| 756 |
break |
| 757 |
else: |
| 758 |
reject() |
| 759 |
return result |
| 760 |
|
| 761 |
return assign_rows() |