+#include "hmath.h"
+
+int main(void) {
+ if (hmath_init() != HMATH_INIT_OK)
+ return 1;
+ double result = 0.0;
+ hmath_status status = hmath_scalar_add(NULL, 2.0, 3.0, &result);
+ if (status != HMATH_OK) {
+ fprintf(stderr, "%s\n", hmath_last_error_message());
+ return 1;
+ }
+ printf("%.1f\n", result);
+ return hmath_runtime_shutdown() == HMATH_OK ? 0 : 1;
+}
+```
+
+Save it as `example.c` in the checkout, then compile and run:
+
+```sh
+cc -std=c11 example.c -Iinclude -Lbuilddir -lhmath \
+ -Wl,-rpath,"$PWD/builddir" -o example
+./example
+```
+
+The expected output is `5.0`.
+
+## Ownership and errors
+
+- Release each successfully created tensor with `hmath_tensor_release`.
+- Retain a reference before sharing a handle with another independent owner.
+- Check status before reading numerical outputs; outputs are written only
+ on success, except APIs that explicitly report partial batch progress.
+- Copy the thread-local error message before the next checked operation.
+- Shut down only after joining all workers and finishing all library use.
+
+The [C ABI reference](../reference/c.md) contains the complete public header,
+status codes, limits, and callback contracts.
diff --git a/docs/guides/numpy.md b/docs/guides/numpy.md
new file mode 100644
index 0000000..8457c73
--- /dev/null
+++ b/docs/guides/numpy.md
@@ -0,0 +1,46 @@
+# Work with NumPy arrays
+
+Install the `numpy` extra as described in [installation](../getting-started/installation.md).
+
+## Copy an array into a tensor
+
+```python
+import numpy as np
+from hmath import Tensor
+
+source = np.array([[1, 2], [3, 4]], dtype=np.float64)
+with Tensor.from_numpy(source) as tensor:
+ assert tensor.shape == (2, 2)
+ assert np.array_equal(tensor.numpy(), source)
+```
+
+Both conversions copy by default. Later changes to the original array do not
+change the copied tensor, and the returned NumPy array owns independent data.
+
+## Borrow an array without copying
+
+```python
+import numpy as np
+from hmath import Tensor
+
+source = np.arange(12, dtype=np.float64).reshape(3, 4)
+source.setflags(write=False)
+with Tensor.from_numpy(source[:, ::2], copy=False) as tensor:
+ view = tensor.numpy(copy=False)
+ assert tensor.shape == (3, 2)
+ assert tensor.sum() == 30.0
+ assert np.shares_memory(view, source)
+ assert not view.flags.writeable
+```
+
+Zero-copy input requires native-endian, aligned, read-only `float64` storage
+and nonnegative strides that are multiples of eight bytes. Negative-stride
+views and writable arrays are rejected with `ValueError`.
+
+The caller must keep all aliases immutable until every tensor and derived
+view has been released. Setting one array to read-only cannot prevent writes
+through another writable alias.
+
+A NumPy view retains a native reference and its borrowed array owner, so it
+remains valid after the original tensor is closed. Release the view when it
+is no longer needed. Empty arrays can use a separate empty NumPy allocation.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
new file mode 100644
index 0000000..73b5053
--- /dev/null
+++ b/docs/guides/troubleshooting.md
@@ -0,0 +1,50 @@
+# Troubleshooting
+
+## `libhmath.so: cannot open shared object file`
+
+The 1.0.0 Python distribution omitted the native library. Upgrade to 1.0.1
+or newer using your application's interpreter:
+
+```sh
+python -m pip install --upgrade --only-binary=:all: "hmath-python>=1.0.1"
+```
+
+In PyCharm, use the interpreter selected in the project's Python interpreter
+settings. Installing into a different terminal environment does not update
+the project's virtual environment.
+
+If an old developer override is set, remove it before importing:
+
+```sh
+unset HMATH_LIBRARY
+python -c "from hmath import add; print(add(2, 3))"
+```
+
+Do not use an arbitrary system library to mask an incomplete wheel. Report
+failures of the fixed wheel with your Python version, Linux distribution,
+CPU architecture, pip output, and complete traceback.
+
+## `No matching distribution found`
+
+Upgrade pip and check that the environment is Linux x86-64 with glibc 2.28
+or newer. Current wheels do not cover Alpine/musl, ARM, macOS, or Windows.
+See [compatibility](../explanation/releases.md).
+
+## `HMathError`
+
+This means native code loaded and rejected an operation. Inspect `.status`
+and the exception message. Common causes are incompatible shapes, non-finite
+values, an oversized tensor, or a matrix multiplication exceeding its work
+budget. The [reference](../reference/python.md) lists limits and errors.
+
+## `Tensor is closed`
+
+Do not use a tensor after leaving its `with` block or calling `.close()`.
+Keep computations inside the owner block, or create an independent result
+before closing it.
+
+## `HMath runtime was permanently shut down`
+
+Final runtime shutdown is irreversible. Call `shutdown()` only as the process
+owner after all numerical work has finished. Ordinary applications can rely
+on process exit and should not call it after each calculation.
diff --git a/docs/guides/wave.md b/docs/guides/wave.md
new file mode 100644
index 0000000..8121114
--- /dev/null
+++ b/docs/guides/wave.md
@@ -0,0 +1,39 @@
+# Integrate with Wave
+
+The maintained Wave binding is `bindings/wave/hmath.wave`. It calls the same
+C ABI used by Python. Build the native library first using the
+[source-build guide](build.md).
+
+The compiler tested by CI is Wave `v0.2.1-pre-beta`. With `wavec` on `PATH`,
+run the checked-in integration client:
+
+```sh
+python tools/run_wave.py --library builddir/libhmath.so
+```
+
+The client exercises scalar addition, vector and matrix construction,
+arbitrary-rank tensors, matrix multiplication, errors, cloning, and cleanup.
+
+## A scalar call
+
+From a Wave source file placed beside `bindings/wave/hmath.wave`:
+
+```wave
+import("./hmath")::{scalar_add};
+
+fun main() -> i32 {
+ var result: f64 = 0.0;
+ if (scalar_add(2.0, 3.0, &result) != 0 || result != 5.0) {
+ return 1;
+ }
+ return 0;
+}
+```
+
+To integrate your application, copy the binding beside your source or adjust
+its import path, and link `hmath` from the native build directory. The
+checked-in `tools/run_wave.py` shows the tested compiler and linker flags.
+
+Wave does not provide Python's automatic tensor cleanup. Call `tensor_close`
+on every owned tensor, including error paths. See the
+[Wave API reference](../reference/wave.md).
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..5638b0a
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,31 @@
+# HMath documentation
+
+HMath is a mathematics and numerical computing library written in Haskell,
+with officially maintained C, Python, and Wave interfaces.
+
+Start with [installation](getting-started/installation.md), then follow
+[your first calculation](getting-started/first-calculation.md). Use the
+[Python reference](reference/python.md) to look up individual operations.
+
+## Choose an interface
+
+| Interface | Scope | Entry point |
+| --- | --- | --- |
+| Python | Scalar addition; binary64 tensors, matrices, reductions, NumPy views | [Python API](reference/python.md) |
+| C | Stable checked ABI, tensors, contexts, callbacks, CPU DLPack | [C ABI](reference/c.md) |
+| Wave | Checked scalar and tensor operations through the C ABI | [Wave integration](guides/wave.md) |
+| Haskell | Full mathematics and scientific computing modules | [Haskell modules](reference/haskell.md) |
+
+The full Haskell API is larger than the Python and Wave APIs. A function
+being available in Haskell does not imply that a Python wrapper exists.
+
+## Find the right kind of documentation
+
+- **Getting started** teaches an end-to-end calculation.
+- **How-to guides** solve specific integration tasks.
+- **Reference** describes signatures, results, constraints, and errors.
+- **Explanation** describes architecture, ownership, and compatibility.
+
+This documentation accompanies HMath 1.0.1. Linux x86-64 is the supported
+binary distribution target. See [release compatibility](explanation/releases.md)
+for Python versions, ABI compatibility, and the 1.0.0 installation defect.
diff --git a/docs/linear-algebra.md b/docs/linear-algebra.md
new file mode 100644
index 0000000..8064025
--- /dev/null
+++ b/docs/linear-algebra.md
@@ -0,0 +1,75 @@
+# Dense linear algebra
+
+`HMath` re-exports the vector, matrix, and error APIs. They can also be imported independently from `HMath.Linear`, `HMath.Matrix`, and `HMath.Error`.
+
+## Shapes and storage
+
+Matrices store an explicit `(rows, columns)` shape and a flat, row-major list. The constructor is private. `fromListChecked` requires exactly `rows * columns` values; `toList` returns them in the same order. Inputs to list-based APIs must be finite.
+
+Negative dimensions and element counts larger than `maxBound :: Int` are rejected before allocation or element-count validation. This is a representability check, not a promise that every representable matrix fits in memory. Arithmetic follows the selected numeric type; for example, `Int` arithmetic can overflow and floating-point results can be non-finite.
+
+Zero dimensions are supported. `0×0`, `m×0`, and `0×n` retain distinct shapes even though all have empty storage. Transpose swaps both dimensions, and transposing twice restores the original matrix. Multiplying `m×0` by `0×n` produces an `m×n` zero matrix, subject to the same output-size check.
+
+```haskell
+import HMath
+
+emptyProduct :: Either MathError ((Int, Int), [Integer])
+emptyProduct = do
+ a <- fromListChecked 2 0 []
+ b <- fromListChecked 0 3 []
+ result <- multiplyChecked a b
+ pure (shape result, toList result)
+-- Right ((2,3),[0,0,0,0,0,0])
+```
+
+## Checked operations and compatibility
+
+Fallible matrix operations have an `Either MathError` variant ending in `Checked`. Their `Maybe` variants return `Nothing` for the same invalid inputs. Existing signatures of `fromList`, `identity`, `addMatrix`, `multiply`, `transposeMatrix`, `shape`, and `toList` are preserved. The derived `Show` output reflects the flat internal storage and is not a serialization format.
+
+| Operation | Result or requirement |
+| --- | --- |
+| `fromListChecked rows cols values` | Exact row-major element count |
+| `zeroMatrixChecked rows cols` | All-zero matrix |
+| `identityChecked n` | Square identity, including `n = 0` |
+| `diagonalChecked values` | Square matrix with the supplied diagonal and zeros elsewhere |
+| `atChecked matrix row col` | Element at a zero-based index |
+| `sliceMatrixChecked start extent matrix` | Rectangular slice with `(row, col)` start and `(rows, cols)` extent |
+| `reshapeChecked rows cols matrix` | New shape with unchanged row-major element order and count |
+| `addMatrixChecked`, `subtractMatrixChecked`, `hadamardChecked` | Equal shapes; Hadamard multiplies corresponding elements |
+| `multiplyChecked left right` | Left column count equals right row count; output shape is representable |
+| `scaleMatrix scalar matrix` | Scalar multiplication preserving shape |
+| `transposeMatrix matrix` | Shape-preserving transpose, including empty dimensions |
+
+An index must be strictly inside both dimensions. A slice's start and extent must fit inside each dimension. Zero-extent slices may start at the corresponding dimension's endpoint. Bounds checks do not add potentially overflowing indices and extents.
+
+```haskell
+matrixExample :: Either MathError ([Int], [Int])
+matrixExample = do
+ matrix <- fromListChecked 2 3 [1, 2, 3, 4, 5, 6]
+ section <- sliceMatrixChecked (0, 1) (2, 2) matrix
+ reshaped <- reshapeChecked 3 2 matrix
+ pure (toList section, toList reshaped)
+-- Right ([2,3,5,6],[1,2,3,4,5,6])
+```
+
+Errors distinguish negative dimensions, size overflow, element-count mismatch, incompatible shapes or inner dimensions, invalid indices, invalid slices, and unequal vector lengths. `ElementCountMismatch` carries expected then actual counts; bounds errors carry the source shape and requested coordinates. See `HMath.Error` and Haddock for constructor details.
+
+## List-based vectors
+
+`dotChecked`, `addChecked`, and `subtractChecked` require equal list lengths and otherwise return `VectorLengthMismatch leftLength rightLength`. Empty lists are valid: their dot product is zero and their sum/difference is empty. The legacy `dot` and `add` preserve their exception behavior for unequal lengths.
+
+`magnitude`, `normalize`, and `scale` retain their existing behavior. Normalization returns a vector unchanged when its computed magnitude is zero, including the empty vector. No finite-value or arithmetic-overflow policy is added to the underlying numeric type.
+
+```haskell
+dotChecked [1, 2, 3 :: Int] [4, 5, 6] -- Right 32
+addChecked [1 :: Int] [2, 3] -- Left (VectorLengthMismatch 1 2)
+subtractChecked [1, 2 :: Int] [3, 4] -- Right [-2,-2]
+```
+
+## Validation
+
+Run the complete checked-API example from the source tree with `runghc -isrc examples/haskell/Main.hs`.
+
+`cabal test hmath-tests --test-show-details=direct` runs the Haskell suite. `meson test -C builddir --print-errorlogs` runs that suite together with the C/Python integration tests. A Haskell assertion failure makes the Meson test fail.
+
+The suite checks boundary errors and a bounded family of small rectangular matrices, including empty shapes, against independent arithmetic and indexing expectations. It also checks transpose involution, identity products, additive identities, and distributivity using exact integer arithmetic. These are correctness checks, not performance benchmarks or broad floating-point accuracy guarantees.
diff --git a/docs/reference/c.md b/docs/reference/c.md
new file mode 100644
index 0000000..8cf3dfa
--- /dev/null
+++ b/docs/reference/c.md
@@ -0,0 +1,46 @@
+# C ABI reference
+
+The ABI epoch is **1**, independent of the package version. Query it with
+`hmath_abi_version()` and compare it with `HMATH_ABI_VERSION`.
+
+| Area | Public API |
+| --- | --- |
+| Version and diagnostics | `hmath_abi_version`, `hmath_library_version`, `hmath_build_info`, `hmath_backend_version`, `hmath_last_error_code`, `hmath_last_error_message`, `hmath_status_string` |
+| Runtime | `hmath_init`, `hmath_runtime_shutdown`, legacy `hmath_shutdown` |
+| Contexts | `hmath_context_create`, `retain`, `release`, `cancel`, `reset` |
+| Construction | `hmath_tensor_copy`, `hmath_tensor_borrow`, `hmath_vector_copy`, `hmath_matrix_copy` |
+| Lifetime | `hmath_tensor_retain`, `hmath_tensor_release` |
+| Inspection and storage | `hmath_tensor_rank`, `count`, `metadata`, `copy_to`, `data`, `reshape` |
+| Allocation | `hmath_buffer_alloc`, `hmath_buffer_free` |
+| Checked kernels | `hmath_scalar_add`, `hmath_tensor_sum`, `dot`, `add`, `matmul`, `map`, `hmath_batch_sum` |
+| Legacy kernels | `hmath_add_f64`, `hmath_factorial`, `hmath_mean_f64`, `hmath_dot_f64` |
+
+Names abbreviated in the table retain the family prefix. The declarations
+below are included directly from the public header, so signatures and
+ownership comments have a single source of truth.
+
+## Public declarations and contracts
+
+```c
+--8<-- "include/hmath.h"
+```
+
+## CPU DLPack exchange
+
+DLPack exchange is available through the separate public header below. Read
+its ownership-transfer and deleter contracts before exporting or importing
+an array. Only supported CPU tensor layouts are accepted.
+
+```c
+--8<-- "include/hmath_dlpack.h"
+```
+
+## Native backend providers
+
+The native backend header defines provider selection, integer-width contracts,
+and the BLAS/LAPACK bridge. It is an internal adapter contract used by Haskell's
+backend integration, separate from the public ABI-1 tensor API above.
+
+```c
+--8<-- "include/hmath_backend.h"
+```
diff --git a/docs/reference/haskell.md b/docs/reference/haskell.md
new file mode 100644
index 0000000..7d6d8ed
--- /dev/null
+++ b/docs/reference/haskell.md
@@ -0,0 +1,34 @@
+# Haskell modules
+
+Haskell exposes the full HMath numerical API. The
+[generated Haddock reference](https://wavefnd.github.io/hmath/haskell/index.html)
+contains public signatures, types, and module documentation, generated from
+the same source revision as this site.
+
+| Area | Representative modules |
+| --- | --- |
+| Foundations | `HMath`, `HMath.Error`, `HMath.Numeric`, `HMath.Constants`, `HMath.Units` |
+| Algebra | `HMath.Algebra`, `HMath.Polynomial`, `HMath.NumberTheory`, `HMath.Combinatorics` |
+| Linear algebra | `HMath.Linear`, `HMath.Matrix`, `HMath.Matrix.LU`, `HMath.Matrix.QR`, `HMath.Sparse` |
+| Calculus and solvers | `HMath.Calculus`, `HMath.Root`, `HMath.ODE`, `HMath.PDE`, `HMath.Interpolation` |
+| Optimization | `HMath.Optimization`, `HMath.Autodiff` |
+| Statistics | `HMath.Statistics`, `HMath.Probability`, `HMath.Random`, `HMath.TimeSeries` |
+| Learning | `HMath.MachineLearning`, `HMath.DeepLearning` |
+| Transforms and signals | `HMath.Fourier`, `HMath.Signal` |
+| Geometry and images | `HMath.Geometry`, `HMath.Image`, `HMath.Rotation`, `HMath.Quaternion` |
+| Discrete and symbolic | `HMath.Graph`, `HMath.Discrete`, `HMath.Symbolic`, `HMath.Expression` |
+| Arrays and interchange | `HMath.Tensor`, `HMath.Interchange`, `HMath.API` |
+
+The `HMath` facade re-exports selected foundational modules. Import additional
+modules explicitly for other numerical domains. Checked APIs generally
+return `Either MathError`; consult the function signature for the exact
+error and result types.
+
+Build the local API documentation with:
+
+```sh
+cabal haddock lib:hmath --haddock-html --haddock-hyperlink-source
+```
+
+The [dense linear algebra guide](../linear-algebra.md) describes matrix shapes,
+checked operations, and zero-dimensional matrices in more detail.
diff --git a/docs/reference/python.md b/docs/reference/python.md
new file mode 100644
index 0000000..a67a427
--- /dev/null
+++ b/docs/reference/python.md
@@ -0,0 +1,83 @@
+# Python API
+
+Import the primary interface with `import hmath`. Values are finite IEEE 754
+binary64 numbers. Tensors are immutable; operations return new owned tensors.
+
+## Functions and exceptions
+
+| API | Result and contract |
+| --- | --- |
+| `add(a, b) -> float` | Add two finite scalar values; initialize the runtime automatically. |
+| `initialize() -> None` | Idempotent initialization; ordinary tensor operations already call it. |
+| `shutdown() -> None` | Final process-owner operation; join workers first. Cannot reinitialize afterward. |
+| `HMathError(status)` | Native checked-operation failure; `.status` contains the integer C status code and the message describes the failure. |
+
+Python shape validation raises `ValueError`. Native validation and arithmetic
+failures raise `HMathError`; use-after-close and final shutdown errors raise
+`RuntimeError`. Numeric conversion can raise ordinary Python conversion errors.
+
+## Tensor construction
+
+| Signature | Result and constraints |
+| --- | --- |
+| `Tensor(values, shape=None)` | Copy an iterable into native storage; default shape is `(len(values),)`. Explicit shape must have exactly the supplied number of elements. |
+| `Tensor.scalar(value)` | Scalar with rank zero and shape `()`. |
+| `Tensor.matrix(values, rows, columns)` | Rank-two matrix, with values in row-major order. |
+| `Tensor.from_numpy(array, copy=True)` | Preserve shape and copy values into binary64 storage. With `copy=False`, borrow suitable read-only NumPy storage. |
+
+Native limits are rank **8** and **1,048,576** elements. Each dimension must
+be a nonnegative integer; zero-length dimensions are allowed. A scalar has
+one value. Non-finite input is rejected. See the [NumPy guide](../guides/numpy.md)
+for borrowing constraints and alias ownership.
+
+## Tensor operations
+
+| API | Return value and behavior |
+| --- | --- |
+| `tensor.shape` | Tuple of dimensions. |
+| `tensor.values()` | Independent Python list of floats in row-major traversal order. |
+| `tensor.numpy(copy=True)` | NumPy array of the same shape; an independent copy by default. With `copy=False`, a read-only native view retaining storage ownership. |
+| `tensor.sum()` | Scalar sum of elements. |
+| `tensor.dot(other)` | Scalar sum of elementwise products; inputs require identical shapes. |
+| `tensor + other` | Elementwise addition; inputs require identical shapes. No broadcasting. |
+| `tensor @ other` | Rank-two dense matrix multiplication, with matching inner dimensions. Work is limited to 16,777,216 scalar multiply-add steps. |
+| `tensor.reshape(shape)` | New handle sharing the same storage; requires contiguous input and unchanged element count. |
+| `tensor.close()` | Release this handle. Repeated calls are allowed. Other retained owners remain valid. |
+
+Use context managers for deterministic cleanup:
+
+```python
+from hmath import Tensor
+
+with Tensor([1, 2, 3]) as a, Tensor([4, 5, 6]) as b:
+ assert a.dot(b) == 32.0
+ with a + b as result:
+ assert result.values() == [5.0, 7.0, 9.0]
+```
+
+## cffi interface
+
+The optional `hmath_cffi` module provides `add`, `HMathError`, and `Tensor`.
+Its tensor API includes the iterable constructor, `values`, `sum`, `dot`,
+`+`, `@`, `close`, and context-manager cleanup. Its `.shape` is the stored
+shape tuple. NumPy conversion, `reshape`, and the convenience `scalar` and
+`matrix` constructors belong to the primary ctypes interface.
+
+Do not close a cffi tensor concurrently with an operation on that tensor.
+Both wrappers load the same bundled C library and share its runtime.
+
+## Native status codes
+
+| Code | Name | Meaning |
+| --- | --- | --- |
+| 0 | `HMATH_OK` | Success |
+| 1 | `HMATH_INVALID_ARGUMENT` | Invalid argument |
+| 2 | `HMATH_SHAPE_ERROR` | Invalid or incompatible dimensions |
+| 3 | `HMATH_OVERFLOW` | Arithmetic or size overflow |
+| 4 | `HMATH_ALLOCATION_FAILED` | Allocation failed |
+| 5 | `HMATH_RUNTIME_ERROR` | Runtime unavailable |
+| 6 | `HMATH_HASKELL_EXCEPTION` | Contained Haskell exception |
+| 7 | `HMATH_CANCELLED` | Cooperative cancellation |
+| 8 | `HMATH_BOUNDS_ERROR` | Buffer or metadata bounds error |
+| 9 | `HMATH_BUSY` | Active work prevents shutdown |
+| 10 | `HMATH_UNSUPPORTED` | Unsupported operation |
diff --git a/docs/reference/wave.md b/docs/reference/wave.md
new file mode 100644
index 0000000..6b8261f
--- /dev/null
+++ b/docs/reference/wave.md
@@ -0,0 +1,40 @@
+# Wave API
+
+The binding lives in `bindings/wave/hmath.wave` and mirrors the checked C ABI.
+Operations return integer status codes: zero is success. Output arguments
+are valid only when the status reports success.
+
+| Function | Purpose |
+| --- | --- |
+| `Tensor` | Wrapper owning one native tensor reference in its `handle` field. |
+| `initialize` | Verify ABI 1 and initialize the runtime; returns 10 for an unsupported ABI or 5 after final runtime shutdown. |
+| `error_message` | Pointer to the thread-local error message; valid until the next checked C call. |
+| `scalar_add` | Add two `f64` values through an output pointer. |
+| `tensor_empty` | Construct an empty wrapper before using an output argument. |
+| `tensor_copy` | Copy values with explicit dimensions and rank. |
+| `vector_copy` | Copy a vector. |
+| `matrix_copy` | Copy a row-major matrix. |
+| `tensor_values` | Copy values to a caller-provided output buffer. |
+| `tensor_sum`, `tensor_dot` | Scalar reductions. |
+| `tensor_add`, `tensor_matmul` | Create a new tensor result. |
+| `tensor_clone` | Retain an independent native reference. |
+| `tensor_close` | Release the wrapper's reference and reset it. |
+
+Native rank, size, and arithmetic limits are shared with the
+[C ABI](c.md). Use `tensor_clone` when creating another owner: assigning a
+wrapper by value does not automatically retain its handle.
+
+Tensor output arguments must point to an empty wrapper created with
+`tensor_empty()`. A successful constructor or tensor operation transfers one
+owned reference to the output. Close every owned result, including those
+created before a later operation fails.
+
+## Binding source
+
+The maintained declarations and wrappers are included directly:
+
+```text
+--8<-- "bindings/wave/hmath.wave"
+```
+
+See [Wave integration](../guides/wave.md) for compiler and linking instructions.
diff --git a/hmath.cabal b/hmath.cabal
index b10fc3e..4e2efd1 100644
--- a/hmath.cabal
+++ b/hmath.cabal
@@ -2,7 +2,7 @@ cabal-version: 3.0
-- SPDX-License-Identifier: MPL-2.0
name: hmath
-version: 1.0.0
+version: 1.0.1
synopsis: General-purpose mathematics library written in Haskell
description:
HMath is a general-purpose mathematics library written in Haskell.
@@ -19,11 +19,24 @@ extra-source-files:
.clang-format
.github/workflows/publish-python.yml
.github/workflows/validate.yml
+ .github/workflows/python-wheels.yml
+ .github/workflows/docs.yml
+ MANIFEST.in
+ setup.py
+ mkdocs.yml
+ requirements-docs.txt
+ docs/**/*.md
README.md
ROADMAP.md
bindings/python/LICENSE
bindings/python/hmath.py
bindings/python/hmath_cffi.py
+ bindings/python/_hmath_native/__init__.py
+ bindings/python/_hmath_native/licenses/NOTICE
+ bindings/python/_hmath_native/licenses/GHC-LICENSE
+ bindings/python/_hmath_native/licenses/LIBFFI-LICENSE
+ bindings/python/_hmath_native/licenses/GMP-COPYING.LESSERv3
+ bindings/python/_hmath_native/licenses/GMP-COPYINGv3
pyproject.toml
bindings/python/test_bindings.py
bindings/wave/hmath.wave
@@ -62,6 +75,10 @@ extra-source-files:
test/native/header_c99.c
test/native/wrong_abi.c
tools/benchmark.py
+ tools/build_python_wheel.sh
+ tools/check_python_wheel.py
+ tools/build_docs.py
+ tools/check_docs_examples.py
tools/check_abi.py
tools/check_install.py
tools/check_interchange.py
diff --git a/meson.build b/meson.build
index 6679bb0..18b944f 100644
--- a/meson.build
+++ b/meson.build
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: MPL-2.0
-project('hmath', 'c', version: '1.0.0', meson_version: '>=1.3.0',
+project('hmath', 'c', version: '1.0.1', meson_version: '>=1.3.0',
default_options: ['c_std=c11', 'warning_level=2', 'buildtype=release'])
cabal = find_program('cabal')
python = import('python').find_installation('python3')
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..55f04d3
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,59 @@
+site_name: HMath
+site_description: HMath mathematics and numerical computing documentation
+site_url: https://wavefnd.github.io/hmath/
+repo_url: https://github.com/wavefnd/hmath
+repo_name: wavefnd/hmath
+edit_uri: edit/master/docs/
+copyright: HMath contributors · MPL-2.0
+strict: true
+theme:
+ name: material
+ language: en
+ features:
+ - navigation.sections
+ - navigation.top
+ - navigation.footer
+ - content.code.copy
+ palette:
+ - scheme: default
+ primary: indigo
+ toggle:
+ icon: material/brightness-7
+ name: Switch to dark mode
+ - scheme: slate
+ primary: indigo
+ toggle:
+ icon: material/brightness-4
+ name: Switch to light mode
+plugins:
+ - search
+markdown_extensions:
+ - admonition
+ - pymdownx.highlight:
+ anchor_linenums: true
+ - pymdownx.superfences
+ - pymdownx.snippets:
+ check_paths: true
+ - toc:
+ permalink: true
+nav:
+ - Overview: index.md
+ - Getting started:
+ - Installation: getting-started/installation.md
+ - First calculation: getting-started/first-calculation.md
+ - How-to guides:
+ - NumPy interoperability: guides/numpy.md
+ - C integration: guides/c.md
+ - Wave integration: guides/wave.md
+ - Build from source: guides/build.md
+ - Troubleshooting: guides/troubleshooting.md
+ - Dense linear algebra: linear-algebra.md
+ - Explanation:
+ - Architecture and ownership: explanation/architecture.md
+ - Compatibility and releases: explanation/releases.md
+ - Contributing: contributing.md
+ - API Reference:
+ - Python API: reference/python.md
+ - C ABI: reference/c.md
+ - Wave API: reference/wave.md
+ - Haskell API: reference/haskell.md
diff --git a/pyproject.toml b/pyproject.toml
index c2b77fb..7764a50 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "hmath-python"
-version = "1.0.0"
+version = "1.0.1"
description = "Python bindings for the Haskell HMath numerical library"
readme = "README.md"
requires-python = ">=3.9"
@@ -23,11 +23,17 @@ classifiers = [
Homepage = "https://github.com/wavefnd/hmath"
Source = "https://github.com/wavefnd/hmath"
Issues = "https://github.com/wavefnd/hmath/issues"
+Documentation = "https://wavefnd.github.io/hmath/"
[project.optional-dependencies]
cffi = ["cffi>=1.15"]
numpy = ["numpy>=1.22"]
[tool.setuptools]
+include-package-data = false
package-dir = {"" = "bindings/python"}
py-modules = ["hmath", "hmath_cffi"]
+packages = ["_hmath_native"]
+
+[tool.setuptools.package-data]
+_hmath_native = ["licenses/*"]
diff --git a/requirements-docs.txt b/requirements-docs.txt
new file mode 100644
index 0000000..4168f66
--- /dev/null
+++ b/requirements-docs.txt
@@ -0,0 +1,2 @@
+mkdocs==1.6.1
+mkdocs-material==9.8.0
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..fe45773
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,66 @@
+# SPDX-License-Identifier: MPL-2.0
+"""Build platform wheels containing the Python-independent HMath C ABI."""
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+from setuptools import Distribution, setup
+from setuptools.command.bdist_wheel import bdist_wheel
+from setuptools.command.build_py import build_py
+
+
+class NativeBuild(build_py):
+ def run(self):
+ super().run()
+ library = os.environ.get("HMATH_BUILD_LIBRARY")
+ if library:
+ library = Path(library).resolve(strict=True)
+ else:
+ if not shutil.which("ghc") or not shutil.which("cabal"):
+ raise RuntimeError(
+ "Building HMath from source requires GHC and Cabal. "
+ "Use a binary wheel on supported Linux x86-64 systems."
+ )
+ root = Path(__file__).parent.resolve()
+ work = Path(self.build_lib).resolve().parent / "hmath-native"
+ library = work / "libhmath.so"
+ subprocess.run(
+ [
+ sys.executable,
+ str(root / "meson-build.py"),
+ str(root),
+ str(library),
+ "--builddir",
+ str(work / "cabal"),
+ "--offline",
+ ],
+ check=True,
+ )
+ destination = Path(self.build_lib) / "_hmath_native" / "libhmath.so"
+ shutil.copy2(library, destination)
+
+
+class NativeWheel(bdist_wheel):
+ def finalize_options(self):
+ super().finalize_options()
+ self.root_is_pure = False
+
+ def get_tag(self):
+ # ctypes uses the C ABI: one wheel works across Python versions.
+ _, _, platform = super().get_tag()
+ return "py3", "none", platform
+
+
+class NativeDistribution(Distribution):
+ def has_ext_modules(self):
+ # Install the bundled shared library into platlib, never purelib.
+ return True
+
+
+setup(
+ distclass=NativeDistribution,
+ cmdclass={"build_py": NativeBuild, "bdist_wheel": NativeWheel},
+)
diff --git a/src/HMath/Complex.hs b/src/HMath/Complex.hs
index 4dcc569..dbd7fe9 100644
--- a/src/HMath/Complex.hs
+++ b/src/HMath/Complex.hs
@@ -1,10 +1,10 @@
-- SPDX-License-Identifier: MPL-2.0
-{- | Checked finite complex arithmetic over 'Data.Complex'. Angles are radians,
+{- | Checked finite complex arithmetic over "Data.Complex". Angles are radians,
positive rotations are counterclockwise, and logarithms/powers use the principal
branch (argument in (-pi,pi], with IEEE signed-zero behavior inherited from
-'Data.Complex'). Poles, zero reciprocals, and nonfinite results are errors.
-Matrices use the existing row-major 'M.Matrix'; FFTs use the existing negative
+"Data.Complex"). Poles, zero reciprocals, and nonfinite results are errors.
+Matrices use the existing row-major @M.Matrix@; FFTs use the existing negative
forward-exponent convention. The reference matrix budget is 256 per dimension.
-}
module HMath.Complex (
diff --git a/src/HMath/Probability.hs b/src/HMath/Probability.hs
index 8ca1e3e..8117f06 100644
--- a/src/HMath/Probability.hs
+++ b/src/HMath/Probability.hs
@@ -3,10 +3,10 @@
{- | Checked probability models. Gamma uses shape/scale, geometric and negative
binomial count failures before successes, Gumbel/GEV model maxima, Student-t
is standardized, and triangular parameters are lower/mode/upper. Discrete
-densities are zero away from integer support; CDF=P(X<=x), survival=P(X>x).
+densities are zero away from integer support; CDF=P(X\<=x), survival=P(X>x).
Quantiles use inf{x:F(x)>=p}. Log zero is -infinity by contract.
Finite reference summation/integration budgets are explicit in the code.
-DiscreteUniform endpoints must be exactly representable integers (|bound|<=2^53),
+DiscreteUniform endpoints must be exactly representable integers (|bound|\<=2^53),
and Skellam log-mass order is capped at 1000000; CDF tails outside its finite
numerical summation window saturate to zero/one.
-}
@@ -340,7 +340,7 @@ logSumExp xs = let m = maximum xs in if isInfinite m then m else m + log (sum (m
density :: Distribution -> Double -> Either MathError Double
density d x = exp <$> logDensity d x
--- | P(X<=x). Gamma/beta and classical transformed families use analytic special-function identities. Remaining finite-support continuous cases use 2048-panel Simpson integration; Skellam drops a tail beyond 14 standard deviations plus 20 counts.
+-- | P(X\<=x). Gamma/beta and classical transformed families use analytic special-function identities. Remaining finite-support continuous cases use 2048-panel Simpson integration; Skellam drops a tail beyond 14 standard deviations plus 20 counts.
cdf :: Distribution -> Double -> Either MathError Double
cdf d x = do
validateDistribution d
@@ -877,7 +877,7 @@ wishartLogDensity nu scale x = do
- lg
)
--- | Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu<=100000.
+-- | Reference Wishart draw as the sum of nu Gaussian outer products; requires integer nu>=p and nu\<=100000.
sampleWishart :: Int -> Matrix Double -> R.RNG -> Either MathError (Matrix Double, R.RNG)
sampleWishart nu scale r = do
let p = fst (shape scale)
diff --git a/src/HMath/Special.hs b/src/HMath/Special.hs
index 8b301c0..46a0e12 100644
--- a/src/HMath/Special.hs
+++ b/src/HMath/Special.hs
@@ -311,13 +311,13 @@ erfcx x
normalCDF :: Double -> Either MathError Double
normalCDF x = (/ 2) <$> erfc (-x / sqrt 2)
--- | Standard-normal inverse CDF for 0 Either MathError Double
normalQuantile p = do
require (finite p && p > 0 && p < 1) "normal quantile requires 0
0.5 then negate <$> normalQuantile (1 - p) else bisect 100 (-40) 0 p normalCDF
--- | Real inverse error function for -1 Either MathError Double
inverseErf x = do
require (finite x && abs x < 1) "inverseErf requires -1 Double
fact n = product [1 .. fromIntegral n]
--- | Dawson integral for |x|<=100; scaled quadrature below |x|=10, inverse-power asymptotics above.
+-- | Dawson integral for |x|\<=100; scaled quadrature below |x|=10, inverse-power asymptotics above.
dawson :: Double -> Either MathError SFResult
dawson x = do
require (finite x && abs x <= 100) "Dawson supports |x|<=100"
@@ -376,7 +376,7 @@ exponentialIntegral n x = do
estimate answer errorEstimate
{- | Real principal-value Ei for x>0; logarithmic integral li(x)=Ei(log x),
-with the real PV continuation on 0 Either MathError SFResult
logarithmicIntegral x = do
@@ -390,7 +390,7 @@ logarithmicIntegral x = do
value <- series 10000 y (\n t -> t * y * fromIntegral n / fromIntegral ((n + 1) * (n + 1)))
estimate (0.5772156649015329 + log y + sfValue value) (sfError value)
--- | Real Si(x) on |x|<=1000, with its removable singularity explicitly filled at zero.
+-- | Real Si(x) on |x|\<=1000, with its removable singularity explicitly filled at zero.
sineIntegral :: Double -> Either MathError SFResult
sineIntegral x = do
require (finite x && abs x <= 1000) "Si supports |x|<=1000"
@@ -404,7 +404,7 @@ sineIntegral x = do
(\t -> if t == 0 then 1 else sin t / t)
(linearSegments 0 x (max 1 (ceiling (abs x))))
-{- | Real Ci(x) on 0 Either MathError SFResult
@@ -433,7 +433,7 @@ integrateSegments f knots = do
parts <- mapM (uncurry (integrate f)) (zip knots (drop 1 knots))
estimate (sum (map sfValue parts)) (sum (map sfError parts))
-{- | Fresnel (C,S), phase pi*t^2/2, |x|<=100. Phase-sized subintervals prevent
+{- | Fresnel (C,S), phase pi*t^2/2, |x|\<=100. Phase-sized subintervals prevent
oscillatory quadrature aliasing; above |x|=8 inverse-power asymptotics avoid it.
-}
fresnel :: Double -> Either MathError (SFResult, SFResult)
@@ -459,7 +459,7 @@ fresnel x = do
pure (c, ss)
{- | Legendre incomplete elliptic integrals, parameter m (not modulus k),
-real branch |phi|<=pi/2, m<1; Pi additionally n<1.
+real branch |phi|\<=pi/2, m\<1; Pi additionally n\<1.
-}
ellipticF :: Double -> Double -> Either MathError SFResult
ellipticF phi m = elliptic phi m 0 0
@@ -468,7 +468,7 @@ ellipticF phi m = elliptic phi m 0 0
ellipticE :: Double -> Double -> Either MathError SFResult
ellipticE phi m = elliptic phi m 0 1
--- | Legendre third-kind integral with arguments characteristic n, amplitude phi, parameter m; n<1, m<1, |phi|<=pi/2.
+-- | Legendre third-kind integral with arguments characteristic n, amplitude phi, parameter m; n\<1, m\<1, |phi|\<=pi/2.
ellipticPi :: Double -> Double -> Double -> Either MathError SFResult
ellipticPi n phi m = elliptic phi m n 2
@@ -485,7 +485,7 @@ elliptic phi m n kind = do
0
phi
-{- | Real (sn,cn,dn), |u|<=10^6 and 0<=m<1, using periodic amplitude
+{- | Real (sn,cn,dn), |u|\<=10^6 and 0\<=m\<1, using periodic amplitude
inversion. The complete period uses AGM; the argument cap prevents accumulated
period uncertainty from being presented as a resolved large-argument phase.
-}
@@ -516,19 +516,19 @@ jacobiElliptic u m = do
let sn = sgn * sin phi; cn = (if reflected then -1 else 1) * cos phi
pure (sn, cn, sqrt (1 - m * sn * sn))
--- | Integer-order J_n(x) from libm, |n|<=100000 and finite real x.
+-- | Integer-order J_n(x) from libm, |n|\<=100000 and finite real x.
besselJ :: Int -> Double -> Either MathError Double
besselJ n x = do
require (abs (toInteger n) <= 100000 && finite x) "Bessel J integer order budget exceeded"
checked (realToFrac (cJn (fromIntegral n) (realToFrac x)))
--- | Integer-order Y_n(x) from libm, |n|<=100000 and x>0.
+-- | Integer-order Y_n(x) from libm, |n|\<=100000 and x>0.
besselY :: Int -> Double -> Either MathError Double
besselY n x = do
require (abs (toInteger n) <= 100000 && finite x && x > 0) "Bessel Y integer order, x>0 required"
checked (realToFrac (cYn (fromIntegral n) (realToFrac x)))
--- | Modified Bessel I_n(x) via its convergent series, integer order 0..100 and |x|<=700. Overflow is an error.
+-- | Modified Bessel I_n(x) via its convergent series, integer order 0..100 and |x|\<=700. Overflow is an error.
besselI :: Int -> Double -> Either MathError SFResult
besselI n x = do
require (n >= 0 && n <= 100 && finite x && abs x <= 700) "Bessel I order 0..100, |x|<=700"
@@ -538,7 +538,7 @@ besselI n x = do
((x / 2) ^ n / g)
(\k t -> t * x * x / (4 * fromIntegral k * (fromIntegral k + fromIntegral n)))
--- | exp(-|x|)*I_n(x). Uses the power series for |x|<=50 and asymptotics when n<=20 and |x|>n^2.
+-- | exp(-|x|)*I_n(x). Uses the power series for |x|\<=50 and asymptotics when n\<=20 and |x|>n^2.
scaledBesselI :: Int -> Double -> Either MathError SFResult
scaledBesselI n x
| abs x <= 50 = do s <- besselI n x; estimate (exp (-abs x) * sfValue s) (exp (-abs x) * sfError s)
@@ -642,7 +642,7 @@ hankel kind n x = do
pure (j :+ (if kind == 1 then y else -y))
{- | Airy Ai,Bi and derivatives solve y''=x y by convergent Maclaurin series.
-The bounded real reference domain |x|<=8 avoids severe recessive cancellation.
+The bounded real reference domain |x|\<=8 avoids severe recessive cancellation.
-}
airy :: Double -> Either MathError (SFResult, SFResult, SFResult, SFResult)
airy x = do
@@ -661,7 +661,7 @@ airy x = do
(b, bd) = eval (sqrt 3 * a0) (-sqrt 3 * a1)
pure (a, ad, b, bd)
--- | Real Struve H_nu(x) by a convergent series; nu>-3/2 and 0<=x<=30.
+-- | Real Struve H_nu(x) by a convergent series; nu>-3/2 and 0\<=x\<=30.
struve :: Double -> Double -> Either MathError SFResult
struve nu x = do
require (finite (nu + x) && nu > -1.5 && x >= 0 && x <= 30) "Struve H requires nu>-1.5,0<=x<=30"
@@ -671,7 +671,7 @@ struve nu x = do
((x / 2) ** (nu + 1) / (sqrt pi / 2 * g))
(\k t -> -t * x * x / (4 * (fromIntegral k + 0.5) * (fromIntegral k + nu + 0.5)))
--- | Generalized pFq power series. Requires p<=q or p=q+1 with |z|<1 and no nonpositive-integer denominator parameters; finite budget 10000 terms.
+-- | Generalized pFq power series. Requires p\<=q or p=q+1 with |z|\<1 and no nonpositive-integer denominator parameters; finite budget 10000 terms.
hypergeometric :: [Double] -> [Double] -> Double -> Either MathError SFResult
hypergeometric as bs z = do
require
@@ -702,7 +702,7 @@ hypergeometric1F1 a b z
estimate (exp z * sfValue value) (exp z * sfError value)
| otherwise = hypergeometric [a] [b] z
--- | Gauss 2F1(a,b;c;z) in the real power-series disk |z|<1.
+-- | Gauss 2F1(a,b;c;z) in the real power-series disk |z|\<1.
hypergeometric2F1 :: Double -> Double -> Double -> Double -> Either MathError SFResult
hypergeometric2F1 a b c z = hypergeometric [a, b] [c] z
@@ -721,11 +721,11 @@ complex1F1 a b z = go 1 1 1
then Left NonFiniteResult
else if magnitude u < 1e-14 * max 1 (magnitude q) then Right q else go (k + 1) u q
--- | Legendre P_n(x), n=0..1000 and |x|<=1.
+-- | Legendre P_n(x), n=0..1000 and |x|\<=1.
legendre :: Int -> Double -> Either MathError Double
legendre n x = associatedLegendre n 0 x
--- | Associated P_l^m(x) with Condon--Shortley phase, 0<=m<=l<=1000 and |x|<=1.
+-- | Associated P_l^m(x) with Condon--Shortley phase, 0\<=m\<=l\<=1000 and |x|\<=1.
associatedLegendre :: Int -> Int -> Double -> Either MathError Double
associatedLegendre l m x = do
require
@@ -772,7 +772,7 @@ hurwitzZeta s q = do
(sum terms + a ** (1 - s) / (s - 1) + 0.5 * a ** (-s) + sum correction)
(abs (last correction))
--- | Real zeta: Euler--Maclaurin for s>1, Euler-transformed eta for 01, Euler-transformed eta for 0\ Either MathError SFResult
riemannZeta s
| s > 1 = hurwitzZeta s 1
@@ -797,13 +797,13 @@ riemannZeta s
den = 1 - 2 ** (1 - s)
estimate (sum terms / den) (abs (last terms / den) + 1e-14 / abs den)
--- | Real polylog Li_s(z) in the convergent power-series disk |z|<1; no cross-cut continuation is implied.
+-- | Real polylog Li_s(z) in the convergent power-series disk |z|\<1; no cross-cut continuation is implied.
polylogarithm :: Double -> Double -> Either MathError SFResult
polylogarithm s z = do
require (finite (s + z) && abs z < 1) "real polylog power series needs |z|<1"
series 100000 z (\k t -> t * z * (fromIntegral k / fromIntegral (k + 1)) ** s)
--- | Real Li_2(x) for x<=1, with reflection and negative-axis transformations for convergent evaluation.
+-- | Real Li_2(x) for x\<=1, with reflection and negative-axis transformations for convergent evaluation.
dilogarithm :: Double -> Either MathError SFResult
dilogarithm x
| x == 1 = Right (SFResult (pi * pi / 6) 1e-15)
@@ -815,7 +815,7 @@ dilogarithm x
| x > 0.5 && x < 1 = do s <- dilogarithm (1 - x); estimate (pi * pi / 6 - log x * log (1 - x) - sfValue s) (sfError s)
| otherwise = polylogarithm 2 x
--- | Real Lambert W branch 0 or -1, x>=-1/e and x<0 on branch -1, using bounded Halley iteration.
+-- | Real Lambert W branch 0 or -1, x>=-1/e and x\<0 on branch -1, using bounded Halley iteration.
lambertW :: Int -> Double -> Either MathError SFResult
lambertW branch x = do
require
@@ -864,11 +864,11 @@ clausen theta = do
then Right (SFResult 0 0)
else integrate (\u -> if u == 0 then 0 else -2 * x * u * log (abs (2 * sin (x * u * u / 2)))) 0 1
--- | Complete normalized Fermi--Dirac integral F_order(eta), 0<=order<=20, |eta|<=100.
+-- | Complete normalized Fermi--Dirac integral F_order(eta), 0\<=order\<=20, |eta|\<=100.
fermiDirac :: Double -> Double -> Either MathError SFResult
fermiDirac order eta = quantumIntegral False order eta
--- | Complete normalized Bose--Einstein integral, same order range, -100<=eta<=0 and positive order at eta=0.
+-- | Complete normalized Bose--Einstein integral, same order range, -100\<=eta\<=0 and positive order at eta=0.
boseEinstein :: Double -> Double -> Either MathError SFResult
boseEinstein order eta = quantumIntegral True order eta
@@ -895,8 +895,8 @@ quantumIntegral bose order eta = do
{- | Regular and irregular Coulomb waves F_l,G_l. The regular function follows
the convergent hypergeometric representation. G is integrated backwards from
a first-order asymptotic boundary at R>=300 using RK4; its error estimate
-includes the omitted O((l(l+1)+eta^2)/R) term. Real reference domain l<=8,
-|eta|<=3, 0.5<=rho<=30. This is deliberately not a high-accuracy scattering solver.
+includes the omitted O((l(l+1)+eta^2)/R) term. Real reference domain l\<=8,
+|eta|\<=3, 0.5\<=rho\<=30. This is deliberately not a high-accuracy scattering solver.
-}
coulombWave :: Int -> Double -> Double -> Either MathError (SFResult, SFResult)
coulombWave l eta rho = do
@@ -979,7 +979,7 @@ gegenbauer n a x = do
| otherwise =
let j = fromIntegral (k + 1) in go (k + 1) q ((2 * (j + a) * x * q - (j + 2 * a - 1) * p) / (j + 1))
--- | Real D_nu(x) via Kummer's representation; reference |x|<=6, |nu|<=10.
+-- | Real D_nu(x) via Kummer's representation; reference |x|\<=6, |nu|\<=10.
parabolicCylinder :: Double -> Double -> Either MathError SFResult
parabolicCylinder nu x = do
require
@@ -997,7 +997,7 @@ parabolicCylinder nu x = do
{- | Mathieu ce_n (even=True) or se_n, from a 32-term Fourier Galerkin
eigenproblem. ce(0)=1 or se'(0)=1. Error estimates the last coefficient;
-reference 0<=n<=12, |q|<=10, any real x. Characteristic value is returned.
+reference 0\<=n\<=12, |q|\<=10, any real x. Characteristic value is returned.
-}
mathieu :: Bool -> Int -> Double -> Double -> Either MathError (Double, SFResult)
mathieu evenMode n q x = do
@@ -1065,7 +1065,7 @@ choose n k
product [fromIntegral (n - k + 1) .. fromIntegral n] `div` product [1 .. fromIntegral k]
{- | Angular momenta and projections are encoded as doubled integers, allowing
-half-integers exactly. Factorial Racah sums have j<=30 and return selection
+half-integers exactly. Factorial Racah sums have j\<=30 and return selection
rule zeros rather than factorials of negative arguments.
-}
wigner3j :: Int -> Int -> Int -> Int -> Int -> Int -> Either MathError Double
@@ -1172,7 +1172,7 @@ wigner9j js = do
[0 .. 60]
checked (sum terms)
--- | Clebsch--Gordan coefficient through the Condon--Shortley 3j convention; all arguments doubled integers.
+-- | Clebsch--Gordan coefficient \ through the Condon--Shortley 3j convention; all arguments doubled integers.
clebschGordan :: Int -> Int -> Int -> Int -> Int -> Int -> Either MathError Double
clebschGordan j1 m1 j2 m2 j m = do
v <- wigner3j j1 j2 j m1 m2 (-m)
diff --git a/tools/build_docs.py b/tools/build_docs.py
new file mode 100644
index 0000000..c97a149
--- /dev/null
+++ b/tools/build_docs.py
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: MPL-2.0
+"""Build the documentation site and its generated Haskell API reference."""
+
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+root = Path(__file__).resolve().parent.parent
+subprocess.run(
+ [
+ "cabal",
+ "haddock",
+ "lib:hmath",
+ "--offline",
+ "--haddock-html",
+ "--haddock-hyperlink-source",
+ "--haddock-quickjump",
+ "--haddock-html-location=https://hackage.haskell.org/package/$pkg-$version/docs",
+ "--haddock-option=--show=HMath.Geometry.Internal",
+ "--haddock-option=--show=HMath.Image.Core",
+ "--haddock-option=--show=HMath.MachineLearning.Internal",
+ "--haddock-option=--show=HMath.TimeSeries.Core",
+ "--builddir=build-docs/cabal",
+ ],
+ cwd=root,
+ check=True,
+)
+plan = json.loads((root / "build-docs/cabal/cache/plan.json").read_text())
+component = next(
+ unit
+ for unit in plan["install-plan"]
+ if unit.get("pkg-name") == "hmath" and unit.get("component-name") == "lib"
+)
+reference = Path(component["dist-dir"]) / "doc/html/hmath"
+if not (reference / "index.html").is_file():
+ raise SystemExit(f"Haddock reference not found: {reference}")
+subprocess.run(
+ [sys.executable, "-m", "mkdocs", "build", "--strict"], cwd=root, check=True
+)
+shutil.copytree(reference, root / "site/haskell", dirs_exist_ok=True)
diff --git a/tools/build_python_wheel.sh b/tools/build_python_wheel.sh
new file mode 100644
index 0000000..98a1c7e
--- /dev/null
+++ b/tools/build_python_wheel.sh
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: MPL-2.0
+# Run inside the official manylinux_2_28_x86_64 image, with this checkout at /io.
+set -euo pipefail
+
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+cd "$work"
+dnf install -y gmp-devel ncurses-devel libffi-devel
+
+if [ ! -x /opt/ghc/bin/ghc ]; then
+ curl --fail --location --retry 3 -o ghc.tar.xz \
+ https://downloads.haskell.org/~ghc/9.10.3/ghc-9.10.3-x86_64-rocky8-linux.tar.xz
+ echo 'd0504f094b827e64653f8e8d7b4b3029bf7ff026f5091c0b22366dcd1b032f2d ghc.tar.xz' | sha256sum --check
+ tar -xf ghc.tar.xz
+ cd ghc-9.10.3-x86_64-unknown-linux
+ ./configure --prefix=/opt/ghc
+ make install > "$work/ghc-install.log" 2>&1 || { tail -40 "$work/ghc-install.log"; exit 1; }
+ export PATH="/opt/ghc/bin:$PATH"
+ cd "$work"
+ curl --fail --location --retry 3 -o cabal.tar.xz \
+ https://downloads.haskell.org/cabal/cabal-install-3.16.1.0/cabal-install-3.16.1.0-x86_64-linux-rocky8.tar.xz
+ echo '9d3c8be81bfd4c9ddc394ff6995369d5babb8ce431bb8eddda806011a903af69 cabal.tar.xz' | sha256sum --check
+ tar -xf cabal.tar.xz cabal
+ install cabal /usr/local/bin/cabal
+fi
+export PATH="/opt/ghc/bin:$PATH"
+
+python=/opt/python/cp312-cp312/bin/python
+"$python" -m pip install 'build==1.3.0' 'auditwheel==6.8.2' 'patchelf==0.17.2.4'
+"$python" /io/meson-build.py /io "$work/libhmath.so" --builddir "$work/cabal-build" --offline
+cd /io
+HMATH_BUILD_LIBRARY="$work/libhmath.so" "$python" -m build --wheel --outdir "$work/wheels"
+"$python" -m auditwheel repair --strip --plat manylinux_2_28_x86_64 \
+ --wheel-dir /io/dist "$work"/wheels/*.whl
+"$python" -m build --sdist --outdir /io/dist
+"$python" -m auditwheel show /io/dist/*.whl
+
+# An sdist must really build without the wheel staging environment variable.
+mkdir "$work/source"
+tar -xf /io/dist/hmath_python-*.tar.gz -C "$work/source"
+cd "$work"/source/hmath_python-*
+"$python" -m build --wheel --outdir "$work/source-wheel"
diff --git a/tools/check_docs_examples.py b/tools/check_docs_examples.py
new file mode 100644
index 0000000..7870d57
--- /dev/null
+++ b/tools/check_docs_examples.py
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: MPL-2.0
+"""Execute Python examples from the documentation against an installed wheel."""
+
+import re
+from pathlib import Path
+
+root = Path(__file__).resolve().parent.parent
+for path in sorted((root / "docs").rglob("*.md")):
+ namespace = {"__name__": "__main__"}
+ examples = re.findall(
+ r"^```python\n(.*?)^```", path.read_text(), re.MULTILINE | re.DOTALL
+ )
+ for example in examples:
+ # These are executable examples from the checked-out project itself.
+ exec(compile(example, str(path), "exec"), namespace) # noqa: S102
+ if examples:
+ print(f"{path.relative_to(root)}: {len(examples)} Python examples pass")
diff --git a/tools/check_python_wheel.py b/tools/check_python_wheel.py
new file mode 100644
index 0000000..1bf920b
--- /dev/null
+++ b/tools/check_python_wheel.py
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: MPL-2.0
+"""Run from a clean installation, without a source checkout or native overrides."""
+
+import ctypes
+import importlib.metadata
+import os
+import runpy
+import sys
+from pathlib import Path
+
+for variable in ("HMATH_LIBRARY", "LD_LIBRARY_PATH", "PYTHONPATH"):
+ if os.environ.get(variable):
+ raise SystemExit(f"Wheel validation must not set {variable}")
+
+import hmath
+from _hmath_native import library_path
+
+assert "site-packages" in Path(hmath.__file__).parts, hmath.__file__
+library = Path(library_path())
+assert library.is_file() and "site-packages" in library.parts, library
+assert hmath.add(2, 3) == 5.0
+with hmath.Tensor.matrix([1, 2, 3, 4], 2, 2) as tensor:
+ assert tensor.sum() == 10.0
+ with tensor @ tensor as product:
+ assert product.values() == [7.0, 10.0, 15.0, 22.0]
+
+if sys.platform == "linux":
+ # Every loaded Haskell runtime must come from the installed wheel.
+ for line in Path("/proc/self/maps").read_text().splitlines():
+ if "libHS" in line or "libhmath" in line:
+ assert "site-packages" in line, line
+ native = ctypes.CDLL(str(library))
+ assert native.hmath_abi_version() == 1
+ native.hmath_library_version.restype = ctypes.c_char_p
+ assert native.hmath_library_version().decode() == importlib.metadata.version(
+ "hmath-python"
+ )
+
+if len(sys.argv) > 1:
+ runpy.run_path(sys.argv[1], run_name="__main__")
+print(f"Installed wheel verified on Python {sys.version.split()[0]}")