Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
b2f6155872
Merge branch 'fields' into 'develop'
Some checks failed
audit / audit (push) Has been cancelled
docs / docs (push) Has been cancelled
lint / lint (push) Has been cancelled
test-coverage / test-coverage (push) Has been cancelled
test-docstrings / test-docstrings (push) Has been cancelled
tests / test-3.10 (push) Has been cancelled
tests / test-3.11 (push) Has been cancelled
tests / test-3.12 (push) Has been cancelled
tests / test-3.13 (push) Has been cancelled
tests / test-3.9 (push) Has been cancelled
2024-10-16 12:01:00 +02:00
c7f076c35c
Update dependencies
- bandit (1.7.9 -> 1.7.10)
- black (24.8.0 -> 24.10.0)
- charset-normalizer (3.3.2 -> 3.4.0)
- coverage (7.6.1 -> 7.6.3)
- distlib (0.3.8 -> 0.3.9)
- markupsafe (2.1.5 -> 3.0.1)
- mypy (1.11.2 -> 1.12.0)
- pydoclint (0.5.7 -> 0.5.9)
- rich (13.8.1 -> 13.9.2)
- ruff (0.6.5 -> 0.6.9)
- sphinx (8.0.2 -> 8.1.3)
- virtualenv (20.26.5 -> 20.26.6)
2024-10-16 11:55:52 +02:00
6ddb545491
Remove unnecessary Optional
The type hints `object` and `Optional[object]`
both allow the default value `None`.

Also, this commit gets rid of ruff's "FA100" error
for the two changed lines.
2024-10-16 11:47:51 +02:00
81912f1a81
Make linters check for unused function arguments 2024-10-16 11:23:54 +02:00
25c718fe6a
Make Python 3.13 the new default 2024-10-16 01:32:14 +02:00
f952d95951
Make value a positional-only argument in gf2()
Most of Python's built-in data types behave like this as well
2024-10-15 02:17:23 +02:00
849b786e13
Add fields to top-level imports for lalib 2024-10-15 02:15:10 +02:00
6bd21ce134
Fix missing module
Forgotten in commit 153094eef5
2024-10-15 02:04:34 +02:00
7e3e67c300
Add smoke tests
- extend `pytest` with an option to run only the minimum number
  of (unit) test cases to just keep the coverage at 100%
- rationale:
  + many of the unit test cases partly overlap with
    respect to the lines of source code executed
  + also, integration tests, by definition, do not
    contribute to a higher test coverage
- implementation: mark "redundant" test cases as one of:
  + `pytest.mark.integration_test`
    => code usage from the perspective of the end user
  + `pytest.mark.overlapping_test`
    => tests not contributing to the 100% coverage
  + `pytest.mark.sanity_test`
    => tests providing confidence in the test data
- add `tests.conftest` module
  => programatically convert the above markers into
     `@pytest.mark.no_cover` and collect the non-"redundant" tests
- add nox session "test-fast" to run only the minimum
  number of (unit) test while holding coverage at 100%
- refactor some test modules
  + wrap some test cases in a class
  + move sanity tests to the end of the files
2024-10-15 01:49:32 +02:00
de740ebb5f
Unify the various *_THRESHOLDs 2024-10-14 16:36:02 +02:00
04addacb09
Add tests.utils module 2024-10-14 16:34:17 +02:00
153094eef5
Add Q, R, C, and GF2 fields
- add `lalib.fields.base.Field`, a blueprint for all concrete fields,
  providing a unified interface to be used outside of the
  `lalib.fields` sub-package
- implement `lalib.fields.complex_.ComplexField`, or `C` for short,
  the field over the complex numbers (modeled as `complex` numbers)
- implement `lalib.fields.galois.GaloisField2`, or `GF2` for short,
  the (finite) field over the two elements `one` and `zero`
  + adapt `lalib.elements.galois.GF2Element.__eq__()` to return
    `NotImplemented` instead of `False` for non-castable `other`s
    => this fixes a minor issue with `pytest.approx()`
- implement `lalib.fields.rational.RationalField`, or `Q` for short,
  the field over the rational numbers (modeled as `fractions.Fraction`s)
- implement `lalib.fields.real.RealField`, or `R` for short,
  the field over the real numbers (modeled as `float`s)
- organize top-level imports for `lalib.fields`,
  making `Q`, `R`, `C`, and `GF2` importable with
  `from lalib.fields import *`
- provide extensive unit and integration tests for the new objects:
  + test generic and common behavior in `tests.fields.test_base`
  + test specific behavior is other modules
  + test the well-known math axioms for all fields (integration tests)
  + test the new objects' docstrings
  + add "pytest-repeat" to run randomized tests many times
2024-10-14 15:17:42 +02:00
cbc1f8fd3a
Add lalib.config for library-wide settings
Also, refactor `lalib.elements.galois`
(incl. tests) to use the new settings
2024-10-14 15:02:50 +02:00
febed693b8
Make asserts more Pythonic 2024-10-14 14:38:09 +02:00
08067b3d6e
Fix pytest not respecting the singleton pattern
This is only a temporary fix!

See issue: https://github.com/webartifex/lalib/issues/1
2024-09-27 16:16:01 +02:00
3d9f990c68
Reset random.seed() before every test case 2024-09-27 16:04:37 +02:00
4c0c7887e5
Allow and unify the usage of TODOs 2024-09-27 15:29:33 +02:00
06d003b615
Hide gf2 sub-classes even more
- the `gf2` sub-classes `GF2One` and `GF2Zero` have no purpose
  other than to provide unique `help(one)` and `help(zero)` messages
- delete them at the bottom of `lalib.elements.galois`
  to prevent them from being imported at all
  (`type(one)` and `type(zero)` still appear to be the `gf2` class,
   which is a little white lie, provided by some meta class)
- differentiate between official and inofficial API in the test suite
2024-09-19 15:36:10 +02:00
348cd53767
Make lalib.elements.galois.to_gf2() a detail
- `to_gf2()` is only to be used within `GF2Element.__new__()`
  => rename it into `_to_gf2()`
- the test cases in `TestGF2ConstructorWithCastedValue`
  cover everything in `TestGF2Casting`
  => retire the redundant test cases
     and make the test suite run faster
2024-09-19 14:22:10 +02:00
917c217ca0
Rename lalib.elements.gf2.GF2 & friends
- the future (concrete) Galois `Field` implementation
  shall receive the name `GF2` (as per common math notation)
  => name conflict with the current `GF2` class
     implementing the elements of the future Galois `Field`
  => rename the current `GF2` class into `GF2Element`
- because `GF2Element` is a bit tedius to type for the end user,
  we introduce a `gf2` alias in line with the naming convention
  for the built-in data types (e.g., `int` or `float`)
  that are also used as elements of (other) `Field`s
  => name conflict with the current `lalib.elements.gf2` module
  => rename the module into `lalib.elements.galois`
- adjust the docstrings to refer to "the `gf2` type"
- adjust the top-level imports and tests
2024-09-19 12:14:20 +02:00
65de932f8d
Add lalib.fields sub-package 2024-09-18 23:42:38 +02:00
4c47ca1b17
Merge branch 'gf2-type' into 'develop' 2024-09-18 23:16:51 +02:00
ea85c73933
Update dependencies
- filelock (3.16.0 -> 3.16.1)
- identify (2.6.0 -> 2.6.1)
- idna (3.8 -> 3.10)
- platformdirs (4.3.2 -> 4.3.6)
- pytest (8.3.2 -> 8.3.3)
- rich (13.8.0 -> 13.8.1)
- ruff (0.6.4 -> 0.6.5)
- setuptools (74.1.2 -> 75.1.0)
- urllib3 (2.2.2 -> 2.2.3)
- virtualenv (20.26.4 -> 20.26.5)
2024-09-18 22:53:33 +02:00
51c73163e4
Refactor test_top_level_imports() test cases ...
... into a unified location
2024-09-18 20:05:49 +02:00
62b25f66d9
Organize top-level imports for lalib
- make `GF2`, `one`, and `zero`, defined in the `lalib.elements.gf2`
  module, available as top-level imports for the `lalib` package
  via `from lalib import *`
- provide some code snippets in the package's docstring
- test the star import
2024-09-18 18:37:54 +02:00
3cfc0db136
Organize top-level imports for lalib.elements
- make `GF2`, `one`, and `zero`, defined in the `lalib.elements.gf2`
  module, available as top-level imports in the `lalib.elements`
  sub-package via `from lalib.elements import *`
- provide some code snippets in the sub-package's docstring
- test the star import
2024-09-18 18:29:40 +02:00
3cecf0d989
Add GF2 type for Galois field elements
- add `GF2` class in the `lalib.elements` sub-package
  implementing a typical Galois field with two elements
- the singleton objects `one` and `zero` are the concrete
  instances of the `GF2` type for the end users
- besides the typical Galois arithmetic, `one` and `zero`
  behave like the built-in numbers `1` and `0`
  and implement the `numbers.Rational` interface
- add exhaustive docstrings with usage examples
- add (unit) test cases with 100% coverage
2024-09-18 18:04:35 +02:00
d405c22c90
Enforce PEP257 strictly ...
... and put docstrings for class constructors
into `.__init__()` methods

Source: https://peps.python.org/pep-0257/#multi-line-docstrings
2024-09-18 15:17:53 +02:00
d9dcea8379
Do not allow mere "pragma: no cover"s 2024-09-18 15:15:24 +02:00
9083cebe18
Fix missing empty line ...
... to make overview on sections clearer
2024-09-18 15:08:19 +02:00
d507e1f56d
Add lalib.elements sub-package 2024-09-10 11:53:17 +02:00
5d2f430893
Bump version 2024-09-10 03:55:36 +02:00
37 changed files with 3422 additions and 412 deletions

View file

@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: 3.12 python-version: 3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: 3.12 python-version: 3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: 3.12 python-version: 3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -16,6 +16,7 @@ jobs:
3.10 3.10
3.11 3.11
3.12 3.12
3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -14,6 +14,7 @@ jobs:
3.10 3.10
3.11 3.11
3.12 3.12
3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: 3.12 python-version: 3.13
architecture: x64 architecture: x64
- run: python --version - run: python --version

View file

