Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
b2f6155872 |
|||
|
c7f076c35c |
|||
|
6ddb545491 |
|||
|
81912f1a81 |
|||
|
25c718fe6a |
|||
|
f952d95951 |
|||
|
849b786e13 |
|||
|
6bd21ce134 |
|||
|
7e3e67c300 |
|||
|
de740ebb5f |
|||
|
04addacb09 |
|||
|
153094eef5 |
|||
|
cbc1f8fd3a |
|||
|
febed693b8 |
|||
|
08067b3d6e |
|||
|
3d9f990c68 |
|||
|
4c0c7887e5 |
|||
|
06d003b615 |
|||
|
348cd53767 |
|||
|
917c217ca0 |
|||
|
65de932f8d |
|||
|
4c47ca1b17 |
|||
|
ea85c73933 |
|||
|
51c73163e4 |
|||
|
62b25f66d9 |
|||
|
3cfc0db136 |
|||
|
3cecf0d989 |
|||
|
d405c22c90 |
|||
|
d9dcea8379 |
|||
|
9083cebe18 |
|||
|
d507e1f56d |
|||
|
5d2f430893 |
37 changed files with 3422 additions and 412 deletions
2
.github/workflows/audit.yml
vendored
2
.github/workflows/audit.yml
vendored
|
|
@ -8,7 +8,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.12
|
||||
python-version: 3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
2
.github/workflows/docs.yml
vendored
2
.github/workflows/docs.yml
vendored
|
|
@ -8,7 +8,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.12
|
||||
python-version: 3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
2
.github/workflows/lint.yml
vendored
2
.github/workflows/lint.yml
vendored
|
|
@ -8,7 +8,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.12
|
||||
python-version: 3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
1
.github/workflows/release.yml
vendored
1
.github/workflows/release.yml
vendored
|
|
@ -16,6 +16,7 @@ jobs:
|
|||
3.10
|
||||
3.11
|
||||
3.12
|
||||
3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
1
.github/workflows/test_coverage.yml
vendored
1
.github/workflows/test_coverage.yml
vendored
|
|
@ -14,6 +14,7 @@ jobs:
|
|||
3.10
|
||||
3.11
|
||||
3.12
|
||||
3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
2
.github/workflows/test_docstrings.yml
vendored
2
.github/workflows/test_docstrings.yml
vendored
|
|
@ -8,7 +8,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.12
|
||||
python-version: 3.13
|
||||
architecture: x64
|
||||
|
||||
- run: python --version
|
||||
|
|
|
|||
2
.github/workflows/tests.yml
vendored
2
.github/workflows/tests.yml
vendored
|
|
@ -5,7 +5,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.9", "3.10", "3.11", "3.12"]
|
||||
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
|
||||
name: test-${{ matrix.python-version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ version: 2
|
|||
build:
|
||||
os: ubuntu-24.04
|
||||
tools:
|
||||
python: "3.12"
|
||||
python: "3.13"
|
||||
|
||||
sphinx:
|
||||
configuration: docs/conf.py
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ To execute all default tasks, simply invoke:
|
|||
`nox`
|
||||
|
||||
This includes running the test suite for the project's main Python version
|
||||
(i.e., [3.12](https://devguide.python.org/versions/)).
|
||||
(i.e., [3.13](https://devguide.python.org/versions/)).
|
||||
|
||||
|
||||
#### Code Formatting & Linting
|
||||
|
|
|
|||
38
noxfile.py
38
noxfile.py
|
|
@ -57,7 +57,7 @@ def load_supported_python_versions(*, reverse: bool = False) -> list[str]:
|
|||
|
||||
|
||||
SUPPORTED_PYTHONS = load_supported_python_versions(reverse=True)
|
||||
MAIN_PYTHON = "3.12"
|
||||
MAIN_PYTHON = "3.13"
|
||||
|
||||
DOCS_SRC, DOCS_BUILD = ("docs/", ".cache/docs/")
|
||||
TESTS_LOCATION = "tests/"
|
||||
|
|
@ -205,8 +205,10 @@ def lint(session: nox.Session) -> None:
|
|||
"flake8-isort",
|
||||
"flake8-quotes",
|
||||
"flake8-string-format",
|
||||
"flake8-todos",
|
||||
"flake8-pyproject",
|
||||
"flake8-pytest-style",
|
||||
"flake8-unused-arguments",
|
||||
"mypy",
|
||||
"pep8-naming", # flake8 plug-in
|
||||
"pydoclint[flake8]",
|
||||
|
|
@ -229,10 +231,15 @@ TEST_DEPENDENCIES = (
|
|||
"packaging",
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"pytest-randomly",
|
||||
"pytest-repeat",
|
||||
"semver",
|
||||
'typing-extensions; python_version < "3.11"', # to support Python 3.9 & 3.10
|
||||
"xdoctest",
|
||||
)
|
||||
|
||||
TEST_RANDOM_SEED = "--randomly-seed=42"
|
||||
|
||||
|
||||
@nox.session(python=SUPPORTED_PYTHONS)
|
||||
def test(session: nox.Session) -> None:
|
||||
|
|
@ -248,6 +255,15 @@ def test(session: nox.Session) -> None:
|
|||
args = posargs or (
|
||||
"--cov",
|
||||
"--no-cov-on-fail",
|
||||
*( # If this function is run via the "test-fast" session,
|
||||
( # the following arguments are added:
|
||||
"--cov-fail-under=100",
|
||||
"--smoke-tests-only",
|
||||
)
|
||||
if session.env.get("_smoke_tests_only")
|
||||
else ()
|
||||
),
|
||||
TEST_RANDOM_SEED,
|
||||
TESTS_LOCATION,
|
||||
)
|
||||
|
||||
|
|
@ -284,6 +300,8 @@ def test_coverage_run(session: nox.Session) -> None:
|
|||
session.install(".")
|
||||
install_pinned(session, "coverage", *TEST_DEPENDENCIES)
|
||||
|
||||
session.env["N_RANDOM_DRAWS"] = "10"
|
||||
session.env["NO_CROSS_REFERENCE"] = "true"
|
||||
session.run(
|
||||
"python",
|
||||
"-m",
|
||||
|
|
@ -291,6 +309,7 @@ def test_coverage_run(session: nox.Session) -> None:
|
|||
"run",
|
||||
"-m",
|
||||
"pytest",
|
||||
TEST_RANDOM_SEED,
|
||||
TESTS_LOCATION,
|
||||
)
|
||||
|
||||
|
|
@ -329,6 +348,18 @@ def test_docstrings(session: nox.Session) -> None:
|
|||
session.run("xdoctest", "src/lalib")
|
||||
|
||||
|
||||
@nox.session(name="test-fast", python=MAIN_PYTHON)
|
||||
def test_fast(session: nox.Session) -> None:
|
||||
"""Test code with `pytest`, selected (smoke) tests only.
|
||||
|
||||
The (unit) test cases are selected such that their number
|
||||
is minimal but the achieved coverage remains at 100%.
|
||||
"""
|
||||
# See implementation notes in `pre_commit_test_hook()` below
|
||||
session.env["_smoke_tests_only"] = "true"
|
||||
test(session)
|
||||
|
||||
|
||||
@nox.session(name="clean-cwd", python=MAIN_PYTHON, venv_backend="none")
|
||||
def clean_cwd(session: nox.Session) -> None:
|
||||
"""Remove (almost) all glob patterns listed in git's ignore file.
|
||||
|
|
@ -430,6 +461,11 @@ def start(session: nox.Session) -> None:
|
|||
session.env["PIP_CACHE_DIR"] = ".cache/pip"
|
||||
session.env["PIP_DISABLE_PIP_VERSION_CHECK"] = "true"
|
||||
|
||||
if session.python in ("3.13", "3.12", "3.11"):
|
||||
session.env["PRAGMA_SUPPORT_39_N_310"] = "to support Python 3.9 & 3.10"
|
||||
else:
|
||||
session.env["PRAGMA_SUPPORT_39_N_310"] = f"{_magic_number =}"
|
||||
|
||||
|
||||
def suppress_poetry_export_warning(session: nox.Session) -> None:
|
||||
"""Temporary fix to avoid poetry's warning ...
|
||||
|
|
|
|||
802
poetry.lock
generated
802
poetry.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,7 +1,7 @@
|
|||
[tool.poetry]
|
||||
|
||||
name = "lalib"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0.dev0"
|
||||
|
||||
authors = [
|
||||
"Alexander Hess <alexander@webartifex.biz>",
|
||||
|
|
@ -16,6 +16,7 @@ classifiers = [
|
|||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
]
|
||||
description = "A Python library to study linear algebra"
|
||||
license = "MIT"
|
||||
|
|
@ -30,6 +31,8 @@ repository = "https://github.com/webartifex/lalib"
|
|||
|
||||
python = "^3.9"
|
||||
|
||||
typing-extensions = [ { python = "<3.11", version = "^4.12" } ] # to support Python 3.9 & 3.10
|
||||
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
|
||||
|
|
@ -55,8 +58,10 @@ flake8-eradicate = "^1.5"
|
|||
flake8-isort = "^6.1"
|
||||
flake8-quotes = "^3.4"
|
||||
flake8-string-format = "^0.3"
|
||||
flake8-todos = "^0.3"
|
||||
flake8-pyproject = "^1.2"
|
||||
flake8-pytest-style = "^2.0"
|
||||
flake8-unused-arguments = "^0.0"
|
||||
mypy = "^1.11"
|
||||
pep8-naming = "^0.14" # flake8 plug-in
|
||||
pydoclint = { extras = ["flake8"], version = "^0.5" }
|
||||
|
|
@ -74,10 +79,13 @@ coverage = "^7.6"
|
|||
packaging = "^24.1" # to test the version identifier
|
||||
pytest = "^8.3"
|
||||
pytest-cov = "^5.0"
|
||||
pytest-randomly = "^3.15"
|
||||
pytest-repeat = "^0.9"
|
||||
semver = "^3.0" # to test the version identifier
|
||||
tomli = [ { python = "<3.11", version = "^2.0" } ]
|
||||
xdoctest = { extras = ["colors"], version = "^1.2" }
|
||||
|
||||
|
||||
[tool.poetry.urls]
|
||||
|
||||
"Issues Tracker" = "https://github.com/webartifex/lalib/issues"
|
||||
|
|
@ -121,6 +129,16 @@ show_missing = true
|
|||
skip_covered = true
|
||||
skip_empty = true
|
||||
|
||||
exclude_lines = [
|
||||
|
||||
# "pragma: no cover"
|
||||
# => Intentionally commented out as we thrive for 100% test coverage
|
||||
|
||||
# PyPI's "typing-extensions" are needed to make `mypy` work
|
||||
"pragma: no cover ${PRAGMA_SUPPORT_39_N_310}",
|
||||
|
||||
]
|
||||
|
||||
|
||||
[tool.coverage.run]
|
||||
|
||||
|
|
@ -158,7 +176,9 @@ select = [
|
|||
"PT", # flake8-pytest-style => enforce a consistent style with pytest
|
||||
"Q", # flake8-quotes => use double quotes everywhere (complying with black)
|
||||
"S", # flake8-bandit => common security issues
|
||||
"T00", # flake8-todos => unify TODOs
|
||||
"T10", # flake8-debugger => no debugger usage
|
||||
"U100", # flake8-unused-arguments => declared function arguments must be used
|
||||
|
||||
# violations not covered by `ruff` below
|
||||
|
||||
|
|
@ -177,6 +197,8 @@ extend-ignore = [ # never check the following codes
|
|||
|
||||
"ANN401", # allow dynamically typed expressions with `typing.Any`
|
||||
|
||||
"DOC301", # PEP257 => class constructor's docstring go in `.__init__()`
|
||||
|
||||
# Comply with black's style
|
||||
# Sources: https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#pycodestyle
|
||||
"E203", "E701", "E704", "W503",
|
||||
|
|
@ -235,6 +257,12 @@ docstring-quotes = "double"
|
|||
inline-quotes = "double"
|
||||
multiline-quotes = "double"
|
||||
|
||||
# Plug-in: flake8-unused-arguments
|
||||
# Source: https://github.com/nhoad/flake8-unused-arguments
|
||||
# Make flake8-unused-arguments behave like ruff's "ARG" error code
|
||||
unused-arguments-ignore-abstract-functions = true
|
||||
unused-arguments-ignore-stub-functions = true
|
||||
|
||||
|
||||
|
||||
[tool.isort] # aligned with [tool.ruff.lint.isort] below
|
||||
|
|
@ -327,6 +355,7 @@ select = [
|
|||
# violations also covered by `flake8` above
|
||||
|
||||
"ANN", # flake8-annotations => enforce type checking for functions
|
||||
"ARG", # flake8-unused-arguments => declared function arguments must be used
|
||||
"B", # flake8-bugbear => bugs and design flaws
|
||||
"C4", # flake8-comprehensions => better comprehensions
|
||||
"C90", # mccabe => cyclomatic complexity
|
||||
|
|
@ -340,6 +369,7 @@ select = [
|
|||
"PT", # flake8-pytest-style => enforce a consistent style with pytest
|
||||
"Q", # flake8-quotes => use double quotes everywhere
|
||||
"S", # flake8-bandit => common security issues
|
||||
"TD", # flake8-todos => unify TODOs
|
||||
"T10", # flake8-debugger => no debugger usage
|
||||
|
||||
# violations not covered by `flake8` above
|
||||
|
|
@ -362,6 +392,8 @@ extend-ignore = [ # never check the following codes
|
|||
|
||||
]
|
||||
|
||||
allowed-confusables = ["ℂ", "ℝ", "ℚ"]
|
||||
|
||||
|
||||
[tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above
|
||||
|
||||
|
|
|
|||
|
|
@ -4,10 +4,27 @@ First, verify that your installation of `lalib` works:
|
|||
>>> import lalib
|
||||
>>> lalib.__version__ != '0.0.0'
|
||||
True
|
||||
|
||||
`lalib` exposes its very own "words" (i.e., its public API) at the root
|
||||
of the package. They can be imported all at once with:
|
||||
|
||||
>>> from lalib import *
|
||||
|
||||
In addition to Python's built-in numbers, `lalib` comes with a couple of
|
||||
specific numeric data types, for example, `one` and `zero` representing
|
||||
the two elements of the Galois field `GF2`:
|
||||
|
||||
>>> one + one
|
||||
zero
|
||||
>>> one + zero
|
||||
one
|
||||
"""
|
||||
|
||||
from importlib import metadata
|
||||
|
||||
from lalib import elements
|
||||
from lalib import fields
|
||||
|
||||
|
||||
try:
|
||||
pkg_info = metadata.metadata(__name__)
|
||||
|
|
@ -24,4 +41,22 @@ else:
|
|||
del pkg_info
|
||||
|
||||
|
||||
gf2, one, zero = elements.gf2, elements.one, elements.zero
|
||||
|
||||
Q, R, C, GF2 = fields.Q, fields.R, fields.C, fields.GF2
|
||||
|
||||
|
||||
del elements
|
||||
del fields
|
||||
del metadata
|
||||
|
||||
|
||||
__all__ = (
|
||||
"gf2",
|
||||
"one",
|
||||
"zero",
|
||||
"Q",
|
||||
"R",
|
||||
"C",
|
||||
"GF2",
|
||||
)
|
||||
|
|
|
|||
13
src/lalib/config.py
Normal file
13
src/lalib/config.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
"""Library-wide default settings."""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
NDIGITS = 12
|
||||
|
||||
THRESHOLD = 1 / (10**NDIGITS)
|
||||
|
||||
MAX_DENOMINATOR = math.trunc(1 / THRESHOLD)
|
||||
|
||||
|
||||
del math
|
||||
34
src/lalib/elements/__init__.py
Normal file
34
src/lalib/elements/__init__.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"""Various elements of various fields.
|
||||
|
||||
Import the objects like so:
|
||||
|
||||
>>> from lalib.elements import *
|
||||
|
||||
Then, use them:
|
||||
|
||||
>>> one + zero
|
||||
one
|
||||
|
||||
>>> gf2(0)
|
||||
zero
|
||||
>>> gf2(42)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: ...
|
||||
>>> gf2(42, strict=False)
|
||||
one
|
||||
"""
|
||||
|
||||
from lalib.elements import galois
|
||||
|
||||
|
||||
gf2, one, zero = galois.gf2, galois.one, galois.zero
|
||||
|
||||
del galois
|
||||
|
||||
|
||||
__all__ = (
|
||||
"gf2",
|
||||
"one",
|
||||
"zero",
|
||||
)
|
||||
560
src/lalib/elements/galois.py
Normal file
560
src/lalib/elements/galois.py
Normal file
|
|
@ -0,0 +1,560 @@
|
|||
"""A Galois field implementation with two elements.
|
||||
|
||||
This module defines two singleton objects, `one` and `zero`,
|
||||
that follow the rules of a Galois field of two elements,
|
||||
also called `GF2` in `lalib`:
|
||||
|
||||
>>> one + one
|
||||
zero
|
||||
>>> zero + one
|
||||
one
|
||||
>>> one * one
|
||||
one
|
||||
>>> one * zero
|
||||
zero
|
||||
|
||||
They mix with numbers that compare equal to either `1` or `0`,
|
||||
for example:
|
||||
|
||||
>>> one + 1
|
||||
zero
|
||||
>>> 0 * zero
|
||||
zero
|
||||
|
||||
Further usage explanations of `one` and `zero`
|
||||
can be found in the various docstrings of the `GF2Element` class.
|
||||
|
||||
This class is also referred to as just "the `gf2` type" outside
|
||||
this module.
|
||||
"""
|
||||
|
||||
import abc
|
||||
import functools
|
||||
import math
|
||||
import numbers
|
||||
from typing import Callable, ClassVar, Literal
|
||||
|
||||
|
||||
try:
|
||||
from typing import Self
|
||||
except ImportError: # pragma: no cover to support Python 3.9 & 3.10
|
||||
from typing_extensions import Self
|
||||
|
||||
|
||||
from lalib import config
|
||||
|
||||
|
||||
def _to_gf2(
|
||||
value: complex, # `mypy` reads `complex | float | int`
|
||||
/,
|
||||
*,
|
||||
strict: bool = True,
|
||||
threshold: float = config.THRESHOLD,
|
||||
) -> int:
|
||||
"""Cast a number as a possible Galois field value: `1` or `0`.
|
||||
|
||||
By default, the `value` is parsed in a `strict` mode where
|
||||
`value`s equal to `1` or `0` within the specified `threshold`
|
||||
return either `1` or `0` exactly.
|
||||
|
||||
Args:
|
||||
value: to be cast; must behave like a number;
|
||||
for `complex` numbers their `.real` part is used
|
||||
strict: if `True`, only accept `value`s equal to
|
||||
`1` or `0` within the `threshold` as `1` or `0`;
|
||||
otherwise, cast any number different from `0` as `1`
|
||||
threshold: used for the equality checks to find
|
||||
`1`-like and `0`-like `value`s
|
||||
|
||||
Returns:
|
||||
either `1` or `0`
|
||||
|
||||
Raises:
|
||||
TypeError: `value` does not behave like a number
|
||||
ValueError: `value != 1` or `value != 0` in `strict` mode
|
||||
"""
|
||||
try:
|
||||
value = complex(value)
|
||||
except (TypeError, ValueError):
|
||||
msg = "`value` must be a number"
|
||||
raise TypeError(msg) from None
|
||||
|
||||
if not (abs(value.imag) < threshold):
|
||||
msg = "`value` must be either `1`-like or `0`-like"
|
||||
raise ValueError(msg)
|
||||
|
||||
value = value.real
|
||||
|
||||
if math.isnan(value):
|
||||
msg = "`value` must be either `1`-like or `0`-like"
|
||||
raise ValueError(msg)
|
||||
|
||||
if strict:
|
||||
if abs(value - 1) < threshold:
|
||||
return 1
|
||||
if abs(value) < threshold:
|
||||
return 0
|
||||
|
||||
msg = "`value` must be either `1`-like or `0`-like"
|
||||
raise ValueError(msg)
|
||||
|
||||
if abs(value) < threshold:
|
||||
return 0
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
class GF2Meta(abc.ABCMeta):
|
||||
"""Make data type of `one` and `zero` appear to be `gf2`."""
|
||||
|
||||
def __repr__(cls) -> str: # noqa: RUF100,U100
|
||||
"""Text representation for `GF2Element` and sub-classes."""
|
||||
return "gf2"
|
||||
|
||||
|
||||
@functools.total_ordering
|
||||
class GF2Element(metaclass=GF2Meta):
|
||||
"""A Galois field value: either `one` or `zero`.
|
||||
|
||||
Implements the singleton design pattern such that
|
||||
only one instance per field value exists in the
|
||||
computer's memory, i.e., there is only one `one`
|
||||
and one `zero` object at all times.
|
||||
"""
|
||||
|
||||
_instances: ClassVar = {}
|
||||
_value: int
|
||||
|
||||
@staticmethod
|
||||
def __new__(
|
||||
cls: type[Self],
|
||||
value: object = None,
|
||||
*,
|
||||
strict: bool = True,
|
||||
threshold: float = config.THRESHOLD,
|
||||
) -> Self:
|
||||
"""See docstring for `.__init__()`."""
|
||||
if isinstance(value, cls):
|
||||
return value
|
||||
|
||||
if value is None:
|
||||
try:
|
||||
value = cls._value
|
||||
except AttributeError:
|
||||
try:
|
||||
return cls._instances[0]
|
||||
except KeyError:
|
||||
msg = "Must create `one` and `zero` first (internal error)"
|
||||
raise RuntimeError(msg) from None
|
||||
else:
|
||||
value = _to_gf2(value, strict=strict, threshold=threshold) # type: ignore[arg-type]
|
||||
|
||||
try:
|
||||
return cls._instances[value]
|
||||
except KeyError:
|
||||
obj = super().__new__(cls)
|
||||
cls._instances[int(obj)] = obj
|
||||
return obj
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
value: object = None,
|
||||
/,
|
||||
*,
|
||||
strict: bool = True,
|
||||
threshold: float = config.THRESHOLD,
|
||||
) -> None:
|
||||
"""Obtain one of two objects: `one` or `zero`.
|
||||
|
||||
Args:
|
||||
value: to be cast; must behave like a number;
|
||||
for `complex` numbers their `.real` part is used
|
||||
strict: if `True`, only accept `value`s equal to
|
||||
`1` or `0` within the `threshold` as `one` or `zero`;
|
||||
otherwise, cast any number different from `0` as `one`
|
||||
threshold: used for the equality checks to find
|
||||
`1`-like and `0`-like `value`s
|
||||
|
||||
Returns:
|
||||
either `one` or `zero`
|
||||
|
||||
Raises:
|
||||
TypeError: `value` does not behave like a number
|
||||
ValueError: `value != 1` or `value != 0` in `strict` mode
|
||||
"""
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Text representation: `repr(one)` and `repr(zero)`.
|
||||
|
||||
`eval(repr(self)) == self` must be `True`; in other words,
|
||||
the text representation of an object must be valid code on its
|
||||
own and evaluate into a (new) object with the same value.
|
||||
|
||||
See: https://docs.python.org/3/reference/datamodel.html#object.__repr__
|
||||
"""
|
||||
return "one" if self._value else "zero"
|
||||
|
||||
__str__ = __repr__
|
||||
|
||||
def __complex__(self) -> complex:
|
||||
"""Cast `self` as a `complex` number: `complex(self)`."""
|
||||
return complex(self._value, 0)
|
||||
|
||||
def __float__(self) -> float:
|
||||
"""Cast `self` as a `float`ing-point number: `float(self)`."""
|
||||
return float(self._value)
|
||||
|
||||
def __int__(self) -> int:
|
||||
"""Cast `self` as a `int`: `int(self)`."""
|
||||
return int(self._value)
|
||||
|
||||
__hash__ = __int__
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
"""Cast `self` as a `bool`ean: `bool(self)`.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> bool(zero)
|
||||
False
|
||||
>>> if zero + one:
|
||||
... result = one
|
||||
... else:
|
||||
... result = zero
|
||||
>>> result
|
||||
one
|
||||
"""
|
||||
return bool(self._value)
|
||||
|
||||
def __abs__(self) -> Self:
|
||||
"""Take the absolute value of `self`: `abs(self)`."""
|
||||
return self
|
||||
|
||||
def __trunc__(self) -> int:
|
||||
"""Truncate `self` to the next `int`: `math.trunc(self)`."""
|
||||
return int(self)
|
||||
|
||||
def __floor__(self) -> int:
|
||||
"""Round `self` down to the next `int`: `math.floor(self)`."""
|
||||
return int(self)
|
||||
|
||||
def __ceil__(self) -> int:
|
||||
"""Round `self` up to the next `int`: `math.ceil(self)`."""
|
||||
return int(self)
|
||||
|
||||
def __round__(self, _ndigits: int = config.NDIGITS) -> int:
|
||||
"""Round `self` to the next `int`: `round(self)`."""
|
||||
return int(self)
|
||||
|
||||
@property
|
||||
def real(self) -> int:
|
||||
"""The `.real` part of a `complex` number.
|
||||
|
||||
For a non-`complex` number this is the number itself.
|
||||
"""
|
||||
# Return an `int` to align with `.imag` above
|
||||
return int(self._value)
|
||||
|
||||
@property
|
||||
def imag(self) -> Literal[0]:
|
||||
"""The `.imag`inary part of a `complex` number.
|
||||
|
||||
For a non-`complex` number this is always `0`.
|
||||
"""
|
||||
# `numbers.Real` returns an `int` here
|
||||
# whereas `numbers.Complex` returns a `float`
|
||||
# => must return an `int` to make `mypy` happy
|
||||
return 0
|
||||
|
||||
def conjugate(self) -> Self:
|
||||
"""The conjugate of a `complex` number.
|
||||
|
||||
For a non-`complex` number this is the number itself.
|
||||
"""
|
||||
return self
|
||||
|
||||
@property
|
||||
def numerator(self) -> int:
|
||||
"""Smallest numerator when expressed as a `Rational` number.
|
||||
|
||||
Either `1` or `0`.
|
||||
|
||||
Reasoning:
|
||||
- `int(one) == 1` => `gf2(1 / 1) == one`
|
||||
- `int(zero) == 0` => `gf2(0 / 1) == zero`
|
||||
|
||||
See also docstring for `.denominator`.
|
||||
"""
|
||||
return int(self)
|
||||
|
||||
@property
|
||||
def denominator(self) -> Literal[1]:
|
||||
"""Smallest denominator when expressed as a `Rational` number.
|
||||
|
||||
Always `1` for `gf2` values.
|
||||
|
||||
See also docstring for `.numerator`.
|
||||
"""
|
||||
return 1
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
"""Comparison: `self == other`.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> zero == one
|
||||
False
|
||||
>>> one == one
|
||||
True
|
||||
>>> one != zero
|
||||
True
|
||||
>>> one == 1
|
||||
True
|
||||
"""
|
||||
try:
|
||||
other = GF2Element(other)
|
||||
except (TypeError, ValueError):
|
||||
return NotImplemented
|
||||
else:
|
||||
# TODO(webartifex): investigate the below issue
|
||||
# https://github.com/webartifex/lalib/issues/1
|
||||
# `one` and `zero` are singletons
|
||||
# => yet, the following does not work with `pytest`
|
||||
# in Python 3.9 & 3.10: `return self is other`
|
||||
# => for now, use the following fix:
|
||||
return int(self) == int(other)
|
||||
|
||||
def __lt__(self, other: object) -> bool:
|
||||
"""Comparison: `self < other`.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> zero < one
|
||||
True
|
||||
>>> one < one
|
||||
False
|
||||
>>> 0 < one
|
||||
True
|
||||
"""
|
||||
try:
|
||||
other = GF2Element(other)
|
||||
except TypeError:
|
||||
return NotImplemented
|
||||
except ValueError:
|
||||
msg = "`other` must be either `1`-like or `0`-like"
|
||||
raise ValueError(msg) from None
|
||||
else:
|
||||
return int(self) < int(other)
|
||||
|
||||
def __le__(self, other: object) -> bool:
|
||||
"""Comparison: `self <= other`.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> zero <= one
|
||||
True
|
||||
>>> zero <= zero
|
||||
True
|
||||
>>> one <= zero
|
||||
False
|
||||
>>> zero <= 1
|
||||
True
|
||||
"""
|
||||
# The `numbers.Rational` abstract base class requires both
|
||||
# `.__lt__()` and `.__le__()` to be present alongside
|
||||
# `.__eq__()` => `@functools.total_ordering` is not enough
|
||||
return self == other or self < other
|
||||
|
||||
def _compute(self, other: object, func: Callable) -> Self:
|
||||
"""Run arithmetic operations using `int`s.
|
||||
|
||||
The `gf2` atithmetic operations can transparently be conducted
|
||||
by converting `self` and `other` into `int`s first, and
|
||||
then "do the math".
|
||||
|
||||
Besides the generic arithmetic, this method also handles the
|
||||
casting of non-`gf2` values and various errors occuring
|
||||
along the way.
|
||||
"""
|
||||
try:
|
||||
other = GF2Element(other)
|
||||
except TypeError:
|
||||
return NotImplemented
|
||||
except ValueError:
|
||||
msg = "`other` must be a `1`-like or `0`-like value"
|
||||
raise ValueError(msg) from None
|
||||
else:
|
||||
try:
|
||||
return self.__class__(func(int(self), int(other)))
|
||||
except ZeroDivisionError:
|
||||
msg = "division by `0`-like value"
|
||||
raise ZeroDivisionError(msg) from None
|
||||
|
||||
def __pos__(self) -> Self:
|
||||
"""Make `self` positive: `+self`."""
|
||||
return self
|
||||
|
||||
def __neg__(self) -> Self:
|
||||
"""Make `self` negative: `-self`."""
|
||||
return self
|
||||
|
||||
def __add__(self, other: object) -> Self:
|
||||
"""Addition / Subtraction: `self + other` / `self - other`.
|
||||
|
||||
For `gf2`, addition and subtraction are identical. Besides
|
||||
`one + one` which cannot result in a "two", all operations
|
||||
behave as one would expect from `int`s.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> one + one
|
||||
zero
|
||||
>>> one + zero
|
||||
one
|
||||
>>> zero - one
|
||||
one
|
||||
>>> zero + 0
|
||||
zero
|
||||
>>> 1 + one
|
||||
zero
|
||||
"""
|
||||
return self._compute(other, lambda s, o: (s + o) % 2)
|
||||
|
||||
__radd__ = __add__
|
||||
__sub__ = __add__
|
||||
__rsub__ = __add__
|
||||
|
||||
def __mul__(self, other: object) -> Self:
|
||||
"""Multiplication: `self * other`.
|
||||
|
||||
Multiplying `gf2` values is like multiplying `int`s.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> one * one
|
||||
one
|
||||
>>> zero * one
|
||||
zero
|
||||
>>> 0 * one
|
||||
zero
|
||||
"""
|
||||
return self._compute(other, lambda s, o: s * o)
|
||||
|
||||
__rmul__ = __mul__
|
||||
|
||||
def __truediv__(self, other: object) -> Self:
|
||||
"""Division: `self / other` and `self // other`.
|
||||
|
||||
Dividing `gf2` values is like dividing `int`s.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> one / one
|
||||
one
|
||||
>>> zero // one
|
||||
zero
|
||||
>>> one / zero
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ZeroDivisionError: ...
|
||||
>>> 1 // one
|
||||
one
|
||||
"""
|
||||
return self._compute(other, lambda s, o: s / o)
|
||||
|
||||
__floordiv__ = __truediv__
|
||||
|
||||
def __rtruediv__(self, other: object) -> Self:
|
||||
"""(Reflected) Division: `other / self` and `other // self`.
|
||||
|
||||
See docstring for `.__truediv__()`.
|
||||
"""
|
||||
return self._compute(other, lambda s, o: o / s)
|
||||
|
||||
__rfloordiv__ = __rtruediv__
|
||||
|
||||
def __mod__(self, other: object) -> Self:
|
||||
"""Modulo Division: `self % other`.
|
||||
|
||||
Modulo dividing `gf2` values is like modulo dividing `int`s.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> one % one
|
||||
zero
|
||||
>>> zero % one
|
||||
zero
|
||||
>>> one % zero
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ZeroDivisionError: ...
|
||||
>>> 1 % one
|
||||
zero
|
||||
"""
|
||||
return self._compute(other, lambda s, o: s % o)
|
||||
|
||||
def __rmod__(self, other: object) -> Self:
|
||||
"""(Reflected) Modulo Division: `other % self`.
|
||||
|
||||
See docstring for `.__mod__()`.
|
||||
"""
|
||||
return self._compute(other, lambda s, o: o % s)
|
||||
|
||||
def __pow__(self, other: object, _modulo: object = None) -> Self:
|
||||
"""Exponentiation: `self ** other`.
|
||||
|
||||
Powers of `gf2` values are like powers of `int`s.
|
||||
|
||||
Example usage:
|
||||
|
||||
>>> one ** one
|
||||
one
|
||||
>>> zero ** one
|
||||
zero
|
||||
>>> one ** zero
|
||||
one
|
||||
>>> 1 ** one
|
||||
one
|
||||
"""
|
||||
return self._compute(other, lambda s, o: s**o)
|
||||
|
||||
def __rpow__(self, other: object, _modulo: object = None) -> Self:
|
||||
"""(Reflected) Exponentiation: `other ** self`.
|
||||
|
||||
See docstring for `.__pow__()`.
|
||||
"""
|
||||
return self._compute(other, lambda s, o: o**s)
|
||||
|
||||
|
||||
numbers.Rational.register(GF2Element)
|
||||
|
||||
|
||||
# The `GF2One` and `GF2Zero` sub-classes' primary purpose
|
||||
# is to give `one` and `zero` their very own `help()` message
|
||||
|
||||
|
||||
class GF2One(GF2Element):
|
||||
"""The Galois field value `one`."""
|
||||
|
||||
_value = 1
|
||||
|
||||
|
||||
class GF2Zero(GF2Element):
|
||||
"""The Galois field value `zero`."""
|
||||
|
||||
_value = 0
|
||||
|
||||
|
||||
one = GF2One()
|
||||
zero = GF2Zero()
|
||||
|
||||
|
||||
# Outside this module the `GF2Element` is just "the `gf2` type"
|
||||
gf2 = GF2Element
|
||||
|
||||
|
||||
del GF2Meta
|
||||
del GF2One
|
||||
del GF2Zero
|
||||
|
||||
del config
|
||||
32
src/lalib/fields/__init__.py
Normal file
32
src/lalib/fields/__init__.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"""A collection of common fields used in linear algebra."""
|
||||
|
||||
from lalib.fields import base
|
||||
from lalib.fields import complex_
|
||||
from lalib.fields import galois
|
||||
from lalib.fields import rational
|
||||
from lalib.fields import real
|
||||
from lalib.fields import utils
|
||||
|
||||
|
||||
Field = base.Field
|
||||
|
||||
Q = rational.Q
|
||||
R = real.R
|
||||
C = complex_.C
|
||||
GF2 = galois.GF2
|
||||
|
||||
|
||||
del base
|
||||
del complex_
|
||||
del galois
|
||||
del rational
|
||||
del real
|
||||
del utils # `import`ed and `del`eted to not be in the final namespace
|
||||
|
||||
|
||||
__all__ = (
|
||||
"Q",
|
||||
"R",
|
||||
"C",
|
||||
"GF2",
|
||||
)
|
||||
227
src/lalib/fields/base.py
Normal file
227
src/lalib/fields/base.py
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
"""The abstract blueprint of a `Field`."""
|
||||
|
||||
import abc
|
||||
import numbers
|
||||
from typing import Any, Callable, Generic, TypeVar
|
||||
|
||||
|
||||
T = TypeVar("T", bound=numbers.Real)
|
||||
|
||||
|
||||
class Field(abc.ABC, Generic[T]):
|
||||
"""The abstract blueprint of a mathematical field."""
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def _math_name(self) -> str:
|
||||
"""The common abbreviation used in math notation."""
|
||||
|
||||
@staticmethod
|
||||
@abc.abstractmethod
|
||||
def _dtype(value: Any, /) -> T:
|
||||
"""Data type to store the `Field` elements."""
|
||||
|
||||
def _cast_func(self, value: Any, /, **kwargs: Any) -> T:
|
||||
"""Function to cast `value`s as field elements."""
|
||||
return self._dtype(value, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def _post_cast_filter(possible_element: T, /) -> bool: # noqa: ARG004
|
||||
"""Function to filter out castable `value`s.
|
||||
|
||||
Called after a successfull call of the `._cast_func()`.
|
||||
|
||||
For example, if one wants to avoid non-finite `Field` elements,
|
||||
an overwriting `._post_cast_filter()` could return `False` for
|
||||
non-finite `value`s like `float("NaN")`.
|
||||
|
||||
By default, all castable `value`s may become `Field` elements.
|
||||
"""
|
||||
return True
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def _additive_identity(self) -> T:
|
||||
"""The field's additive identity."""
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def _multiplicative_identity(self) -> T:
|
||||
"""The field's multiplicative identity."""
|
||||
|
||||
def cast(
|
||||
self,
|
||||
value: object,
|
||||
/,
|
||||
**cast_kwargs: Any,
|
||||
) -> T:
|
||||
"""Cast a (numeric) `value` as an element of the field.
|
||||
|
||||
Args:
|
||||
value: to be cast as the "right" data type
|
||||
as defined in the concrete `Field` sub-class
|
||||
**cast_kwargs: extra `kwargs` to the `._cast_func()`
|
||||
|
||||
Returns:
|
||||
element: of the concrete `Field`
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not an element of the field
|
||||
"""
|
||||
try:
|
||||
element = self._cast_func(value, **cast_kwargs) # type: ignore[arg-type]
|
||||
except (ArithmeticError, TypeError, ValueError):
|
||||
msg = "`value` is not an element of the field"
|
||||
raise ValueError(msg) from None
|
||||
|
||||
if not self._post_cast_filter(element):
|
||||
msg = "`value` is not an element of the field"
|
||||
raise ValueError(msg)
|
||||
|
||||
return element
|
||||
|
||||
def validate(
|
||||
self,
|
||||
value: object,
|
||||
/,
|
||||
*,
|
||||
silent: bool = True,
|
||||
**cast_kwargs: Any,
|
||||
) -> bool:
|
||||
"""Check if a (numeric) `value` is an element of the `Field`.
|
||||
|
||||
Wraps `.cast()`, catches the documented `ValueError`,
|
||||
and returns a `bool`ean indicating field membership.
|
||||
|
||||
Args:
|
||||
value: see docstring for `.cast()`
|
||||
silent: suppress the `ValueError`
|
||||
**cast_kwargs: extra `kwargs` to `.cast()` the `value`
|
||||
|
||||
Returns:
|
||||
is_element
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not `.cast()`able
|
||||
(suppressed by default)
|
||||
"""
|
||||
try:
|
||||
self.cast(value, **cast_kwargs)
|
||||
except ValueError:
|
||||
if not silent:
|
||||
raise
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@property
|
||||
def dtype(self) -> Callable[[Any], T]:
|
||||
"""Data type to store the `Field` elements."""
|
||||
return self._dtype
|
||||
|
||||
@property
|
||||
def zero(self) -> T:
|
||||
"""The field's additive identity."""
|
||||
return self._additive_identity
|
||||
|
||||
def is_zero(self, value: T, /, **cast_kwargs: Any) -> bool:
|
||||
"""Check if `value` equals the `.zero`-like field element.
|
||||
|
||||
This method, together with `.is_one()` below, provides a unified
|
||||
way across the different `Field`s to check if a given `value`
|
||||
equals the field's additive or multiplicative identity.
|
||||
|
||||
Concrete `Field`s may use a different logic. For example, some
|
||||
compare the absolute difference between the `value` and the
|
||||
`.zero`-or-`.one`-like field element to a small `threshold`.
|
||||
|
||||
Overwriting methods should
|
||||
- check the `value` for field membership first, and
|
||||
- accept arbitrary keyword-only arguments
|
||||
that they may simply ignore
|
||||
|
||||
Args:
|
||||
value: see docstring for `.cast()`
|
||||
**cast_kwargs: extra `kwargs` to `.cast()` the `value`
|
||||
|
||||
Returns:
|
||||
is_zero
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not `.cast()`able
|
||||
"""
|
||||
return self.cast(value, **cast_kwargs) == self._additive_identity
|
||||
|
||||
@property
|
||||
def one(self) -> T:
|
||||
"""The field's multiplicative identity."""
|
||||
return self._multiplicative_identity
|
||||
|
||||
def is_one(self, value: T, /, **cast_kwargs: Any) -> bool:
|
||||
"""Check if `value` equals the `.one`-like field element.
|
||||
|
||||
See docstring for `.is_zero()` above for more details.
|
||||
|
||||
Args:
|
||||
value: see docstring for `.cast()`
|
||||
**cast_kwargs: extra `kwargs` to `.cast()` the `value`
|
||||
|
||||
Returns:
|
||||
is_one
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not `.cast()`able
|
||||
"""
|
||||
return self.cast(value, **cast_kwargs) == self._multiplicative_identity
|
||||
|
||||
@abc.abstractmethod
|
||||
def random(
|
||||
self,
|
||||
*,
|
||||
lower: T,
|
||||
upper: T,
|
||||
**cast_kwargs: Any,
|
||||
) -> T:
|
||||
"""Draw a uniformly distributed random element from the field.
|
||||
|
||||
`lower` and `upper` may come in reversed order.
|
||||
Overwriting methods should sort them if necessary.
|
||||
|
||||
Extra keyword arguments should be passed through to `.cast()`.
|
||||
"""
|
||||
|
||||
def _get_bounds(
|
||||
self,
|
||||
lower: T,
|
||||
upper: T,
|
||||
/,
|
||||
**cast_kwargs: Any,
|
||||
) -> tuple[T, T]:
|
||||
"""Get the `lower` & `upper` bounds for `Field.random()`.
|
||||
|
||||
Utility method to either
|
||||
- resolve the given `lower` and `upper` bounds into a
|
||||
`.cast()`ed element of the `Field`, or
|
||||
- obtain their default `value`s, which are
|
||||
+ the `.additive_identity` for `lower`, and
|
||||
+ the `.multiplicative_identity` for `upper`
|
||||
|
||||
Extra keyword arguments are passed through to `.cast()`.
|
||||
"""
|
||||
lower = lower if lower is not None else self._additive_identity
|
||||
upper = upper if upper is not None else self._multiplicative_identity
|
||||
|
||||
return (self.cast(lower, **cast_kwargs), self.cast(upper, **cast_kwargs))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Text representations: `repr(...)` and `str(...)`.
|
||||
|
||||
The `.math_name` should be a valid name within `lalib`.
|
||||
If not, use the "<cls ...>" convention; in other words,
|
||||
the text representation is no valid code on its own.
|
||||
|
||||
See: https://docs.python.org/3/reference/datamodel.html#object.__repr__
|
||||
"""
|
||||
return self._math_name
|
||||
|
||||
__str__ = __repr__
|
||||
110
src/lalib/fields/complex_.py
Normal file
110
src/lalib/fields/complex_.py
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
"""The concrete `ComplexField`."""
|
||||
|
||||
import cmath
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from lalib import config
|
||||
from lalib.fields import base
|
||||
from lalib.fields import utils
|
||||
|
||||
|
||||
class ComplexField(utils.SingletonMixin, base.Field):
|
||||
"""The `Field` over ℂ, the complex numbers."""
|
||||
|
||||
_math_name = "ℂ"
|
||||
_dtype = complex
|
||||
_post_cast_filter = cmath.isfinite
|
||||
_additive_identity = 0 + 0j
|
||||
_multiplicative_identity = 1 + 0j
|
||||
|
||||
def random(
|
||||
self,
|
||||
*,
|
||||
lower: complex = _additive_identity,
|
||||
upper: complex = _multiplicative_identity,
|
||||
ndigits: int = config.NDIGITS,
|
||||
**_cast_kwargs: Any,
|
||||
) -> complex:
|
||||
"""Draw a uniformly distributed random element from the field.
|
||||
|
||||
The `.real` and `.imag`inary parts of the `lower` and `upper`
|
||||
bounds evaluated separately; i.e., the `random_element` is drawn
|
||||
from a rectangle with opposing corners `lower` and `upper`.
|
||||
|
||||
`lower` and `upper` may come in reversed order.
|
||||
|
||||
Args:
|
||||
lower: bound of the random interval
|
||||
upper: bound of the random interval
|
||||
ndigits: no. of significant digits to the right of the ".";
|
||||
both the `.real` and the `.imag`inary parts are rounded
|
||||
|
||||
Returns:
|
||||
random_element
|
||||
|
||||
Raises:
|
||||
ValueError: `lower` and `upper` are not `.cast()`able
|
||||
"""
|
||||
lower, upper = self._get_bounds(lower, upper)
|
||||
|
||||
random_real, random_imag = (
|
||||
# `random.uniform()` can handle `upper < lower`
|
||||
round(random.uniform(lower.real, upper.real), ndigits), # noqa: S311
|
||||
round(random.uniform(lower.imag, upper.imag), ndigits), # noqa: S311
|
||||
)
|
||||
|
||||
return complex(random_real, random_imag)
|
||||
|
||||
def is_zero(
|
||||
self,
|
||||
value: complex,
|
||||
/,
|
||||
*,
|
||||
threshold: float = config.THRESHOLD,
|
||||
**_cast_kwargs: Any,
|
||||
) -> bool:
|
||||
"""Check if `value` equals `0.0 + 0.0j`.
|
||||
|
||||
To be precise: Check if `value` deviates by less than the
|
||||
`threshold` from `0.0 + 0.0j` in absolute terms.
|
||||
|
||||
Args:
|
||||
value: to be compared to `0.0 + 0.0j`
|
||||
threshold: for the equality check
|
||||
|
||||
Returns:
|
||||
is_zero
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not `.cast()`able
|
||||
"""
|
||||
return abs(self.cast(value)) < threshold
|
||||
|
||||
def is_one(
|
||||
self,
|
||||
value: complex,
|
||||
/,
|
||||
*,
|
||||
threshold: float = config.THRESHOLD,
|
||||
**_cast_kwargs: Any,
|
||||
) -> bool:
|
||||
"""Check if `value` equals `1.0 + 0.0j`.
|
||||
|
||||
To be precise: Check if `value` deviates by less than the
|
||||
`threshold` from `1.0 + 0.0j` in absolute terms.
|
||||
|
||||
Args:
|
||||
value: to be compared to `1.0 + 0.0j`
|
||||
threshold: for the equality check
|
||||
|
||||
Returns:
|
||||
is_one
|
||||
|
||||
Raises:
|
||||
ValueError: `value` is not `.cast()`able
|
||||
"""
|
||||
return abs(self.cast(value) - (1.0 + 0j)) < threshold
|
||||
|
||||
|
||||
C = ComplexField()
|
||||
45
src/lalib/fields/galois.py
Normal file
45
src/lalib/fields/galois.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""The concrete `GaloisField2`."""
|
||||
|
||||
import random
|
||||
from typing import Any
|
||||
|
||||
from lalib.elements import galois as gf2_elements
|
||||
from lalib.fields import base
|
||||
from lalib.fields import utils
|
||||
|
||||
|
||||
class GaloisField2(utils.SingletonMixin, base.Field):
|
||||
"""The Galois `Field` of 2 elements."""
|
||||
|
||||
_math_name = "GF2"
|
||||
_dtype = gf2_elements.GF2Element
|
||||
_additive_identity = gf2_elements.zero
|
||||
_multiplicative_identity = gf2_elements.one
|
||||
|
||||
def random(
|
||||
self,
|
||||
lower: gf2_elements.GF2Element = gf2_elements.zero,
|
||||
upper: gf2_elements.GF2Element = gf2_elements.one,
|
||||
**cast_kwargs: Any,
|
||||
) -> gf2_elements.GF2Element:
|
||||
"""Draw a uniformly distributed random element from the field.
|
||||
|
||||
Args:
|
||||
lower: bound of the random interval
|
||||
upper: bound of the random interval
|
||||
**cast_kwargs: extra `kwargs` to `.cast()`
|
||||
the `lower` and `upper` bounds
|
||||
|
||||
Returns:
|
||||
random_element: either `one` or `zero`
|
||||
|
||||
Raises:
|
||||
ValueError: `lower` and `upper` are not `.cast()`able
|
||||
"""
|
||||
lower, upper = self._get_bounds(lower, upper, **cast_kwargs)
|
||||
|
||||
# `random.choice()` can handle `upper < lower`
|
||||
return random.choice((lower, upper)) # noqa: S311
|
||||
|
||||
|
||||
GF2 = GaloisField2()
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue