From 8eb7febfbb606453d6436a9cc77bb2ad81530c01 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 28 Oct 2026 21:03:25 +0900 Subject: [PATCH 1/2] fix: ship self-contained Python wheels and documentation site --- .github/workflows/docs.yml | 60 ++ .github/workflows/publish-python.yml | 47 +- .github/workflows/python-wheels.yml | 73 ++ .github/workflows/validate.yml | 58 +- .gitignore | 3 +- CHANGELOG.md | 14 +- MANIFEST.in | 15 + README.md | 6 +- bindings/python/_hmath_native/__init__.py | 23 + .../python/_hmath_native/licenses/GHC-LICENSE | 31 + .../licenses/GMP-COPYING.LESSERv3 | 165 +++++ .../_hmath_native/licenses/GMP-COPYINGv3 | 674 ++++++++++++++++++ .../_hmath_native/licenses/LIBFFI-LICENSE | 21 + bindings/python/_hmath_native/licenses/NOTICE | 14 + bindings/python/hmath.py | 12 +- bindings/python/hmath_cffi.py | 4 +- cbits/native.c | 2 +- docs/contributing.md | 38 + docs/explanation/architecture.md | 47 ++ docs/explanation/releases.md | 40 ++ docs/getting-started/first-calculation.md | 59 ++ docs/getting-started/installation.md | 56 ++ docs/guides/build.md | 48 ++ docs/guides/c.md | 47 ++ docs/guides/numpy.md | 46 ++ docs/guides/troubleshooting.md | 50 ++ docs/guides/wave.md | 39 + docs/index.md | 31 + docs/linear-algebra.md | 75 ++ docs/reference/c.md | 36 + docs/reference/haskell.md | 34 + docs/reference/python.md | 83 +++ docs/reference/wave.md | 32 + hmath.cabal | 19 +- meson.build | 2 +- mkdocs.yml | 59 ++ pyproject.toml | 8 +- requirements-docs.txt | 2 + setup.py | 66 ++ src/HMath/Complex.hs | 6 +- src/HMath/Probability.hs | 8 +- src/HMath/Special.hs | 64 +- tools/build_docs.py | 42 ++ tools/build_python_wheel.sh | 43 ++ tools/check_docs_examples.py | 17 + tools/check_python_wheel.py | 41 ++ 46 files changed, 2235 insertions(+), 125 deletions(-) create mode 100644 .github/workflows/docs.yml create mode 100644 .github/workflows/python-wheels.yml create mode 100644 MANIFEST.in create mode 100644 bindings/python/_hmath_native/__init__.py create mode 100644 bindings/python/_hmath_native/licenses/GHC-LICENSE create mode 100644 bindings/python/_hmath_native/licenses/GMP-COPYING.LESSERv3 create mode 100644 bindings/python/_hmath_native/licenses/GMP-COPYINGv3 create mode 100644 bindings/python/_hmath_native/licenses/LIBFFI-LICENSE create mode 100644 bindings/python/_hmath_native/licenses/NOTICE create mode 100644 docs/contributing.md create mode 100644 docs/explanation/architecture.md create mode 100644 docs/explanation/releases.md create mode 100644 docs/getting-started/first-calculation.md create mode 100644 docs/getting-started/installation.md create mode 100644 docs/guides/build.md create mode 100644 docs/guides/c.md create mode 100644 docs/guides/numpy.md create mode 100644 docs/guides/troubleshooting.md create mode 100644 docs/guides/wave.md create mode 100644 docs/index.md create mode 100644 docs/linear-algebra.md create mode 100644 docs/reference/c.md create mode 100644 docs/reference/haskell.md create mode 100644 docs/reference/python.md create mode 100644 docs/reference/wave.md create mode 100644 mkdocs.yml create mode 100644 requirements-docs.txt create mode 100644 setup.py create mode 100644 tools/build_docs.py create mode 100644 tools/build_python_wheel.sh create mode 100644 tools/check_docs_examples.py create mode 100644 tools/check_python_wheel.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..9e361da --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: MPL-2.0 +name: Documentation + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: documentation-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: requirements-docs.txt + - uses: haskell-actions/setup@7fd2bb5ca789761088fbc831406b2910e47e56f1 # v2 + with: + ghc-version: '9.10.3' + cabal-version: '3.16.1.0' + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: build-docs/cabal + key: docs-haddock-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**') }} + restore-keys: docs-haddock- + - name: Build documentation and Haskell reference + run: | + python -m pip install -r requirements-docs.txt + python tools/build_docs.py + - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 + with: + path: site + + deploy: + if: github.repository == 'wavefnd/hmath' && github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + needs: build + runs-on: ubuntu-24.04 + concurrency: + group: documentation-pages + cancel-in-progress: false + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 diff --git a/.github/workflows/publish-python.yml b/.github/workflows/publish-python.yml index 3f8ac53..14dbec8 100644 --- a/.github/workflows/publish-python.yml +++ b/.github/workflows/publish-python.yml @@ -20,52 +20,7 @@ concurrency: jobs: build: if: github.repository == 'wavefnd/hmath' && github.ref == 'refs/heads/master' - runs-on: ubuntu-24.04 - outputs: - version: ${{ steps.version.outputs.version }} - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - persist-credentials: false - - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 - with: - python-version: '3.12' - - uses: haskell-actions/setup@7fd2bb5ca789761088fbc831406b2910e47e56f1 # v2 - with: - ghc-version: '9.10.3' - cabal-version: '3.16.1.0' - - name: Read package version - id: version - run: | - python - <<'PY' - import os - import pathlib - import tomllib - metadata = tomllib.loads(pathlib.Path('pyproject.toml').read_text()) - with open(os.environ['GITHUB_OUTPUT'], 'a') as output: - print('version=' + metadata['project']['version'], file=output) - PY - - name: Build and validate the distributions - run: | - python -m pip install build twine numpy cffi - python -m build --outdir dist - python -m twine check --strict dist/* - cabal update - python meson-build.py . build-python/libhmath.so build-python/libhmath.so.1 --builddir build-python/cabal - python -m pip install dist/*.whl - HMATH_LIBRARY="$PWD/build-python/libhmath.so" python - <<'PY' - import pathlib - import runpy - import hmath - if 'site-packages' not in pathlib.Path(hmath.__file__).parts: - raise SystemExit('Validation must import the installed wheel') - runpy.run_path('bindings/python/test_bindings.py', run_name='__main__') - PY - - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: python-distributions - path: dist/* - if-no-files-found: error + uses: ./.github/workflows/python-wheels.yml publish: needs: build diff --git a/.github/workflows/python-wheels.yml b/.github/workflows/python-wheels.yml new file mode 100644 index 0000000..240881b --- /dev/null +++ b/.github/workflows/python-wheels.yml @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: MPL-2.0 +name: Python wheels + +on: + push: + branches: [master] + paths-ignore: ['docs/**', 'mkdocs.yml', 'requirements-docs.txt', 'tools/build_docs.py', 'README.md'] + pull_request: + paths-ignore: ['docs/**', 'mkdocs.yml', 'requirements-docs.txt', 'tools/build_docs.py', 'README.md'] + workflow_call: + outputs: + version: + description: Version read from the built package metadata + value: ${{ jobs.build.outputs.version }} + +permissions: + contents: read + +concurrency: + group: python-wheels-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} + +jobs: + build: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Read package version + id: version + run: | + python - <<'PY' + import os, pathlib, tomllib + version = tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'] + with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + print('version=' + version, file=output) + PY + - name: Build self-contained manylinux wheel and source distribution + run: | + docker run --rm --volume "$PWD:/io" \ + quay.io/pypa/manylinux_2_28_x86_64@sha256:e0adf18521ad35192df733a6c62d35df7801957d24e0470238aacecfab2188a3 \ + bash /io/tools/build_python_wheel.sh + python -m pip install twine + python -m twine check --strict dist/* + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: python-distributions + path: dist/* + if-no-files-found: error + + test: + needs: build + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + python: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14'] + container: python:${{ matrix.python }}-slim-bookworm + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6 + with: + name: python-distributions + path: /tmp/hmath-distributions + - name: Verify installation without GHC or a system HMath library + run: | + python -m pip install /tmp/hmath-distributions/*.whl + cd "$RUNNER_TEMP" + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" + python -m pip install numpy cffi + python "$GITHUB_WORKSPACE/tools/check_python_wheel.py" "$GITHUB_WORKSPACE/bindings/python/test_bindings.py" + python "$GITHUB_WORKSPACE/tools/check_docs_examples.py" diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 9018572..5dd3ec6 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -3,12 +3,19 @@ name: Validate on: push: + branches: [master] + paths-ignore: ['docs/**', 'mkdocs.yml', 'requirements-docs.txt', 'tools/build_docs.py', 'README.md'] pull_request: + paths-ignore: ['docs/**', 'mkdocs.yml', 'requirements-docs.txt', 'tools/build_docs.py', 'README.md'] workflow_dispatch: permissions: contents: read +concurrency: + group: validate-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: linux: strategy: @@ -20,17 +27,34 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: haskell-actions/setup@7fd2bb5ca789761088fbc831406b2910e47e56f1 # v2 + id: haskell with: ghc-version: ${{ matrix.ghc }} cabal-version: '3.16.1.0' + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: | + ~/.cabal/packages + ${{ steps.haskell.outputs.cabal-store }} + dist-newstyle + build-ci/cabal + build-interchange/cabal + key: cabal-${{ runner.os }}-${{ matrix.ghc }}-${{ matrix.buildtype }}-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**', 'test/**', 'bench/**') }} + restore-keys: cabal-${{ runner.os }}-${{ matrix.ghc }}-${{ matrix.buildtype }}- - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.12' + cache: pip + cache-dependency-path: pyproject.toml - name: Dependencies run: | sudo apt-get update sudo apt-get install -y liblapacke-dev libopenblas-dev zlib1g-dev cmake ninja-build clang - python -m pip install meson==1.8.5 numpy scipy cffi h5py pyarrow onnx + python -m pip install meson==1.8.5 numpy cffi + - name: Differential validation dependencies + if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' + run: | + python -m pip install scipy h5py pyarrow onnx cabal update - name: Wave compiler if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' @@ -50,14 +74,15 @@ jobs: if [ '${{ matrix.ghc }}' = '9.10.3' ] && [ '${{ matrix.buildtype }}' = release ]; then wave_tests=enabled fi - meson setup build-ci --buildtype=${{ matrix.buildtype }} -Dwerror=true -Dpython_bindings=enabled -Dwave_bindings="$wave_tests" -Dbenchmarks=true + meson setup build-ci --buildtype=${{ matrix.buildtype }} -Doffline=true -Dwerror=true -Dpython_bindings=enabled -Dwave_bindings="$wave_tests" -Dbenchmarks=true meson compile -C build-ci meson test -C build-ci --print-errorlogs python tools/check_install.py build-ci python tools/check_abi.py build-ci/libhmath.so - name: Properties and interchange + if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' run: | - cabal test hmath-properties -fvalidation-frameworks --test-show-details=direct + cabal test hmath-properties -fvalidation-frameworks -fcriterion-benchmarks --test-show-details=direct python tools/check_interchange.py --builddir=build-interchange --require-optional - name: Sanitized metadata and DLPack fuzzing if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' @@ -65,22 +90,8 @@ jobs: - name: Criterion fixture and native benchmark smoke if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' run: | - cabal bench hmath-criterion -fcriterion-benchmarks --benchmark-options='--iters 1' + cabal bench hmath-criterion -fvalidation-frameworks -fcriterion-benchmarks --benchmark-options='--iters 1' python tools/benchmark.py --library=build-ci/libhmath.so --native=build-ci/hmath-native-benchmark --iterations=10 --output=build-ci/benchmark.json - - name: Python distribution validation - if: matrix.ghc == '9.10.3' && matrix.buildtype == 'release' - run: | - python -m pip install build twine - python -m build --outdir dist - python -m twine check --strict dist/* - python -m pip install dist/*.whl - HMATH_LIBRARY="$PWD/build-ci/libhmath.so" python - <<'PY' - import pathlib - import runpy - import hmath - assert 'site-packages' in pathlib.Path(hmath.__file__).parts - runpy.run_path('bindings/python/test_bindings.py', run_name='__main__') - PY - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 if: always() with: @@ -101,8 +112,15 @@ jobs: steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - uses: haskell-actions/setup@7fd2bb5ca789761088fbc831406b2910e47e56f1 # v2 + id: haskell with: ghc-version: '9.10.3' cabal-version: '3.16.1.0' - - run: cabal update - - run: cabal build lib:hmath flib:hmath -f-interchange-zlib --ghc-options="-Wall -Werror" + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: | + ${{ steps.haskell.outputs.cabal-store }} + dist-newstyle + key: cabal-portability-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('hmath.cabal', 'cabal.project', 'src/**', 'cbits/**') }} + restore-keys: cabal-portability-${{ runner.os }}-${{ runner.arch }}- + - run: cabal build --offline lib:hmath flib:hmath -f-interchange-zlib --ghc-options="-Wall -Werror" diff --git a/.gitignore b/.gitignore index fec2924..ff357fd 100644 --- a/.gitignore +++ b/.gitignore @@ -32,4 +32,5 @@ __pycache__/ # Local Cabal overrides /cabal.project.local /cabal.project.local~ -/docs/ +/site/ +/*.egg-info/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ee2d0e4..25e1a87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # Changelog -## 1.0.0 — Unreleased +## 1.0.1 + +- Bundle the native HMath library and required runtime dependencies in the Linux x86-64 Python wheel, fixing import failures after a normal pip installation. +- Validate the same release wheel in clean CPython 3.9–3.14 environments without a system HMath library, GHC, or native-library environment overrides. +- Add a searchable documentation site with installation, guides, language references, and generated Haskell API documentation. +- Cache Haskell builds and dependencies; run differential validation once rather than repeating it across the compiler/build-type matrix. + +## 1.0.0 - Add checked native tensors, ownership and cancellation contracts, and CPU DLPack exchange. - Establish C, Python, and Wave as the officially maintained external interfaces. @@ -9,8 +16,9 @@ - Add integrated validation, benchmarks, native installation checks, and build metadata. The first release covers the implemented Haskell numerical modules and the -C, Python, and Wave interfaces on Linux x86-64. Python distributions contain -bindings and require a separately installed HMath shared library. +C, Python, and Wave interfaces on Linux x86-64. Python distributions in 1.0.0 +contain only bindings and require a separately installed HMath shared library. +Upgrade to 1.0.1 or newer for a self-contained Linux x86-64 Python wheel. Package versions follow SemVer: compatible fixes increment the patch, compatible features increment the minor, and breaking public API changes increment the major. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..a12c9d3 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,15 @@ +include LICENSE README.md CHANGELOG.md ROADMAP.md hmath.cabal cabal.project meson-build.py +include meson.build meson_options.txt mkdocs.yml requirements-docs.txt fourmolu.yaml .clang-format +recursive-include src *.hs +recursive-include cbits *.c *.h +recursive-include include *.h +recursive-include bindings/python/_hmath_native/licenses * +recursive-include bindings/python *.py LICENSE +recursive-include bindings/wave *.wave +recursive-include docs *.md +recursive-include tools *.py *.sh +recursive-include test *.hs *.c *.py *.txt +recursive-include examples *.hs *.c *.py +recursive-include bench *.hs *.c +recursive-include meson *.in +recursive-include .github/workflows *.yml diff --git a/README.md b/README.md index be1d40a..bbebebd 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,14 @@ HMath is a mathematics and numerical computing library with Python bindings, written in Haskell. It also provides native Haskell, C, and Wave interfaces. -The 1.0.0 release targets Linux x86-64. The Python distribution is named **hmath-python** and is imported as `hmath`. +HMath targets Linux x86-64. The Python distribution is named **hmath-python** and is imported as `hmath`. Version 1.0.1 includes the native library and runtime; GHC is not needed to use its Python wheel. ## Python quick start Install the Python package on Linux x86-64: ```sh -pip install hmath-python +python -m pip install --upgrade --only-binary=:all: "hmath-python>=1.0.1" ``` ```python @@ -24,6 +24,8 @@ with Tensor.matrix([1, 2, 3, 4], 2, 2) as matrix: Use `with` to release native resources automatically. Invalid operations raise `HMathError`. Install `hmath-python[numpy,cffi]` for optional NumPy and cffi support. +See the [documentation](https://wavefnd.github.io/hmath/) for installation requirements, tutorials, API reference, and C/Wave integration. + ## Features - **Core math:** checked scalar operations, numeric types, constants, units, number theory, and polynomials. diff --git a/bindings/python/_hmath_native/__init__.py b/bindings/python/_hmath_native/__init__.py new file mode 100644 index 0000000..dfa87a1 --- /dev/null +++ b/bindings/python/_hmath_native/__init__.py @@ -0,0 +1,23 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Locate the wheel's native library, or an explicit developer override.""" + +import ctypes.util +import os +from pathlib import Path + + +def library_path(): + override = os.environ.get("HMATH_LIBRARY") + if override: + return override + bundled = Path(__file__).with_name("libhmath.so") + if bundled.is_file(): + return str(bundled) + # Source checkouts can use a separately built and installed C library. + installed = ctypes.util.find_library("hmath") + if installed: + return installed + raise ImportError( + "HMath's native library is missing. Install a supported hmath-python " + "binary wheel, or build the library when developing from source." + ) diff --git a/bindings/python/_hmath_native/licenses/GHC-LICENSE b/bindings/python/_hmath_native/licenses/GHC-LICENSE new file mode 100644 index 0000000..99fa526 --- /dev/null +++ b/bindings/python/_hmath_native/licenses/GHC-LICENSE @@ -0,0 +1,31 @@ +The Glasgow Haskell Compiler License + +Copyright 2002, The University Court of the University of Glasgow. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +- Neither name of the University nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY COURT OF THE UNIVERSITY OF +GLASGOW AND THE CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +UNIVERSITY COURT OF THE UNIVERSITY OF GLASGOW OR THE CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. diff --git a/bindings/python/_hmath_native/licenses/GMP-COPYING.LESSERv3 b/bindings/python/_hmath_native/licenses/GMP-COPYING.LESSERv3 new file mode 100644 index 0000000..cca7fc2 --- /dev/null +++ b/bindings/python/_hmath_native/licenses/GMP-COPYING.LESSERv3 @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/bindings/python/_hmath_native/licenses/GMP-COPYINGv3 b/bindings/python/_hmath_native/licenses/GMP-COPYINGv3 new file mode 100644 index 0000000..2a00065 --- /dev/null +++ b/bindings/python/_hmath_native/licenses/GMP-COPYINGv3 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/bindings/python/_hmath_native/licenses/LIBFFI-LICENSE b/bindings/python/_hmath_native/licenses/LIBFFI-LICENSE new file mode 100644 index 0000000..7282e79 --- /dev/null +++ b/bindings/python/_hmath_native/licenses/LIBFFI-LICENSE @@ -0,0 +1,21 @@ +libffi - Copyright (c) 1996-2024 Anthony Green, Red Hat, Inc and others. +See source files for details. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/bindings/python/_hmath_native/licenses/NOTICE b/bindings/python/_hmath_native/licenses/NOTICE new file mode 100644 index 0000000..2f8328f --- /dev/null +++ b/bindings/python/_hmath_native/licenses/NOTICE @@ -0,0 +1,14 @@ +HMath binary wheels include an unmodified, dynamically linked GHC 9.10.3 +runtime and its base, ghc-internal, ghc-bignum and ghc-prim libraries. +GHC license: GHC-LICENSE +Source: https://downloads.haskell.org/ghc/9.10.3/ghc-9.10.3-src.tar.xz + +The runtime also uses libffi (MIT license: LIBFFI-LICENSE) and GNU MP +(LGPL version 3 or later: GMP-COPYING.LESSERv3 and GMP-COPYINGv3). +GNU MP and libffi are separate shared libraries; HMath does not statically +link them. Their source distributions and build information are available at: +https://gmplib.org/download/gmp/ +https://github.com/libffi/libffi/releases +https://github.com/pypa/manylinux + +HMath itself is licensed under MPL-2.0; see the distribution's LICENSE. diff --git a/bindings/python/hmath.py b/bindings/python/hmath.py index 62488da..64fea39 100644 --- a/bindings/python/hmath.py +++ b/bindings/python/hmath.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: MPL-2.0 -"""Binary64 HMath ABI 1. Set HMATH_LIBRARY to the installed shared library. +"""Binary64 HMath ABI 1, with its native library included in binary wheels. Tensor owns one native reference. close()/with provide deterministic cleanup; __del__ is a fallback. Arrays are copied by default. from_numpy(copy=False) @@ -10,17 +10,13 @@ """ import ctypes as C -import ctypes.util -import os import threading import weakref from itertools import islice -_lib = C.CDLL( - os.environ.get("HMATH_LIBRARY") - or ctypes.util.find_library("hmath") - or "libhmath.so" -) +from _hmath_native import library_path + +_lib = C.CDLL(library_path()) P, Z, D = C.c_void_p, C.c_size_t, C.c_double diff --git a/bindings/python/hmath_cffi.py b/bindings/python/hmath_cffi.py index 687ff33..25371aa 100644 --- a/bindings/python/hmath_cffi.py +++ b/bindings/python/hmath_cffi.py @@ -1,9 +1,9 @@ # SPDX-License-Identifier: MPL-2.0 """Optional cffi ABI binding; no compiler needed. Explicit close/with cleanup.""" -import os from itertools import islice +from _hmath_native import library_path from cffi import FFI ffi = FFI() @@ -21,7 +21,7 @@ int hmath_tensor_add(void*,const hmath_tensor*,const hmath_tensor*,hmath_tensor**); int hmath_tensor_matmul(void*,const hmath_tensor*,const hmath_tensor*,hmath_tensor**); """) -lib = ffi.dlopen(os.environ.get("HMATH_LIBRARY", "libhmath.so")) +lib = ffi.dlopen(library_path()) try: if lib.hmath_abi_version() != 1: raise RuntimeError("HMath binding requires ABI 1") diff --git a/cbits/native.c b/cbits/native.c index 10e2e01..c60ae8c 100644 --- a/cbits/native.c +++ b/cbits/native.c @@ -31,7 +31,7 @@ const char *hmath_status_string(hmath_status s) { return (unsigned)s < sizeof names / sizeof names[0] ? names[s] : "unknown status"; } uint32_t hmath_abi_version(void) { return HMATH_ABI_VERSION; } -const char *hmath_library_version(void) { return "1.0.0"; } +const char *hmath_library_version(void) { return "1.0.1"; } const char *hmath_build_info(void) { return "HMath ABI 1; C11; GHC threaded RTS; binary64; max-rank=8"; } diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..cdd3ed0 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,38 @@ +# Contributing + +Discuss bugs and proposed changes in +[GitHub issues](https://github.com/wavefnd/hmath/issues). Send pull requests +from a fork to `wavefnd/hmath:master`. HMath is licensed under MPL-2.0. + +## Validate a change + +Run the [source build and tests](guides/build.md) for numerical or native +changes. Match the existing Fourmolu, clang-format, and Python formatting +styles. Explain the behavior change and meaningful validation in the PR. + +Python distribution changes must pass the installed-wheel checks without +`HMATH_LIBRARY`, `LD_LIBRARY_PATH`, or a system HMath/GHC installation. +The same wheel pipeline is required before production publication. + +## Edit the documentation + +Documentation source lives in `docs/`, with navigation and theme configuration +in `mkdocs.yml`. README contains only a brief project overview and quick start; +put detailed instructions here and link to the authoritative explanation. + +```sh +python -m pip install -r requirements-docs.txt +python -m mkdocs serve +``` + +To build the site together with the complete Haskell API reference, install +the Haskell toolchain and run: + +```sh +python tools/build_docs.py +``` + +CI builds with strict validation and deploys the generated `site/` directory +to GitHub Pages after changes reach `master`. Do not commit generated HTML. +Use runnable examples with expected results; distinguish available interfaces +from future or Haskell-only features. diff --git a/docs/explanation/architecture.md b/docs/explanation/architecture.md new file mode 100644 index 0000000..7a23638 --- /dev/null +++ b/docs/explanation/architecture.md @@ -0,0 +1,47 @@ +# Architecture and ownership + +## From Python to Haskell + +The primary Python wrapper uses ctypes to call HMath's C ABI. The C layer +validates sizes, shapes, pointers, and runtime state before calling Haskell +numerical kernels. A binary wheel includes this C library and its required +non-system shared libraries. No Python-version-specific extension module +is needed; supported Python versions use the same C ABI. + +The cffi wrapper and Wave binding call the same ABI. The complete Haskell +library additionally exposes domains that have no Python wrapper yet. + +## Immutable handles, shared storage + +Each native tensor handle owns a reference. Copy constructors own copied +storage; borrowed tensors retain access to caller-owned storage under an +immutability contract. A contiguous reshape creates another owner of the +same storage. Closing one handle does not invalidate another retained owner. + +The Python wrapper protects operations and cleanup with locks. NumPy views +retain both a native reference and any borrowed Python owner. The last +remaining owner releases the storage. Do not mutate borrowed data through +an alias while a tensor or derived view still uses it. + +## Runtime lifetime + +HMath owns one GHC runtime in the process. Initialization is idempotent, +and checked numerical calls reserve the runtime while executing. +Shutdown returns a busy status if calls are active and is irreversible +once it succeeds. Do not combine HMath with independently initialized +GHC libraries in the same process. + +Most Python applications should use tensor context managers and let process +exit end the runtime. Per-tensor cleanup is separate from final runtime +shutdown. + +## Errors and numerical limits + +Checked calls report structured status codes and a thread-local message. +Finite binary64 input, rank and element bounds, and matrix multiplication +work limits keep calls bounded. Cancellation is cooperative; an already +running Haskell kernel is not asynchronously interrupted. + +These contracts detect invalid inputs within the API's documented bounds. +Like other C APIs, they cannot validate arbitrary pointers or prove the +actual size of caller-provided allocations. diff --git a/docs/explanation/releases.md b/docs/explanation/releases.md new file mode 100644 index 0000000..946dea5 --- /dev/null +++ b/docs/explanation/releases.md @@ -0,0 +1,40 @@ +# Compatibility and releases + +## Supported binary target + +| Component | Supported target | +| --- | --- | +| Python wheel | Linux x86-64, glibc 2.28 or newer | +| Python runtime | Python 3.9 or newer; standard CPython 3.9–3.14 tested | +| Native external interfaces | C, Python, Wave | +| Haskell compiler CI | GHC 9.6.7 and 9.10.3 | +| C ABI | Epoch 1 | + +macOS and Windows CI jobs are compilation probes. They do not establish +full runtime or Python binary support. Musl Linux and other architectures +need separate build and runtime validation before official support. + +## Versioning + +HMath follows semantic versioning: compatible fixes increment the patch +version, compatible features the minor version, and breaking public API +changes the major version. The C ABI epoch changes independently when its +calling or ownership contracts require it. + +Version 1.0.1 repairs Python packaging: unlike 1.0.0, its Linux wheel includes +the native library and required runtime dependencies. No new numerical API +is needed for this fix, so it is a patch release. + +## Publication + +The release workflow reads the package version from `pyproject.toml`; +operators do not type it a second time. A common wheel pipeline builds +and tests the distributions before either TestPyPI or production PyPI +publication. Production publication is followed by a matching GitHub tag +and release containing the same distribution files. TestPyPI does not +create a GitHub release. + +Published PyPI filenames cannot be replaced. Fixes to an already published +distribution require a new release. A GitHub release failure after PyPI +publication must be retried at the failed job rather than repeating the +PyPI upload. diff --git a/docs/getting-started/first-calculation.md b/docs/getting-started/first-calculation.md new file mode 100644 index 0000000..fe4df49 --- /dev/null +++ b/docs/getting-started/first-calculation.md @@ -0,0 +1,59 @@ +# Your first calculation + +This tutorial constructs a matrix, multiplies it, and reads the result. +Complete [installation](installation.md) first. + +## Add two scalars + +```python +from hmath import Tensor, add + +assert add(2, 3) == 5.0 +``` + +The Python interface calculates with IEEE 754 binary64 values, corresponding +to C `double`. Results are Python floats. + +## Construct and multiply a matrix + +HMath stores matrix values in row-major order. The list below represents +`[[1, 2], [3, 4]]`. + +```python +from hmath import Tensor + +with Tensor.matrix([1, 2, 3, 4], 2, 2) as matrix: + assert matrix.shape == (2, 2) + assert matrix.sum() == 10.0 + with matrix @ matrix as product: + assert product.shape == (2, 2) + assert product.values() == [7.0, 10.0, 15.0, 22.0] +``` + +The product follows ordinary matrix multiplication: + +```text +[1 2] [1 2] = [ 7 10] +[3 4] [3 4] [15 22] +``` + +Each `with` block releases its tensor when the block ends. Operators create +new tensors; they do not modify their operands. + +## Handle invalid input + +The number of values must equal the product of the dimensions: + +```python +from hmath import HMathError, Tensor + +try: + Tensor([1.0], shape=(2, 2)) +except HMathError as error: + assert error.status == 2 # HMATH_SHAPE_ERROR +else: + raise AssertionError("An invalid shape was accepted") +``` + +Continue with [NumPy interoperability](../guides/numpy.md), or consult +the [complete Python reference](../reference/python.md). diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 0000000..4a36e56 --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,56 @@ +# Installation + +## Requirements + +- Linux on an x86-64 CPU, with glibc 2.28 or newer. +- Python 3.9 or newer; standard CPython 3.9–3.14 is tested in CI. +- A recent pip capable of selecting manylinux wheels. + +The binary wheel includes HMath and the required Haskell runtime libraries. +GHC, Cabal, a C compiler, and an environment variable pointing to a shared +library are not needed for normal Python use. + +## Install into your project + +Use the interpreter belonging to your project or IDE environment: + +```sh +python -m pip install --upgrade pip +python -m pip install --upgrade --only-binary=:all: "hmath-python>=1.0.1" +python -c "from hmath import add; print(add(2, 3))" +``` + +The expected result is `5.0`. The distribution name is `hmath-python`; +the import name is `hmath`. + +`--only-binary=:all:` makes unsupported platforms fail with a package-selection +error instead of unexpectedly attempting a source build. + +For a new environment: + +```sh +python -m venv .venv +. .venv/bin/activate +python -m pip install --upgrade pip +python -m pip install --only-binary=:all: "hmath-python>=1.0.1" +``` + +## Optional integrations + +```sh +python -m pip install --upgrade --only-binary=:all: "hmath-python[numpy,cffi]>=1.0.1" +``` + +NumPy enables array conversion and zero-copy views. The `hmath_cffi` module +provides an alternative cffi wrapper; the default `hmath` module uses ctypes. + +## Upgrade from 1.0.0 + +Version 1.0.0 shipped Python wrappers without the native library. Upgrade using +the command above. Do not copy a random `libhmath.so` into your system library +directory. If `HMATH_LIBRARY` was set as an earlier workaround, remove that +override to let the fixed wheel load its own library. + +For macOS, Windows, musl-based Linux, or another CPU architecture, prebuilt +wheels are not currently supplied. See [building from source](../guides/build.md) +and the [support policy](../explanation/releases.md). diff --git a/docs/guides/build.md b/docs/guides/build.md new file mode 100644 index 0000000..874f3f2 --- /dev/null +++ b/docs/guides/build.md @@ -0,0 +1,48 @@ +# Build from source + +## Native development + +The supported native target is Linux x86-64. Install GHC 9.6.7 or 9.10.3, +Cabal, a C11 compiler, Meson 1.3 or newer, Ninja, and Python 3. +Zlib enables compressed interchange; LAPACKE and BLAS providers are optional +for the corresponding Haskell backends. + +```sh +git clone https://github.com/wavefnd/hmath.git +cd hmath +meson setup builddir --buildtype=release +meson compile -C builddir +meson test -C builddir --print-errorlogs +``` + +The build creates `builddir/libhmath.so` and its ABI-versioned copy. It runs +Haskell and C tests, plus optional Python and Wave tests when their +dependencies are installed. Install NumPy and cffi to run the Python binding +suite; install `wavec` to run Wave integration. + +## Haskell only + +```sh +cabal build lib:hmath +cabal test hmath-tests --test-show-details=direct +``` + +The [Haskell reference](../reference/haskell.md) links all public modules. + +## Reproduce a Python release wheel + +Docker is sufficient; the build installs its pinned toolchain inside the +container and checks the GHC and Cabal download checksums. + +```sh +docker run --rm -v "$PWD:/io" \ + quay.io/pypa/manylinux_2_28_x86_64@sha256:e0adf18521ad35192df733a6c62d35df7801957d24e0470238aacecfab2188a3 \ + bash /io/tools/build_python_wheel.sh +``` + +The wheel and source distribution are written to `dist/`. Auditwheel bundles +required non-system shared libraries and replaces build-machine runtime +paths with paths relative to the installed wheel. + +An sdist build requires GHC, Cabal, and the system toolchain. Unsupported +platforms are not automatically covered by successful source compilation. diff --git a/docs/guides/c.md b/docs/guides/c.md new file mode 100644 index 0000000..467a0c6 --- /dev/null +++ b/docs/guides/c.md @@ -0,0 +1,47 @@ +# Integrate with C + +Build the native library using the [source-build guide](build.md). C programs +use `include/hmath.h`; Python wheel contents are an implementation detail, +not a system C development installation. + +## A checked scalar call + +```c +#include +#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..12b77df --- /dev/null +++ b/docs/reference/c.md @@ -0,0 +1,36 @@ +# 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" +``` 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..b892b20 --- /dev/null +++ b/docs/reference/wave.md @@ -0,0 +1,32 @@ +# 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 | +| --- | --- | +| `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. + +## 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..ac68d8a --- /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 + - Reference: + - Python API: reference/python.md + - C ABI: reference/c.md + - Wave API: reference/wave.md + - Haskell modules: reference/haskell.md + - Dense linear algebra: linear-algebra.md + - Explanation: + - Architecture and ownership: explanation/architecture.md + - Compatibility and releases: explanation/releases.md + - Contributing: contributing.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]}") From e5bc98aad2307b5012532616bc7645036149057f Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 28 Oct 2026 21:13:46 +0900 Subject: [PATCH 2/2] docs: place complete API reference at the bottom of navigation --- docs/reference/c.md | 10 ++++++++++ docs/reference/wave.md | 8 ++++++++ mkdocs.yml | 10 +++++----- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/reference/c.md b/docs/reference/c.md index 12b77df..8cf3dfa 100644 --- a/docs/reference/c.md +++ b/docs/reference/c.md @@ -34,3 +34,13 @@ 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/wave.md b/docs/reference/wave.md index b892b20..6b8261f 100644 --- a/docs/reference/wave.md +++ b/docs/reference/wave.md @@ -6,6 +6,9 @@ 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. | @@ -21,6 +24,11 @@ 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: diff --git a/mkdocs.yml b/mkdocs.yml index ac68d8a..55f04d3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -47,13 +47,13 @@ nav: - Wave integration: guides/wave.md - Build from source: guides/build.md - Troubleshooting: guides/troubleshooting.md - - Reference: - - Python API: reference/python.md - - C ABI: reference/c.md - - Wave API: reference/wave.md - - Haskell modules: reference/haskell.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