@ -5,7 +5,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: 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 }} name: test-${{ matrix.python-version }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4

View file

@ -3,7 +3,7 @@ version: 2
build: build:
os: ubuntu-24.04 os: ubuntu-24.04
tools: tools:
python: "3.12" python: "3.13"
sphinx: sphinx:
configuration: docs/conf.py configuration: docs/conf.py

View file

@ -89,7 +89,7 @@ To execute all default tasks, simply invoke:
`nox` `nox`
This includes running the test suite for the project's main Python version 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 #### Code Formatting & Linting

View file

@ -57,7 +57,7 @@ def load_supported_python_versions(*, reverse: bool = False) -> list[str]:
SUPPORTED_PYTHONS = load_supported_python_versions(reverse=True) SUPPORTED_PYTHONS = load_supported_python_versions(reverse=True)
MAIN_PYTHON = "3.12" MAIN_PYTHON = "3.13"
DOCS_SRC, DOCS_BUILD = ("docs/", ".cache/docs/") DOCS_SRC, DOCS_BUILD = ("docs/", ".cache/docs/")
TESTS_LOCATION = "tests/" TESTS_LOCATION = "tests/"
@ -205,8 +205,10 @@ def lint(session: nox.Session) -> None:
"flake8-isort", "flake8-isort",
"flake8-quotes", "flake8-quotes",
"flake8-string-format", "flake8-string-format",
"flake8-todos",
"flake8-pyproject", "flake8-pyproject",
"flake8-pytest-style", "flake8-pytest-style",
"flake8-unused-arguments",
"mypy", "mypy",
"pep8-naming", # flake8 plug-in "pep8-naming", # flake8 plug-in
"pydoclint[flake8]", "pydoclint[flake8]",
@ -229,10 +231,15 @@ TEST_DEPENDENCIES = (
"packaging", "packaging",
"pytest", "pytest",
"pytest-cov", "pytest-cov",
"pytest-randomly",
"pytest-repeat",
"semver", "semver",
'typing-extensions; python_version < "3.11"', # to support Python 3.9 & 3.10
"xdoctest", "xdoctest",
) )
TEST_RANDOM_SEED = "--randomly-seed=42"
@nox.session(python=SUPPORTED_PYTHONS) @nox.session(python=SUPPORTED_PYTHONS)
def test(session: nox.Session) -> None: def test(session: nox.Session) -> None:
@ -248,6 +255,15 @@ def test(session: nox.Session) -> None:
args = posargs or ( args = posargs or (
"--cov", "--cov",
"--no-cov-on-fail", "--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, TESTS_LOCATION,
) )
@ -284,6 +300,8 @@ def test_coverage_run(session: nox.Session) -> None:
session.install(".") session.install(".")
install_pinned(session, "coverage", *TEST_DEPENDENCIES) install_pinned(session, "coverage", *TEST_DEPENDENCIES)
session.env["N_RANDOM_DRAWS"] = "10"
session.env["NO_CROSS_REFERENCE"] = "true"
session.run( session.run(
"python", "python",
"-m", "-m",
@ -291,6 +309,7 @@ def test_coverage_run(session: nox.Session) -> None:
"run", "run",
"-m", "-m",
"pytest", "pytest",
TEST_RANDOM_SEED,
TESTS_LOCATION, TESTS_LOCATION,
) )
@ -329,6 +348,18 @@ def test_docstrings(session: nox.Session) -> None:
session.run("xdoctest", "src/lalib") 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") @nox.session(name="clean-cwd", python=MAIN_PYTHON, venv_backend="none")
def clean_cwd(session: nox.Session) -> None: def clean_cwd(session: nox.Session) -> None:
"""Remove (almost) all glob patterns listed in git's ignore file. """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_CACHE_DIR"] = ".cache/pip"
session.env["PIP_DISABLE_PIP_VERSION_CHECK"] = "true" 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: def suppress_poetry_export_warning(session: nox.Session) -> None:
"""Temporary fix to avoid poetry's warning ... """Temporary fix to avoid poetry's warning ...

