Debian Codegraph @

hypothesis-python/tests/array_api/common.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 from importlib.metadata import EntryPoint, entry_points # type: ignore
12 from typing import Literal
13
14 import pytest
15
16 from hypothesis.extra.array_api import (
17 COMPLEX_NAMES,
18 REAL_NAMES,
19 RELEASED_VERSIONS,
20 NominalVersion,
21 )
22 from hypothesis.internal.floats import next_up
23
24 __all__ = [
25 "MIN_VER_FOR_COMPLEX",
26 "dtype_name_params",
27 "flushes_to_zero",
28 "installed_array_modules",
29 ]
30
31
32 MIN_VER_FOR_COMPLEX: NominalVersion = "2022.12"
33 if len(RELEASED_VERSIONS) > 1:
34 assert MIN_VER_FOR_COMPLEX == RELEASED_VERSIONS[1]
35
36
37 def installed_array_modules() -> dict[str, EntryPoint]:
38 """Returns a dictionary of array module names paired to their entry points
39
40 A convenience wrapper for importlib.metadata.entry_points(). It has the
41 added benefit of working with both the original dict interface and the new
42 select interface, so this can be used warning-free in all modern Python
43 versions.
44 """
45 return {ep.name: ep for ep in entry_points(group="array_api")}
46
47
48 def flushes_to_zero(xp, width: Literal[32, 64]) -> bool:
49 """Infer whether build of array module has its float dtype of the specified
50 width flush subnormals to zero
51
52 We do this per-width because compilers might FTZ for one dtype but allow
53 subnormals in the other.
54 """
55 if width not in [32, 64]:
56 raise ValueError(f"{width=}, but should be either 32 or 64")
57 dtype = getattr(xp, f"float{width}")
58 return bool(xp.asarray(next_up(0.0, width=width), dtype=dtype) == 0)
59
60
61 dtype_name_params = ["bool", *REAL_NAMES]
62 for name in COMPLEX_NAMES:
63 param = pytest.param(name, marks=pytest.mark.xp_min_version(MIN_VER_FOR_COMPLEX))
64 dtype_name_params.append(param)