Skip to main content

AlgebraX - Algebraic primitives over sparse data structures in pure Python

AlgebraX Banner

Package PyPI - Version PyPI - Status PyPI - Python Version PyPI - Downloads PyPI - Dependents Libraries.io SourceRank
Code GitHub GitHub repo size GitHub last commit (by committer) Contributors
Tools PyCharm uv Ruff Hatch project commitizen Zensical Jupytext agentskills
CI/CD Test Publish Benchmarks Publish Publish Docs
Scans Coverage Quality Gate Status Security Rating Maintainability Rating Reliability Rating Lines of Code Vulnerabilities Bugs Codacy Quality Codacy Coverage CodeFactor Snyk CodSpeed OpenSSF Scorecard
Mentions Python Hub X

AlgebraX treats Python's native dict (and Mapping) as a first-class sparse algebraic object, unifying linear algebra, abstract algebra, graph algorithms, discrete geometry & topology, signal transforms, and information metrics under a single pure-Python polymorphic framework.

Key Features

  • ⚡ Zero Heavy Dependencies: Pure-Python core requiring no C++ compilation (mappingtools is the sole core runtime dependency), with optional bridges to NumPy, SciPy, and PIL.
  • 🧱 Deductive Algebraic Hierarchy (algebrax.algebra, algebrax.category, algebrax.variety): Lean 4 / Mathlib-aligned @runtime_checkable protocols composed from 41 orthogonal atomic mixins (28 algebraic Has* + 9 categorical Has* + 4 geometric Has*) — spanning Magma, Monoid, Group, Lattice & BooleanAlgebra, Semiring / StarSemiring / KleeneAlgebra, Ring / Field / GaloisField / PAdicField, Ideal / GroebnerIdeal / QuotientRing, MultivariatePolynomialAlgebra, GeometricVariety / SmoothableVariety, Module / Algebra / NormedSpace / InnerProductSpace, dual Coalgebra / Bialgebra / HopfAlgebra, and Category / Groupoid / CartesianClosedCategory.
  • 🔄 Polymorphic Semiring Computing (algebrax.semiring): 33 built-in semirings and algebras. Swap $(\oplus, \otimes)$ in matrix.dot, tensor.einsum, or AlgebraicTrie to switch seamlessly between linear algebra, tropical shortest paths, Viterbi probabilities, statistical moments, or symbolic rule provenance.
  • 🎯 Exact Drift-Free Linear Solvers, Gröbner Ideals, Varieties & $p$-Adic Fields (algebrax.matrix, algebrax.algebra, algebrax.variety): Gaussian elimination, LU, QR, SVD, Cholesky, determinants, matrix inversion, multivariate polynomials $k[x_1, \dots, x_n]$, exact Gröbner bases (Buchberger & Faugère $F_4$), affine algebraic varieties (AffineVariety, PolynomialMap, Stickelberger companion matrix solvers, finite-field elliptic curves, CoordinateHopfAlgebra, and algebraic $K$-theory bridges), and piecewise-linear tropical varieties (TropicalPolynomialAlgebra, TropicalHypersurface, dual Newton polytope subdivisions, Noether/Minkowski balancing, and Dressian $\operatorname{Trop}(\operatorname{Gr}(k, n))$ Plücker relations) — parameterized over exact Field[V] implementations including rationals (StandardField(Fraction)), prime fields (ModularField(p)), finite extension fields (GaloisField), and non-archimedean $p$-adic numbers (PAdicField(p)).
  • 🌌 Geometry, Symmetry, Representation Theory & Topology: Multivector Clifford algebras $Cl(p,q,r)$ (clifford), classical & exceptional Lie algebras, Langlands dual root systems & IwahoriHeckeAlgebra (lie), finite fields $\mathrm{GF}(p^m)$ (algebra.GaloisField, galois), full representation theory (rep: finite-group characters & Schur projectors, Frobenius induction & Mackey theory, Lie weights, Clebsch–Gordan 3-tensors & cubic Casimirs, Molien invariant series, $U_q(\mathfrak{sl}_2)$ quantum groups, Yang–Baxter $R$-matrices & Jones knot invariants, quiver representations, PathAlgebra & Gabriel's ADE theorem), and unified algebraic topology (topology: homology, cohomology cup products, persistent barcodes, DEC, cellular sheaves, discrete bundles, K-theory & Chern classes, and path groupoids $\Pi_1(K)$).
  • 🧪 Unified 100-Structure Registry, CLI & Axiomatic Verification (algebrax.registry, algebrax.verification): Discover, inspect, and empirically verify all 100 built-in 0-cell algebraic structures via ax.registry or the python -m algebrax CLI (catalog, describe, inspect, verify), backed by property-based testing, differential SymPy/SciPy/NumPy oracles, Ramanujan expander verification (is_ramanujan_graph), and Z3 proofs, plus a 12-module DearPyGui desktop laboratory (recipes/lab.py).

Installation

# Using uv (recommended)
uv add algebrax

# Using pip
pip install algebrax

5-Minute Quickstart

1. Polymorphic Semiring Matrix Multiplication

By changing the semiring parameter in matrix.dot, the exact same sparse matrix multiplication computes standard linear combinations, tropical shortest paths, or symbolic rule derivations:

import algebrax as ax

# Define a Sparse Graph Adjacency / Distance Matrix
graph = {
    0: {1: 2.0, 2: 10.0},
    1: {2: 3.0},
}

# 1. Standard Linear Matrix Multiplication (+, *)
linear_mult = ax.matrix.dot(graph, graph, semiring=ax.semiring.StandardSemiring())
print('Linear Combination (0->2):', linear_mult[0][2])
# Output: 6.0 (2.0 * 3.0)

# 2. Tropical Shortest Path (min, +)
shortest_path = ax.matrix.dot(graph, graph, semiring=ax.semiring.TropicalSemiring())
print('Shortest Path Cost (0->1->2):', shortest_path[0][2])
# Output: 5.0 (min(2.0 + 3.0, 10.0 + inf))

# 3. Symbolic Provenance Rule Tracking
provenance_graph = {
    0: {1: {('rule_A',): 1}, 2: {('rule_C',): 1}},
    1: {2: {('rule_B',): 1}},
}
provenance_mult = ax.matrix.dot(provenance_graph, provenance_graph, semiring=ax.semiring.ProvenanceSemiring())
print('Symbolic Derivation Polynomial:', provenance_mult[0][2])
# Output: {('rule_A', 'rule_B'): 1}

2. Exact Drift-Free Solvers over Rational & Finite Fields

Parameterize sparse linear solvers over any Field[V] to eliminate IEEE-754 floating-point cancellation:

from fractions import Fraction
from algebrax.algebra import ModularField, StandardField
from algebrax.matrix import det, solve

# Exact rational Hilbert matrix determinant over Q
h2 = {0: {0: Fraction(1, 1), 1: Fraction(1, 2)}, 1: {0: Fraction(1, 2), 1: Fraction(1, 3)}}
print(det(h2, field=StandardField(Fraction)))
# Output: Fraction(1, 12)

# Exact sparse linear system over prime field F_11
a = {'eq1': {'x': 3, 'y': 2}, 'eq2': {'x': 4, 'y': 9}}
b = {'eq1': 5, 'eq2': 1}
print(solve(a, b, field=ModularField(11)))
# Output: {'x': 4, 'y': 2}

3. Explore & Verify the 100-Structure Registry (Python & CLI)

Browse, inspect, and empirically verify all 100 built-in 0-cell algebraic structures from Python or the terminal:

import algebrax as ax

print(len(ax.registry.catalog()))  # 100 concrete 0-cell structures
entry = ax.registry.get('TropicalHypersurface')
print(entry.domain, [p.__name__ for p in entry.protocols])
python -m algebrax catalog --domain variety
python -m algebrax describe TropicalHypersurface
python -m algebrax verify TropicalHypersurface

Architecture & Module Map

Pillar Submodules Highlights
Algebraic Foundations algebra, semiring, group, lattice 28 algebraic mixins, Semiring/StarSemiring/KleeneAlgebra, Ring/Field/GaloisField/PAdicField, MultivariatePolynomialAlgebra, GroebnerIdeal ($F_4$ & Buchberger), GrothendieckRing, HopfAlgebra, PathAlgebra, ActionAlgebra, Ideal & QuotientRing
Linear & Tensor Computing matrix, tensor, trie Sparse dot/power/closure, LU/QR/SVD/Cholesky, exact Field solvers, einsum, Clebsch–Gordan 3-tensors, AlgebraicTrie
Geometry, Symmetry, Representations & Topology variety, clifford, lie, rep, galois, topology Classical & tropical varieties (AffineVariety, PolynomialMap, Stickelberger solvers, CoordinateHopfAlgebra, TropicalHypersurface, TropicalPolynomialAlgebra, Newton polytopes & Dressians $\operatorname{Trop}(\operatorname{Gr}(k, n))$), Clifford $Cl(p,q,r)$ rotors, Lie algebras ($\mathfrak{so}(3)$, $\mathfrak{e}_8$, BCH, Langlands duals, IwahoriHeckeAlgebra), group/induced/Lie/invariant/quantum ($U_q(\mathfrak{sl}_2)$, Jones)/quiver (Gabriel ADE) representations, $\mathrm{GF}(p^m)$, homology, cohomology, persistence, DEC, sheaves, K-theory & path groupoids $\Pi_1(K)$
Dynamics, Categories, Registry & Tools category, automata, transforms, analysis, probability, metrics, converters, display, registry, verification 9 categorical mixins, CartesianClosedCategory, CoeffectContext, Kleisli composition, DFA/NFA, DFT/Walsh–Hadamard/Z-transform, Fiedler/curvature/Ramanujan expanders & RKHS, entropy, NumPy/SciPy bridges, 100-structure registry & python -m algebrax CLI, axiom verifiers

Recipe Highlights & Jupyter Notebooks

The recipes/ directory includes 51 runnable CLI scripts and synced .ipynb notebooks. Here is a curated sample across domains — see the full catalog in Recipes & Applications:

Domain Recipe & Notebook Algebraic Components
Tropical Geometry, ReLU & Phylogenetics Tropical Curves, ReLU & Dressians — 🐍 📓 TropicalHypersurface, TropicalPolynomialAlgebra, newton_subdivision, balancing_cochain, tropical_plucker_relations
Kinematics & Algebraic Geometry 2R Robot IK & Singularities — 🐍 📓 AffineVariety, companion_matrix, solve_zero_dimensional, radical_zero_dim, is_smooth_at
Quantum & Algebraic Stats Segre Entanglement & Markov Models — 🐍 📓 AffineVariety, PolynomialMap, syzygy_variety, tensor.einsum, probability.mutual_information
Vibrations & Equivariant ML Symmetry Modes & Molien Basis — 🐍 📓 isotypic_projector, reynolds_average, induced_representation, compute_molien_series, invariant_basis_at_degree
Quantum Spins & Polymer Knots Spin Coupling & Jones Knots — 🐍 📓 clebsch_gordan_matrix, quadratic_casimir, cubic_casimir_operator, QuantumSL2, jones_polynomial_eval
Multi-Sensor Robotics Quiver Calibration & Sheaf Drift — 🐍 📓 QuiverRepresentation, path_algebra, classify_representation_type, gabriel_positive_roots, to_cellular_sheaf
Graphs & Optimization Traffic Resilience — 🐍 📓 TropicalSemiring, matrix.power, analysis.forman_ricci_curvature, markov_steady_state
Spectral & Graph ML Spectral Graph Clustering — 🐍 📓 matrix.laplacian_matrix, analysis.fiedler_vector, analysis.laplacian_spectrum
TDA + Kernel ML TDA $\to$ RKHS Shape Classifier — 🐍 📓 FilteredSimplicialComplex, persistent_homology, betti_curve, ReproducingKernelHilbertSpace
Robotics & SLAM Pose Sync & Loop Holonomy — 🐍 📓 DiscreteOrthogonalConnection, build_connection_laplacian, compute_face_holonomy
Exact Math & Secret Sharing Zero-Drift Fields & Quotients — 🐍 📓 StandardField(Fraction), ModularField, PolynomialTruncationIdeal, QuotientRing
Topology & Deep Learning Topological Neural Networks — 🐍 📓 topology.SimplicialComplex, helmholtz_hodge_decomposition, Hodge 1-Laplacians
K-Theory & Gauge Bundles Topological K-Theory & Chern — 🐍 📓 TopologicalKTheoryRing, bundle_direct_sum, chern_character, first_chern_number
Categories & Homotopy CCC, Coeffects & $\Pi_1(K)$ — 🐍 📓 FiniteSetCCC, CoeffectContext, SemiringCoeffectTracker, SimplicialPathGroupoid
Langlands, Expanders & $\mathbb{Q}_p$ Langlands, Hecke & $p$-Adics — 🐍 📓 langlands_dual, IwahoriHeckeAlgebra, is_ramanujan_graph, hecke_graph_operator, PAdicField
Duality & Quantum Symmetry Coalgebras & Hopf Algebras — 🐍 📓 Coalgebra, Bialgebra, HopfAlgebra, GroupHopfAlgebra, SimplicialChainCoalgebra, cup_product
Geometric Physics Relativistic Dirac Spinors — 🐍 📓 clifford.CliffordAlgebra(1, 3), even subalgebra $Cl^+(1,3)$, $4\pi$ periodicity, Lorentz boosts
Automatic Differentiation Forward-Mode Autodiff — 🐍 📓 StandardSemiring(DualNumber), quotient ring $\mathbb{R}[\epsilon]/(\epsilon^2)$, matrix.dot
Group Theory & Combinatorics Rubik's Cube Solver — 🐍 📓 group.compose, group.invert, group.signature, commutator surgery
Information & NLP CYK Provenance Parser — 🐍 📓 matrix.dot, semiring.ProvenanceSemiring, probability.entropy
Cryptography & Finite Fields Galois Finite Fields — 🐍 📓 algebra.GaloisField, galois.gf_matrix_mul, QuotientMonoidAlgebraSemiring
Distributed Systems Vector Clocks & CRDTs — 🐍 📓 lattice.combine, ArcticSemiring, BooleanSemiring, causal DAG contractions

Run any recipe directly using uv:

uv run recipes/tropical_algebraic_curves.py

Graphical Desktop Laboratory

Launch the interactive DearPyGui laboratory application featuring 12 interactive modules, live image convolution texture previews, force-directed graph canvases, signal transforms, and information theory calculators:

uv run recipes/lab.py

Documentation

Full documentation is published at erivlis.github.io/algebrax and structured in docs/:


Development & Contributing

Golden Source Recipes & Jupytext Sync

All recipes in recipes/ are authored as Python scripts (.py) using Jupytext Percent format (# %% cell markers) as the canonical Golden Source. Corresponding Jupyter Notebooks (.ipynb) are auto-generated from these scripts.

Pre-Commit Hook Setup

Install the pre-commit hook to automatically sync .ipynb notebooks whenever you modify a .py recipe script:

# Ensure local repository hooks directory is active (recommended if global hooksPath is set)
git config --local core.hooksPath .git/hooks

# Install pre-commit hook
uvx pre-commit install

Manual Sync & Testing

# Refresh all Jupyter notebooks from Golden Source scripts
uvx jupytext --to notebook recipes/*.py

# Run unit tests (or notebook execution tests)
uv run --group test pytest
uv run --group test pytest --nbmake recipes/

License

Distributed under the MIT License. See LICENSE for more information.

Metadata

Release files for algebrax 0.18.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for algebrax 0.18.0
File Size Uploaded Provenance Actions
algebrax-0.18.0.tar.gz 53.9 MB Without provenance Details for algebrax-0.18.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for algebrax 0.18.0
File Interpreter ABI Platform Actions
algebrax-0.18.0-py3-none-any.whl Python 3 none any Details for algebrax-0.18.0-py3-none-any.whl

Total release size: 54.3 MB

Release files / algebrax-0.18.0.tar.gz

Download URL algebrax-0.18.0.tar.gz
Size 53.9 MB
Tags Source
SHA-256 checksum
How to use checksums
d31b94afef89c4b1bf59512f8d86ae313d3caa4c27f60d461219816a0d99fc3f
BLAKE2b-256 checksum
How to use checksums
64da930cecaa309fe9028f010d0d77b72472baaba078a8b8c54239a22d759847
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / algebrax-0.18.0-py3-none-any.whl

Download URL algebrax-0.18.0-py3-none-any.whl
Size 457.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
96e2514577d7b2ae9766ce3713cb96b0f49fb7826476b0e3e137b519010060f1
BLAKE2b-256 checksum
How to use checksums
e022450d571412a132c5685d7f760bd61bc3d48587aa67f52b0ec82e932f382b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for algebrax 0.18.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page