802
poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
[tool.poetry] [tool.poetry]
name = "lalib" name = "lalib"
version = "0.4.2" version = "0.5.0.dev0"
authors = [ authors = [
"Alexander Hess <alexander@webartifex.biz>", "Alexander Hess <alexander@webartifex.biz>",
@ -16,6 +16,7 @@ classifiers = [
"Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
] ]
description = "A Python library to study linear algebra" description = "A Python library to study linear algebra"
license = "MIT" license = "MIT"
@ -30,6 +31,8 @@ repository = "https://github.com/webartifex/lalib"
python = "^3.9" python = "^3.9"
typing-extensions = [ { python = "<3.11", version = "^4.12" } ] # to support Python 3.9 & 3.10
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]
@ -55,8 +58,10 @@ flake8-eradicate = "^1.5"
flake8-isort = "^6.1" flake8-isort = "^6.1"
flake8-quotes = "^3.4" flake8-quotes = "^3.4"
flake8-string-format = "^0.3" flake8-string-format = "^0.3"
flake8-todos = "^0.3"
flake8-pyproject = "^1.2" flake8-pyproject = "^1.2"
flake8-pytest-style = "^2.0" flake8-pytest-style = "^2.0"
flake8-unused-arguments = "^0.0"
mypy = "^1.11" mypy = "^1.11"
pep8-naming = "^0.14" # flake8 plug-in pep8-naming = "^0.14" # flake8 plug-in
pydoclint = { extras = ["flake8"], version = "^0.5" } pydoclint = { extras = ["flake8"], version = "^0.5" }
@ -74,10 +79,13 @@ coverage = "^7.6"
packaging = "^24.1" # to test the version identifier packaging = "^24.1" # to test the version identifier
pytest = "^8.3" pytest = "^8.3"
pytest-cov = "^5.0" pytest-cov = "^5.0"
pytest-randomly = "^3.15"
pytest-repeat = "^0.9"
semver = "^3.0" # to test the version identifier semver = "^3.0" # to test the version identifier
tomli = [ { python = "<3.11", version = "^2.0" } ] tomli = [ { python = "<3.11", version = "^2.0" } ]
xdoctest = { extras = ["colors"], version = "^1.2" } xdoctest = { extras = ["colors"], version = "^1.2" }
[tool.poetry.urls] [tool.poetry.urls]
"Issues Tracker" = "https://github.com/webartifex/lalib/issues" "Issues Tracker" = "https://github.com/webartifex/lalib/issues"
@ -121,6 +129,16 @@ show_missing = true
skip_covered = true skip_covered = true
skip_empty = 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] [tool.coverage.run]
@ -158,7 +176,9 @@ select = [
"PT", # flake8-pytest-style => enforce a consistent style with pytest "PT", # flake8-pytest-style => enforce a consistent style with pytest
"Q", # flake8-quotes => use double quotes everywhere (complying with black) "Q", # flake8-quotes => use double quotes everywhere (complying with black)
"S", # flake8-bandit => common security issues "S", # flake8-bandit => common security issues
"T00", # flake8-todos => unify TODOs
"T10", # flake8-debugger => no debugger usage "T10", # flake8-debugger => no debugger usage
"U100", # flake8-unused-arguments => declared function arguments must be used
# violations not covered by `ruff` below # 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` "ANN401", # allow dynamically typed expressions with `typing.Any`
"DOC301", # PEP257 => class constructor's docstring go in `.__init__()`
# Comply with black's style # Comply with black's style
# Sources: https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#pycodestyle # Sources: https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#pycodestyle
"E203", "E701", "E704", "W503", "E203", "E701", "E704", "W503",
@ -235,6 +257,12 @@ docstring-quotes = "double"
inline-quotes = "double" inline-quotes = "double"
multiline-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 [tool.isort] # aligned with [tool.ruff.lint.isort] below
@ -327,6 +355,7 @@ select = [
# violations also covered by `flake8` above # violations also covered by `flake8` above
"ANN", # flake8-annotations => enforce type checking for functions "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 "B", # flake8-bugbear => bugs and design flaws
"C4", # flake8-comprehensions => better comprehensions "C4", # flake8-comprehensions => better comprehensions
"C90", # mccabe => cyclomatic complexity "C90", # mccabe => cyclomatic complexity
@ -340,6 +369,7 @@ select = [
"PT", # flake8-pytest-style => enforce a consistent style with pytest "PT", # flake8-pytest-style => enforce a consistent style with pytest
"Q", # flake8-quotes => use double quotes everywhere "Q", # flake8-quotes => use double quotes everywhere
"S", # flake8-bandit => common security issues "S", # flake8-bandit => common security issues
"TD", # flake8-todos => unify TODOs
"T10", # flake8-debugger => no debugger usage "T10", # flake8-debugger => no debugger usage
# violations not covered by `flake8` above # 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 [tool.ruff.lint.flake8-pytest-style] # aligned with [tool.flake8] above

View file

@ -4,10 +4,27 @@ First, verify that your installation of `lalib` works:
>>> import lalib >>> import lalib
>>> lalib.__version__ != '0.0.0' >>> lalib.__version__ != '0.0.0'
True 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 importlib import metadata
from lalib import elements
from lalib import fields
try: try:
pkg_info = metadata.metadata(__name__) pkg_info = metadata.metadata(__name__)
@ -24,4 +41,22 @@ else:
del pkg_info 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 del metadata
__all__ = (
"gf2",
"one",
"zero",
"Q",
"R",
"C",
"GF2",
)

13
src/lalib/config.py Normal file
View 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

View 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",
)

View 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

View 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
View 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__

View 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()

View 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