From 836c44cd99d79c114e3c24a68170964187206205 Mon Sep 17 00:00:00 2001 From: Simon Beyer <64092903+simonbeyer1@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:47:13 +0100 Subject: [PATCH] build: the checks of the Scientific Python Development Guide: nox sessions, dependency groups, strict pytest with warnings as errors, ruff format, mypy, codespell, pygrep and mdformat hooks, pre-commit.ci settings, zizmor with actions pinned by SHA and minimal permissions; actions checkout 7, setup-python 7, upload-artifact 7, download-artifact 8, upload-pages-artifact 5, deploy-pages 5; the distro job tests the wheel of the run Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 2 + .github/workflows/cd.yml | 48 +- .github/workflows/ci.yml | 13 +- .github/workflows/docs.yml | 13 +- .gitignore | 3 + .pre-commit-config.yaml | 44 + README.md | 23 +- docs/conf.py | 63 +- noxfile.py | 51 + pyproject.toml | 44 +- src/symident/__init__.py | 15 +- src/symident/_core.pyi | 4 + src/symident/api.py | 536 ++++++-- src/symident/detection/bound.py | 47 +- src/symident/detection/classify.py | 54 +- src/symident/detection/closedform.py | 8 +- src/symident/detection/conditions.py | 93 +- src/symident/detection/core.py | 1080 +++++++++++----- src/symident/detection/cq.py | 101 +- src/symident/detection/discrete.py | 820 ++++++++---- src/symident/detection/elim.py | 37 +- src/symident/detection/fewcoef.py | 47 +- src/symident/detection/fiber.py | 1 + src/symident/detection/fieldproof.py | 276 ++-- src/symident/detection/fields.py | 319 +++-- src/symident/detection/finalize.py | 131 +- src/symident/detection/firstint.py | 163 ++- src/symident/detection/forward.py | 231 +++- src/symident/detection/gapcert.py | 20 +- src/symident/detection/gauge.py | 89 +- src/symident/detection/groups.py | 9 +- src/symident/detection/hybrid.py | 540 +++++--- src/symident/detection/inputs.py | 8 +- src/symident/detection/interp.py | 105 +- src/symident/detection/ioproj.py | 75 +- src/symident/detection/monodromy.py | 75 +- src/symident/detection/multiexp.py | 42 +- src/symident/detection/numbase.py | 57 +- .../detection/observability/analysis.py | 906 +++++++++---- .../detection/observability/context.py | 251 +++- src/symident/detection/observability/guard.py | 21 +- .../detection/observability/homotopy.py | 42 +- .../detection/observability/homstate.py | 29 +- src/symident/detection/observability/joint.py | 385 ++++-- .../detection/observability/narrow.py | 255 +++- .../detection/observability/nuisance.py | 5 +- src/symident/detection/observability/plain.py | 106 +- src/symident/detection/observability/proof.py | 299 +++-- .../detection/observability/reconstruct.py | 435 +++++-- src/symident/detection/observability/rest.py | 224 +++- .../detection/observability/select.py | 59 +- src/symident/detection/observability/start.py | 8 +- src/symident/detection/perprime.py | 103 +- src/symident/detection/rank.py | 132 +- src/symident/detection/rationalize.py | 128 +- src/symident/detection/relax.py | 145 ++- src/symident/detection/relevance.py | 22 +- src/symident/detection/restchart.py | 39 +- src/symident/detection/series.py | 4 + src/symident/detection/sparse.py | 43 +- src/symident/detection/startpow.py | 49 +- src/symident/detection/uinputs.py | 34 +- src/symident/detection/verify.py | 25 +- src/symident/detection/work.py | 28 +- src/symident/errors.py | 21 +- src/symident/gfp.py | 51 +- src/symident/install.py | 56 +- src/symident/options.py | 97 +- src/symident/par.py | 2 +- src/symident/petab.py | 306 +++-- src/symident/reduction/absorb.py | 87 +- src/symident/reduction/blocks.py | 276 ++-- src/symident/reduction/branches.py | 22 +- src/symident/reduction/core.py | 542 +++++--- src/symident/reduction/darboux.py | 99 +- src/symident/reduction/expr.py | 16 +- src/symident/reduction/invariants.py | 99 +- src/symident/reduction/linear.py | 42 +- src/symident/reduction/scaling.py | 48 +- src/symident/reduction/sections.py | 187 ++- src/symident/reduction/sign.py | 52 +- src/symident/reduction/solve.py | 188 ++- src/symident/reduction/zero.py | 42 +- src/symident/report.py | 609 ++++++--- src/symident/rexpr.py | 41 +- src/symident/rjson.py | 89 +- src/symident/session.py | 4 +- src/symident/state.py | 39 +- src/symident/sym/algebraic.py | 5 +- src/symident/sym/charts.py | 253 ++-- src/symident/sym/continuation.py | 42 +- src/symident/sym/degrees.py | 6 +- src/symident/sym/direction.py | 35 +- src/symident/sym/domain.py | 1 + src/symident/sym/exact.py | 38 +- src/symident/sym/fields.py | 350 ++--- src/symident/sym/gfpoly.py | 47 +- src/symident/sym/invariants.py | 25 +- src/symident/sym/jets.py | 64 +- src/symident/sym/liecert.py | 7 +- src/symident/sym/linalg.py | 13 +- src/symident/sym/modp.py | 17 +- src/symident/sym/msolve.py | 42 +- src/symident/sym/numfield.py | 3 +- src/symident/sym/parse.py | 77 +- src/symident/sym/recast.py | 641 ++++++---- src/symident/sym/restcheck.py | 57 +- src/symident/sym/restforward.py | 183 ++- src/symident/sym/scaling.py | 172 +-- src/symident/sym/shared.py | 88 +- src/symident/sym/steady.py | 290 +++-- src/symident/sym/supportlift.py | 39 +- src/symident/sym/switching.py | 61 +- src/symident/sym/symbolic.py | 95 +- src/symident/sym/tape.py | 848 +++++++----- src/symident/sym/taylor.py | 3 +- tests/spec_util.py | 60 +- tests/test_certificates.py | 103 +- tests/test_chain_rows.py | 52 +- tests/test_detect.py | 1136 +++++++++++------ tests/test_determinism.py | 32 +- tests/test_discrete.py | 430 +++++-- tests/test_errors.py | 11 +- tests/test_exact.py | 288 +++-- tests/test_experiments.py | 39 +- tests/test_exponential.py | 72 +- tests/test_homotopy.py | 147 ++- tests/test_inputs.py | 8 +- tests/test_install.py | 40 +- tests/test_kernel_modes.py | 51 +- tests/test_kernel_parity.py | 16 +- tests/test_models.py | 48 +- tests/test_monodromy.py | 3 +- tests/test_par.py | 2 + tests/test_petab.py | 128 +- tests/test_projections.py | 77 +- tests/test_reconstruct.py | 59 +- tests/test_reduce.py | 392 ++++-- tests/test_reduce_linear.py | 34 +- tests/test_report.py | 190 ++- tests/test_rest_nonrational.py | 78 +- tests/test_rjson.py | 32 +- tests/test_select.py | 18 +- tests/test_series_start.py | 25 +- tests/test_settings.py | 14 +- tests/test_switching.py | 337 +++-- tests/test_totals.py | 158 ++- tests/test_unknown_inputs.py | 80 +- tests/tjson.py | 3 +- 149 files changed, 13620 insertions(+), 6124 deletions(-) create mode 100755 noxfile.py create mode 100644 src/symident/_core.pyi diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d31a49a..84b1b1b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,6 +5,8 @@ updates: directory: / schedule: interval: monthly + cooldown: + default-days: 7 groups: actions: patterns: ["*"] diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index d8f8c11..3ee4ddc 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -31,6 +31,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name != 'release' }} +permissions: + contents: read + jobs: wheels: name: wheels ${{ matrix.os }} @@ -40,9 +43,11 @@ jobs: matrix: os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, windows-latest] steps: - - uses: actions/checkout@v5 - - uses: pypa/cibuildwheel@v4.3.5 - - uses: actions/upload-artifact@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: wheels-${{ matrix.os }} path: wheelhouse/*.whl @@ -50,9 +55,11 @@ jobs: sdist: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - run: pipx run build --sdist - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: sdist path: dist/*.tar.gz @@ -68,7 +75,8 @@ jobs: fail-fast: false matrix: image: ["fedora:latest", "debian:stable"] - container: ${{ matrix.image }} + # the current release of each distribution, on purpose + container: ${{ matrix.image }} # zizmor: ignore[unpinned-images] steps: - name: Install Python and build tools run: | @@ -78,15 +86,19 @@ jobs: apt-get update && apt-get install -y --no-install-recommends \ python3 python3-venv ca-certificates fi - - uses: actions/checkout@v5 - - uses: actions/download-artifact@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: wheels-ubuntu-latest path: wheelhouse - name: Install the wheel run: | python3 -m venv /opt/venv - /opt/venv/bin/pip install --upgrade pip pytest pytest-xdist + /opt/venv/bin/pip install --upgrade pip pytest pytest-xdist pytest-timeout + # the wheel of this run, never a release of the same version on PyPI + /opt/venv/bin/pip install --no-index --no-deps --only-binary=:all: --find-links wheelhouse symident /opt/venv/bin/pip install --only-binary=:all: --find-links wheelhouse symident - name: Build msolve if: startsWith(matrix.image, 'fedora') @@ -101,7 +113,9 @@ jobs: steps: - name: Install build tools run: dnf install -y --setopt=install_weak_deps=False gcc make m4 diffutils curl xz tar - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Build msolve run: SYMIDENT_LIBS_CACHE=/tmp/msolve SYMIDENT_JOBS=4 sh src/symident/tools/build-msolve.sh @@ -109,15 +123,17 @@ jobs: fedora: name: fedora runs-on: ubuntu-latest - container: fedora:latest + container: fedora:latest # zizmor: ignore[unpinned-images] steps: - name: Install Python and the compilers run: dnf install -y --setopt=install_weak_deps=False python3 python3-devel python3-pip gcc-c++ cmake - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install from source run: | python3 -m venv /opt/venv - /opt/venv/bin/pip install --upgrade pip pytest pytest-xdist + /opt/venv/bin/pip install --upgrade pip pytest pytest-xdist pytest-timeout /opt/venv/bin/pip install . - name: Tests run: cd /tmp && /opt/venv/bin/python -m pytest -q -n auto "$GITHUB_WORKSPACE/tests" @@ -131,13 +147,13 @@ jobs: permissions: id-token: write steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: wheels-* path: dist merge-multiple: true - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: sdist path: dist - - uses: pypa/gh-action-pypi-publish@release/v1 + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6594a73..027d6d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,11 +12,16 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +permissions: + contents: read + jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - run: pipx run pre-commit run --all-files --show-diff-on-failure tests: @@ -28,8 +33,10 @@ jobs: os: [ubuntu-latest, macos-latest, windows-latest] python: ["3.10", "3.15"] steps: - - uses: actions/checkout@v5 - - uses: actions/setup-python@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python }} allow-prereleases: true diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 53e9bfb..e5caca1 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -25,17 +25,22 @@ concurrency: # a deployment to Pages runs to the end cancel-in-progress: ${{ github.event_name == 'pull_request' }} +permissions: + contents: read + jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 - - uses: actions/setup-python@v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - run: pip install ".[docs]" - run: sphinx-build -W -b html docs docs/_build/html - - uses: actions/upload-pages-artifact@v3 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: docs/_build/html @@ -51,4 +56,4 @@ jobs: url: ${{ steps.deploy.outputs.page_url }} steps: - id: deploy - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.gitignore b/.gitignore index 0cb582c..8cfdda3 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ build.ninja .ruff_cache/ docs/_build/ docs/generated/ +.mypy_cache/ +.nox/ +dist/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b93954c..bdde5d7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,11 @@ # `pre-commit install` runs these on every commit; CI runs them on all files. exclude: ^tests/data/ +ci: + autoupdate_commit_msg: "chore(pre-commit): update hooks" + autofix_commit_msg: "style: pre-commit fixes" + autoupdate_schedule: monthly + repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 @@ -18,6 +23,45 @@ repos: rev: v0.17.6 hooks: - id: ruff-check + - id: ruff-format + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v2.4.1 + hooks: + - id: mypy + files: ^src/ + args: [] + + - repo: https://github.com/codespell-project/codespell + rev: v2.4.3 + hooks: + - id: codespell + additional_dependencies: ["tomli; python_version<'3.11'"] + + - repo: https://github.com/pre-commit/pygrep-hooks + rev: v1.10.0 + hooks: + - id: python-check-blanket-noqa + - id: python-check-blanket-type-ignore + - id: python-no-log-warn + - id: python-use-type-annotations + - id: rst-backticks + - id: rst-directive-colons + - id: rst-inline-touching-normal + + # NEWS.md keeps the bullets and wrapping of the release notes + - repo: https://github.com/hukkin/mdformat + rev: 1.0.0 + hooks: + - id: mdformat + args: [--wrap=keep, --compact-tables] + additional_dependencies: [mdformat-gfm] + exclude: ^NEWS\.md$ + + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.33.1 + hooks: + - id: zizmor - repo: local hooks: diff --git a/README.md b/README.md index 7e67e8a..9294378 100644 --- a/README.md +++ b/README.md @@ -53,18 +53,17 @@ the output: ```python import symident as si -m = si.Model({"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, - {"y": "x2"}, known_inputs=["u"]) +m = si.Model({"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, {"y": "x2"}, known_inputs=["u"]) res = si.detect(m, mode="global") print(res) -#> Result: structurally locally identifiable (rank 5 / 5) -#> -#> Global: values with the output of a generic one, counted at random points -#> 2 over the algebraic closure, 1 or 2 in the domain (order 5, stable) -#> exactly 2 values at a generic point, proven -#> sigma1 (exact): k01 -> k12, x1 -> (k01*x2 - k12*x2 + k21*x1)/k21, k12 -> -#> k01; in the domain where (k01*x2 - k12*x2 + k21*x1)/k21 > 0 -#> fundamental domain: k01 < k12 +# > Result: structurally locally identifiable (rank 5 / 5) +# > +# > Global: values with the output of a generic one, counted at random points +# > 2 over the algebraic closure, 1 or 2 in the domain (order 5, stable) +# > exactly 2 values at a generic point, proven +# > sigma1 (exact): k01 -> k12, x1 -> (k01*x2 - k12*x2 + k21*x1)/k21, k12 -> +# > k01; in the domain where (k01*x2 - k12*x2 + k21*x1)/k21 > 0 +# > fundamental domain: k01 < k12 ``` A model with non-identifiable directions prints them as generators, and `res.reduce()` returns @@ -73,8 +72,8 @@ the reparametrization to identifiable parameters; the ## Interface -| | | -|---|---| +| | | +| -- | -- | | `Model(odes, observables, ...)` | ODEs or a reaction network with observables, conditions, events, inputs and switches | | `detect(model, ...)` | rank, identifiability and the non-identifiable directions (`Symmetries` of `Symmetry`) | | `detect(model, mode="global", global_options=...)` | also the count of the values with the same output and the discrete symmetries | diff --git a/docs/conf.py b/docs/conf.py index 4ae8762..86482af 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -65,9 +65,13 @@ def _chapters(doc): # the header lists the pages of the root toctree; the guide and the method also open a menu of their chapters -html_context = {"symident_nav": [(d, _title(d), _chapters(d) if d in ("guide", "method") else []) - for d in ("install", "quickstart", "guide", "method", "api")] - + [("changelog", "Changelog", [])]} +html_context = { + "symident_nav": [ + (d, _title(d), _chapters(d) if d in ("guide", "method") else []) + for d in ("install", "quickstart", "guide", "method", "api") + ] + + [("changelog", "Changelog", [])] +} # citations: numbered in the order cited, in the reference format of IEEE, as on the dMod2 and cppDE sites @@ -107,22 +111,55 @@ def _doi(self): def get_article_template(self, e): return join[ - _authors(), ", ", self._title(), tag("em")[field("journal")], - optional[", vol. ", field("volume")], optional[", no. ", field("number")], - optional[", pp. ", _pages()], optional[", Art. no. ", field("eid")], ", ", field("year"), - self._doi(), "."] + _authors(), + ", ", + self._title(), + tag("em")[field("journal")], + optional[", vol. ", field("volume")], + optional[", no. ", field("number")], + optional[", pp. ", _pages()], + optional[", Art. no. ", field("eid")], + ", ", + field("year"), + self._doi(), + ".", + ] def get_inproceedings_template(self, e): return join[ - _authors(), ", ", self._title(), "in ", tag("em")[field("booktitle")], self._series(), - ", ", field("address"), ": ", field("publisher"), ", ", field("year"), - optional[", pp. ", _pages()], self._doi(), "."] + _authors(), + ", ", + self._title(), + "in ", + tag("em")[field("booktitle")], + self._series(), + ", ", + field("address"), + ": ", + field("publisher"), + ", ", + field("year"), + optional[", pp. ", _pages()], + self._doi(), + ".", + ] def get_book_template(self, e): return join[ - _authors(), ", ", tag("em")[field("title")], optional[", ", field("edition"), " ed."], - self._series(), ". ", field("address"), ": ", field("publisher"), ", ", field("year"), - self._doi(), "."] + _authors(), + ", ", + tag("em")[field("title")], + optional[", ", field("edition"), " ed."], + self._series(), + ". ", + field("address"), + ": ", + field("publisher"), + ", ", + field("year"), + self._doi(), + ".", + ] register_plugin("pybtex.style.formatting", "ieee", _IEEE) diff --git a/noxfile.py b/noxfile.py new file mode 100755 index 0000000..573cb51 --- /dev/null +++ b/noxfile.py @@ -0,0 +1,51 @@ +#!/usr/bin/env -S uv run --script +# /// script +# dependencies = ["nox>=2025.2.9"] +# /// +"""Development sessions: `nox -s lint`, `nox -s tests`, `nox -s docs`, `nox -s build`.""" + +import shutil +from pathlib import Path + +import nox + +nox.needs_version = ">=2025.2.9" +nox.options.default_venv_backend = "uv|virtualenv" + +DIR = Path(__file__).parent.resolve() +PYPROJECT = nox.project.load_toml(DIR / "pyproject.toml") + + +@nox.session(default=True) +def lint(session: nox.Session) -> None: + """The pre-commit hooks on all files.""" + session.install("pre-commit") + session.run("pre-commit", "run", "--all-files", "--show-diff-on-failure", *session.posargs) + + +@nox.session(default=True) +def tests(session: nox.Session) -> None: + """The test suite against a source build; arguments go to pytest.""" + session.install(str(DIR), *nox.project.dependency_groups(PYPROJECT, "test")) + # outside the checkout, so that the tests import the installed package + session.chdir(session.create_tmp()) + session.run("pytest", "-n", "auto", str(DIR / "tests"), *session.posargs) + + +@nox.session(reuse_venv=True, default=False) +def docs(session: nox.Session) -> None: + """The documentation as HTML in docs/_build/html, warnings as errors.""" + session.install(str(DIR), *nox.project.dependency_groups(PYPROJECT, "docs")) + session.run("sphinx-build", "-W", "-b", "html", str(DIR / "docs"), str(DIR / "docs/_build/html"), *session.posargs) + + +@nox.session(default=False) +def build(session: nox.Session) -> None: + """The sdist and the wheel in dist/.""" + shutil.rmtree(DIR / "dist", ignore_errors=True) + session.install("build") + session.run("python", "-m", "build", str(DIR), "--outdir", str(DIR / "dist"), *session.posargs) + + +if __name__ == "__main__": + nox.main() diff --git a/pyproject.toml b/pyproject.toml index 29d01d2..db5e319 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,9 +40,15 @@ Issues = "https://github.com/dModverse/symident/issues" [project.optional-dependencies] petab = ["python-libsbml>=5.20", "pyyaml>=6"] -test = ["pytest>=8", "pytest-xdist", "pytest-timeout", "python-libsbml>=5.20", "pyyaml>=6"] +test = ["pytest>=9", "pytest-xdist", "pytest-timeout", "python-libsbml>=5.20", "pyyaml>=6"] docs = ["sphinx>=8", "numpydoc", "pydata-sphinx-theme", "myst-parser", "sphinxcontrib-bibtex>=2.6"] +# the extras above stay for `pip install symident[test]`; the groups serve uv, nox and `pip install --group` +[dependency-groups] +test = ["pytest>=9", "pytest-xdist", "pytest-timeout", "python-libsbml>=5.20", "pyyaml>=6"] +docs = ["sphinx>=8", "numpydoc", "pydata-sphinx-theme", "myst-parser", "sphinxcontrib-bibtex>=2.6"] +dev = [{ include-group = "test" }, { include-group = "docs" }, "nox", "pre-commit"] + [tool.scikit-build] wheel.packages = ["src/symident"] cmake.build-type = "Release" @@ -60,14 +66,48 @@ test-skip = "cp311-* cp312-* cp313-* cp314-*" test-command = 'pytest -q -n auto {project}/tests' [tool.pytest.ini_options] +minversion = "9" testpaths = ["tests"] +addopts = ["-ra", "--strict-markers", "--strict-config"] +xfail_strict = true +log_level = "INFO" +# the fork warning of Python and the warnings symident emits by design, in tests that do not assert them; +# a colon in a message is written as "." +filterwarnings = [ + "error", + 'ignore:This process \(pid=\d+\) is multi-threaded, use of fork\(\) may lead to deadlocks:DeprecationWarning', + "ignore:estimated parameters without effect on the model as fitted:UserWarning", + 'ignore:equilibrate. at \d+ of \d+ random parameter values the resting balances have no solution:UserWarning', + "ignore:`positive` names .* (is|are) no symbol of the model:UserWarning", + "ignore:the default positive=True decides the sign of:UserWarning", + "ignore:`verify`. the rank still grows past the Lie or gap order:UserWarning", + "ignore:no effect. .*not a coordinate of the analysis:UserWarning", + "ignore:a direction is verified, not proven:UserWarning", + "ignore:a direction is checked at random points only:UserWarning", +] # a test that runs past this many seconds is a failure, not a hang timeout = 900 [tool.ruff] line-length = 120 -target-version = "py310" + +[tool.ruff.format] +exclude = ["tests/data/**"] [tool.ruff.lint] select = ["E", "F", "W", "I", "B", "UP", "N8"] ignore = ["E741", "N802", "N803", "N806", "B905", "UP031", "B023"] + +[tool.mypy] +files = ["src"] +python_version = "3.10" +strict = false +ignore_missing_imports = true +warn_unused_configs = true +warn_unreachable = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] + +[tool.codespell] +# identifiers (series, numerator, equilibrate, inhibitor, closure) and author names in refs.bib +ignore-words-list = "ane,bu,clos,equil,fo,hass,inh,loos,mis,nd,numer,ser,statics,te,theis" +skip = "tests/data/*" diff --git a/src/symident/__init__.py b/src/symident/__init__.py index aba44a1..de07c06 100644 --- a/src/symident/__init__.py +++ b/src/symident/__init__.py @@ -6,6 +6,17 @@ from .petab import PEtabError, read_petab from .state import switches -__all__ = ["Model", "Symmetries", "Symmetry", "Reduction", "detect", "reduce", "read_petab", "PEtabError", - "reconst_control", "install_msolve", "switches"] +__all__ = [ + "Model", + "Symmetries", + "Symmetry", + "Reduction", + "detect", + "reduce", + "read_petab", + "PEtabError", + "reconst_control", + "install_msolve", + "switches", +] __version__ = "0.18.1" diff --git a/src/symident/_core.pyi b/src/symident/_core.pyi new file mode 100644 index 0000000..ed68ffd --- /dev/null +++ b/src/symident/_core.pyi @@ -0,0 +1,4 @@ +# The pybind11 extension built from cpp/; the functions are untyped. +from typing import Any + +def __getattr__(name: str) -> Any: ... diff --git a/src/symident/api.py b/src/symident/api.py index adc281a..fc31763 100644 --- a/src/symident/api.py +++ b/src/symident/api.py @@ -17,8 +17,16 @@ # the types _data_copy() returns as they are _ATOMS = frozenset((str, int, float, bool, type(None))) # the settings global_options of detect() takes -_GLOBAL_OPTIONS = ("order", "points", "memory", "experiments", "msolve_entries", "msolve_terms", "search_entries", - "elimination_terms") +_GLOBAL_OPTIONS = ( + "order", + "points", + "memory", + "experiments", + "msolve_entries", + "msolve_terms", + "search_entries", + "elimination_terms", +) def _rhs_from_reactions(species, smatrix, rates): @@ -96,9 +104,26 @@ class Model: The default of :func:`detect`'s ``reduce_cq`` for this model. """ - def __init__(self, odes=None, observables=None, *, reactions=None, totals=None, trafo=None, - conditions=None, events=None, inputs=(), unknown_inputs=(), known_inputs=(), fixed=(), - parameters=(), regimes=None, equilibrate=None, positive=None, reduce_cq=None): + def __init__( + self, + odes=None, + observables=None, + *, + reactions=None, + totals=None, + trafo=None, + conditions=None, + events=None, + inputs=(), + unknown_inputs=(), + known_inputs=(), + fixed=(), + parameters=(), + regimes=None, + equilibrate=None, + positive=None, + reduce_cq=None, + ): derived = None if reactions is not None: sp = list(reactions["species"]) @@ -106,13 +131,16 @@ def __init__(self, odes=None, observables=None, *, reactions=None, totals=None, rates = [str(r) for r in reactions["rates"]] shape = np.asarray(Sm, dtype=float).shape if shape != (len(rates), len(sp)): - raise InputError(f"`stoichiometry` has shape {shape}, but {len(rates)} rate(s) and {len(sp)} " - "species need one row per reaction and one column per species") + raise InputError( + f"`stoichiometry` has shape {shape}, but {len(rates)} rate(s) and {len(sp)} " + "species need one row per reaction and one column per species" + ) self.reactions = {"species": sp, "smatrix": np.asarray(Sm, dtype=float).tolist(), "rates": rates} if odes is None: odes = _rhs_from_reactions(sp, Sm, self.reactions["rates"]) if totals is None: from .detection.cq import conserved_totals + derived = conserved_totals(Sm, sp) else: self.reactions = None @@ -124,8 +152,10 @@ def __init__(self, odes=None, observables=None, *, reactions=None, totals=None, self.odes = {str(k): str(v) for k, v in odes.items()} if totals is None: from .detection.cq import conserved_totals_of_odes, exact_totals - totals = (exact_totals(derived, self.odes) if reactions is not None - else conserved_totals_of_odes(self.odes)) or None + + totals = ( + exact_totals(derived, self.odes) if reactions is not None else conserved_totals_of_odes(self.odes) + ) or None self.observables = observables self.totals = totals self.trafo = trafo @@ -145,15 +175,25 @@ def __init__(self, odes=None, observables=None, *, reactions=None, totals=None, def from_petab(cls, path): """The model of a PEtab problem; see :func:`read_petab`.""" from .petab import read_petab + return read_petab(path) def _kwargs(self): - return dict(f=self.odes, g=self.observables, trafo=self.trafo, conditions=self.conditions, - events=self.events, forcings=self.inputs or None, fixed=self.fixed or None, - parameters=self.parameters or None, reactions=self.reactions, - totals=self.totals, regimes=self.regimes, - unknown_inputs=self.unknown_inputs or None, - known_inputs=getattr(self, "known_inputs", None) or None) + return dict( + f=self.odes, + g=self.observables, + trafo=self.trafo, + conditions=self.conditions, + events=self.events, + forcings=self.inputs or None, + fixed=self.fixed or None, + parameters=self.parameters or None, + reactions=self.reactions, + totals=self.totals, + regimes=self.regimes, + unknown_inputs=self.unknown_inputs or None, + known_inputs=getattr(self, "known_inputs", None) or None, + ) @contextlib.contextmanager @@ -165,7 +205,6 @@ def _trace(on): yield - def _data_copy(x): """A deep copy of `x` that copies dicts, lists and tuples of strings and numbers without the memo of copy.deepcopy.""" @@ -260,6 +299,7 @@ def sympy(self): Coordinate to expression; ``None`` without a closed form. """ from .sym.parse import model_sympify + if self.get("generator") is None: return None return {k: model_sympify(v) for k, v in self["generator"].items()} @@ -410,19 +450,32 @@ def solution_count(self, order=None): Where msolve is not found (:func:`install_msolve`). """ from .detection.fiber import solution_count + if self.model is None or not self.identifiable: raise ValueError("solution_count() needs a locally identifiable result of detect() on a Model") n = len(self.info["coordinates"]) order = int(order or 2 * n) from .sym.switching import _SWITCHY + st = self.info.get("settings") or {} if st.get("equilibrate") or st.get("reduce_cq"): raise ValueError("solution_count() needs a result of detect() without equilibrate and reduce_cq") - if any(_SWITCHY.search(str(v)) for v in list(self.model.odes.values()) + [ - str(e) for o in (self.model.observables if isinstance(self.model.observables, (list, tuple)) - else [self.model.observables]) for e in dict(o).values()]): + if any( + _SWITCHY.search(str(v)) + for v in list(self.model.odes.values()) + + [ + str(e) + for o in ( + self.model.observables + if isinstance(self.model.observables, (list, tuple)) + else [self.model.observables] + ) + for e in dict(o).values() + ] + ): raise ValueError("solution_count() handles models without switches") from .detection.rationalize import NotRationalError + try: got = self._fiber_parts(order, "solution_count()", switches=False) except NotRationalError: @@ -436,8 +489,18 @@ def solution_count(self, order=None): f, g, ic = seg["f"], seg["g"], seg["ic"] return solution_count(f, g, ic, list(self.info["coordinates"]), order) - def discrete(self, order=None, points=5, cores=1, memory=None, experiments=None, msolve_entries=None, - msolve_terms=None, search_entries=None, elimination_terms=None): + def discrete( + self, + order=None, + points=5, + cores=1, + memory=None, + experiments=None, + msolve_entries=None, + msolve_terms=None, + search_entries=None, + elimination_terms=None, + ): """The discrete symmetries: other values of the coordinates in the domain with the same output. The Taylor coefficients of the observables up to `order` are equated with their values at @@ -538,8 +601,13 @@ def discrete(self, order=None, points=5, cores=1, memory=None, experiments=None, Where msolve is not found (:func:`install_msolve`). """ from .detection import work - limits = {"msolve_entries": msolve_entries, "msolve_terms": msolve_terms, "search_entries": search_entries, - "elimination_terms": elimination_terms} + + limits = { + "msolve_entries": msolve_entries, + "msolve_terms": msolve_terms, + "search_entries": search_entries, + "elimination_terms": elimination_terms, + } for k, v in limits.items(): if v is not None and (isinstance(v, bool) or not isinstance(v, (int, float)) or v < 1): raise InputError(f"`{k}` must be a positive number, not {v!r}") @@ -548,17 +616,22 @@ def discrete(self, order=None, points=5, cores=1, memory=None, experiments=None, def _discrete(self, order, points, cores, experiments=None): from .detection.discrete import analyze + if self.model is None or self.identifiable is None: raise ValueError("discrete() needs a result of detect() on a Model") if not self.identifiable: from .detection.relax import terms_of_states + obs = self.model.observables if isinstance(obs, dict) and terms_of_states(self.model.odes, obs): # the relaxed model is rational: the directions reduce there, without a reduction of this model try: - out = self._relaxed_discrete(ValueError("discrete() needs a model rational in the states"), - order=order, points=points, - cores=cores) + out = self._relaxed_discrete( + ValueError("discrete() needs a model rational in the states"), + order=order, + points=points, + cores=cores, + ) if not (out["info"].get("certificate") or {}).get("relaxed_why"): return out except ValueError: @@ -569,20 +642,24 @@ def _discrete(self, order, points, cores, experiments=None): except ValueError as exc: from .detection.rationalize import _blocking from .sym.parse import model_sympify + obs = self.model.observables texts = list(self.model.odes.values()) + (list(dict(obs).values()) if isinstance(obs, dict) else []) if all(_blocking(model_sympify(str(t))) is None for t in texts): raise # a direction the reduction does not remove can be a scaling of the relaxed model - return self._relaxed_discrete(exc, order=order, points=points, cores=cores, - experiments=experiments) + return self._relaxed_discrete(exc, order=order, points=points, cores=cores, experiments=experiments) out = red.discrete(order=order, points=points, cores=cores, experiments=experiments) - out["info"]["reduced"] = {"trafo": red.model.trafo, "fixed": list(red.model.fixed or []), - "coordinates": list(red.info["coordinates"]), - "section": getattr(red, "_section", None)} + out["info"]["reduced"] = { + "trafo": red.model.trafo, + "fixed": list(red.model.fixed or []), + "coordinates": list(red.info["coordinates"]), + "section": getattr(red, "_section", None), + } return self._keep_discrete(out) coords = list(self.info["coordinates"]) from .detection.rationalize import NotRationalError + try: # the jets of known inputs reach past the highest order the count may take parts, rw = self._fiber_parts(int(order or 2 * len(coords)), "discrete()") @@ -594,13 +671,23 @@ def _discrete(self, order, points, cores, experiments=None): # X = b^theta is positive whatever the domain of theta positive = list(declared(positive)[0] or ()) + [str(x) for x in declared(positive)[1]] + list(rw["logs"]) from .sym.msolve import msolve_threads + with msolve_threads(cores): - out = analyze(parts, coords, positive, rw["states"], order=order, - start=self.info.get("lie_order_used"), points=points, - inputs=[str(u) for u in getattr(self.model, "known_inputs", None) or []], - experiments=experiments) - out["info"]["limits"] = ["the counts are at random points: the count over the algebraic closure modulo " - "a prime, the real count at rational points"] + out["info"]["limits"] + out = analyze( + parts, + coords, + positive, + rw["states"], + order=order, + start=self.info.get("lie_order_used"), + points=points, + inputs=[str(u) for u in getattr(self.model, "known_inputs", None) or []], + experiments=experiments, + ) + out["info"]["limits"] = [ + "the counts are at random points: the count over the algebraic closure modulo " + "a prime, the real count at rational points" + ] + out["info"]["limits"] out["info"]["rewrites"] = rw["rewrites"] if rw["eliminated"]: out["info"]["eliminated"] = {x: v.replace("**", "^") for x, v in rw["eliminated"].items()} @@ -610,11 +697,13 @@ def _discrete(self, order, points, cores, experiments=None): out["info"]["limits"].append( "the totals " + ", ".join(free) + " are coordinates; the domain holds them in their declared " "signs, not the species " + ", ".join(rw["eliminated"]) + " solved through them " - "(info['discrete']['eliminated']), so count_domain stands only at 1") + "(info['discrete']['eliminated']), so count_domain stands only at 1" + ) if (out["info"].get("count_domain") or 1) > 1: out["info"]["count_domain"] = None if rw["logs"]: from .detection.rationalize import report_given + report_given(out, rw["logs"]) return self._keep_discrete(out) @@ -631,6 +720,7 @@ def _relaxed_discrete(self, exc, **opts): the count of the model, which is proven where the new coordinates are absorbed or independent and the maps keep the starts of the new states (docs/method/global.rst, "Rational form of the fiber").""" from .detection.relax import independent_leaves, keeps_leaves, relax, scalings_keep_leaves + if getattr(self, "_relaxed", False): # a relaxed model is not relaxed again raise exc @@ -638,9 +728,14 @@ def _relaxed_discrete(self, exc, **opts): st = self.info.get("settings") or {} obs = m.observables equil = bool(st.get("equilibrate")) - if (m.events and not equil) or m.conditions or isinstance(obs, (list, tuple)) or \ - isinstance(m.trafo, (list, tuple)) or self.info.get("switching") or (equil and ( - m.known_inputs or set(m.trafo or {}) & set(m.odes))): + if ( + (m.events and not equil) + or m.conditions + or isinstance(obs, (list, tuple)) + or isinstance(m.trafo, (list, tuple)) + or self.info.get("switching") + or (equil and (m.known_inputs or set(m.trafo or {}) & set(m.odes))) + ): raise exc coords = list(self.info["coordinates"]) odes, trafo, positive, events, chart = m.odes, m.trafo, st.get("positive", True), None, None @@ -648,52 +743,89 @@ def _relaxed_discrete(self, exc, **opts): if equil: # the resting values inside transcendental terms become coordinates from .detection.restchart import rest_chart - chart = rest_chart(m.odes, dict(obs), list(m.inputs or []), coords, positive, list(m.fixed or []), - m.events or [], m.trafo or {}) + + chart = rest_chart( + m.odes, + dict(obs), + list(m.inputs or []), + coords, + positive, + list(m.fixed or []), + m.events or [], + m.trafo or {}, + ) odes, obs, trafo, positive = chart["odes"], chart["observables"], chart["trafo"], chart["positive"] coords, events = chart["coordinates"], chart["events"] or None rx = relax(odes, dict(obs), trafo, coords, list(m.known_inputs or []), positive) - except ValueError as why: - raise ValueError(f"{exc}; the relaxation does not apply: {why}") from None + except ValueError as err: + raise ValueError(f"{exc}; the relaxation does not apply: {err}") from None fixed = [p for p in m.fixed or [] if p not in rx["dropped"]] + rx["known"] - mr = Model(rx["odes"], rx["observables"], trafo=rx["trafo"], known_inputs=rx["inputs"], fixed=fixed, - positive=rx["positive"], events=events) + mr = Model( + rx["odes"], + rx["observables"], + trafo=rx["trafo"], + known_inputs=rx["inputs"], + fixed=fixed, + positive=rx["positive"], + events=events, + ) r = detect(mr, positive=rx["positive"], engine=st.get("sym_engine", "modular"), reconstruct=True) r._relaxed = True out = r.discrete(**opts) info = out["info"] cert = info.get("certificate") or {} - why = scalings_keep_leaves(r._raw.get("symmetries") or [], rx["leaves"], rx["dropped"]) \ - if not r.identifiable else None + why = ( + scalings_keep_leaves(r._raw.get("symmetries") or [], rx["leaves"], rx["dropped"]) + if not r.identifiable + else None + ) moved = {n for s in r._raw.get("symmetries") or [] for n in s.get("support") or []} free = [lf for lf in rx["leaves"] if lf["absorbs"] is None and lf["name"] not in moved] kinds = {lf["kind"] for lf in free} premise = None if free and not (len(kinds) == 1 and kinds <= {"exp", "log"} and independent_leaves(free, coords)): - premise = ("the starts of the new states " + ", ".join(lf["name"] for lf in free) + " are algebraically " - "independent over the rational functions of the coordinates") + premise = ( + "the starts of the new states " + ", ".join(lf["name"] for lf in free) + " are algebraically " + "independent over the rational functions of the coordinates" + ) keep = [s for s in out["symmetries"] if s.get("level") == "exact"] lost = [s for s in keep if not keeps_leaves(s.get("map") or {}, rx["leaves"], rx["dropped"])] count = info.get("count") if why is None and lost and count != 1: why = "an exact map of the relaxed model moves a new coordinate or a coordinate the new states start from" info["relaxed"] = { - "rewrites": rx["rewrites"], "dropped": rx["dropped"], "premise": premise, "why": why, - "leaves": [{"name": lf["name"], "kind": lf["kind"], "start": str(lf["value"]).replace("**", "^"), - "absorbs": lf["absorbs"]} for lf in rx["leaves"]], + "rewrites": rx["rewrites"], + "dropped": rx["dropped"], + "premise": premise, + "why": why, + "leaves": [ + { + "name": lf["name"], + "kind": lf["kind"], + "start": str(lf["value"]).replace("**", "^"), + "absorbs": lf["absorbs"], + } + for lf in rx["leaves"] + ], "model": {"odes": rx["odes"], "observables": rx["observables"], "trafo": rx["trafo"]}, "rest_chart": None if chart is None else {"rest": chart["rest"], "exchanged": chart["exchanged"]}, - "coordinates": list(r.info.get("coordinates") or [])} + "coordinates": list(r.info.get("coordinates") or []), + } info["limits"] = list(info.get("limits") or []) + [ "the count is that of the relaxed model, in the coordinates of that model: each non-rational term of the " "states is a new state times or plus a new coordinate, the value of the term at the start " - "(info['discrete']['relaxed'])"] + "(info['discrete']['relaxed'])" + ] if chart is not None: info["limits"].append( "under equilibrate the count is over the points of the resting set, in the chart where the resting " - "values " + ", ".join(chart["rest"].values()) + " are coordinates in place of " + - ", ".join(chart["exchanged"]) + " (info['discrete']['relaxed']['rest_chart']); the counts in the " - "domain do not hold these in their declared signs") + "values " + + ", ".join(chart["rest"].values()) + + " are coordinates in place of " + + ", ".join(chart["exchanged"]) + + " (info['discrete']['relaxed']['rest_chart']); the counts in the " + "domain do not hold these in their declared signs" + ) if why is not None: # the count of the relaxed model bounds nothing here info["relaxed"]["count"], info["count"] = count, None @@ -710,7 +842,8 @@ def _relaxed_discrete(self, exc, **opts): cert["axiom"] = cert["premise"] cert.setdefault("proven", []).append( "the values of the coordinates with the output of a generic point map injectively into the fiber of the " - "relaxed model modulo the continuous directions") + "relaxed model modulo the continuous directions" + ) for s in out["symmetries"]: if s.get("map"): s["relaxed"] = True @@ -721,19 +854,30 @@ def _reduced_detection(self): st = self.info.get("settings") or {} res = self if any(d.get("level") == "open" for d in self.symmetries): - res = detect(self.model, positive=st.get("positive", True), engine=st.get("sym_engine", "modular"), - equilibrate=bool(st.get("equilibrate")), reconstruct=True) + res = detect( + self.model, + positive=st.get("positive", True), + engine=st.get("sym_engine", "modular"), + equilibrate=bool(st.get("equilibrate")), + reconstruct=True, + ) # a rational trafo keeps the reduced model rational: a section met once is a chart by itself where it solves so with state.options(section_charts=True): red = reduce(res).to_dict() if red.get("remaining"): - raise ValueError("discrete() needs a reduction that removes every direction; directions remain: " - + ", ".join(str(d) for d in red["remaining"])) + raise ValueError( + "discrete() needs a reduction that removes every direction; directions remain: " + + ", ".join(str(d) for d in red["remaining"]) + ) m, why = _reduced_copy(self.model, red, res.gauge, bool(st.get("equilibrate"))) if why is not None: raise ValueError("discrete(): " + why) - r = detect(m, positive=_reduced_positive(st.get("positive", True), red, list(m.odes)), - engine=st.get("sym_engine", "modular"), equilibrate=bool(st.get("equilibrate"))) + r = detect( + m, + positive=_reduced_positive(st.get("positive", True), red, list(m.odes)), + engine=st.get("sym_engine", "modular"), + equilibrate=bool(st.get("equilibrate")), + ) if not r.identifiable: raise ValueError("discrete(): the reduced model is not locally identifiable") r._section = red.get("trafo") @@ -759,6 +903,7 @@ def _fiber_parts(self, order, what, switches=True): from .errors import SYMPY_FAILS from .rexpr import get_symbols, replace_symbols from .sym.switching import _SWITCHY + m = self.model st = self.info.get("settings") or {} unknown = [str(w) for w in m.unknown_inputs or []] @@ -774,6 +919,7 @@ def _fiber_parts(self, order, what, switches=True): if st.get("reduce_cq") and st.get("eliminated"): # the model on the level sets of the totals, as the detection read it: the totals are parameters from .detection.cq import reduced_by_totals + f0, obs, events, recon = reduced_by_totals(f0, obs, events, m.totals, st["eliminated"]) states = list(f0) obs_list = list(obs) if isinstance(obs, (list, tuple)) else None @@ -805,25 +951,33 @@ def _fiber_parts(self, order, what, switches=True): for c in range(K): g = {str(k): str(v) for k, v in dict(obs_list[c] if obs_list else obs).items()} # one simultaneous substitution as in the detection: the trafo, then the cells of the grid - tr = {str(k): num_str(replace_symbols(list(recon), list(recon.values()), str(v)) if recon else v) - for k, v in dict((trafos[c] if trafos else m.trafo) or {}).items() if str(k) not in recon} + tr = { + str(k): num_str(replace_symbols(list(recon), list(recon.values()), str(v)) if recon else v) + for k, v in dict((trafos[c] if trafos else m.trafo) or {}).items() + if str(k) not in recon + } tr = initial_value_split([tr], list(f0), taken=list(g))["trafos"][0] sub = {k: v for k, v in tr.items() if k not in f0} - cells = {} if grid is None else {col: replace_symbols(list(sub), list(sub.values()), grid.cell(c, col)) - for col in grid.colnames()} + cells = ( + {} + if grid is None + else {col: replace_symbols(list(sub), list(sub.values()), grid.cell(c, col)) for col in grid.colnames()} + ) steps = [s for s in (sub, {col: v for col, v in cells.items() if col not in f0}) if s] def apply(e, steps=steps): for s in steps: e = replace_symbols(list(s), list(s.values()), e) return e + ev = [] for e in events: if e.get("cond") is None or c in e["cond"]: t = apply(str(e["time"])) # an event value reads the clock at the event time - ev.append({"var": e["var"], "method": e["method"], "time": t, - "value": at_time(apply(str(e["value"])), t)}) + ev.append( + {"var": e["var"], "method": e["method"], "time": t, "value": at_time(apply(str(e["value"])), t)} + ) per.append((g, tr, cells, apply, ev)) # each condition starts at zero or at the earliest event that comes before nums = [time_value(e["time"]) for *_, ev in per for e in ev] @@ -864,6 +1018,7 @@ def key(e): def key(e): return e["time"] + if known: # a known input is a chain of jets whose values are known symbols, long enough for the gaps taken = set(get_symbols(list(f.values()) + list(g.values()))) | set(f) @@ -873,8 +1028,10 @@ def key(e): if unknown: # an unknown input is a chain of jets with free starts, unknowns of the fiber but no coordinates from .detection.uinputs import unknown_chain - f, ic, free_jets = unknown_chain(f, g, ic, unknown, 2 * order + 12, hy is not None or bool(ev) or - equil or K > 1, what) + + f, ic, free_jets = unknown_chain( + f, g, ic, unknown, 2 * order + 12, hy is not None or bool(ev) or equil or K > 1, what + ) # the clock advances at rate one from the start f["time"], ic["time"] = "1", start one_seg = K == 1 and not keys @@ -902,12 +1059,25 @@ def key(e): fr["time"], icr["time"] = "1", None for j in r["entries"]: on = apply(r["surfaces"][j]) - parts.append({"segments": [{"f": fr, "g": gr, "ic": icr, "on": on, "t": start, - "label": f"{rows[c]}~{k + 1}|{j + 1}:"}]}) + parts.append( + { + "segments": [ + { + "f": fr, + "g": gr, + "ic": icr, + "on": on, + "t": start, + "label": f"{rows[c]}~{k + 1}|{j + 1}:", + } + ] + } + ) if regimes is not None: for part in parts[n0:]: part["surfaces"] = [apply(q) for q in regimes[0]["surfaces"]] from .detection.rationalize import NotRationalError, rationalize + try: parts, rewrites, logs = rationalize(parts, list(self.info.get("coordinates") or ()), states) except NotRationalError: @@ -921,6 +1091,7 @@ def _switches(self, f, obs, events, what): signs decide them all, or None.""" from .errors import InapplicableError from .sym.switching import hybrid_model + st = self.info.get("settings") or {} try: hy = hybrid_model(f, obs, st.get("positive", True), events=events, inputs=list(self.model.inputs or [])) @@ -940,9 +1111,13 @@ def _regimes(self, hy, c, apply, tr, cells, inputs, start, what): from .detection.conditions import at_time from .sym.parse import model_sympify from .sym.switching import BACK, to_str + conds = (self.info.get("switching") or {}).get("conditions") or [] - allowed = (conds[c] if c < len(conds) else {}).get("regimes") or \ - (self.info.get("switching") or {}).get("regimes") or [] + allowed = ( + (conds[c] if c < len(conds) else {}).get("regimes") + or (self.info.get("switching") or {}).get("regimes") + or [] + ) n = len(hy.sw.funcs) side = {hy.text(j, sgn): (j, int(sgn > 0)) for j in range(n) for sgn in (1, -1)} out = [] @@ -954,14 +1129,21 @@ def _regimes(self, hy, c, apply, tr, cells, inputs, start, what): def text(e, assign=assign): return to_str(e.xreplace(assign).xreplace(BACK)) - out.append({"f": {x: text(e) for x, e in hy.f.items()}, - "g": {y: text(e) for y, e in hy.g[c if hy.g_list else 0].items()}, - "sides": [v for _, v in sorted(hit)]}) + + out.append( + { + "f": {x: text(e) for x, e in hy.f.items()}, + "g": {y: text(e) for y, e in hy.g[c if hy.g_list else 0].items()}, + "sides": [v for _, v in sorted(hit)], + } + ) surfaces = [to_str(q.xreplace(BACK)) for q in hy.sw.funcs] # the sides of the start at a random point of the domain rng = random.Random(f"{c}:{','.join(surfaces)}") - ic = {x: model_sympify(at_time(apply(tr.get(x, cells.get(x, x))), start)) if x not in inputs - else spy.Integer(0) for x in hy.f} + ic = { + x: model_sympify(at_time(apply(tr.get(x, cells.get(x, x))), start)) if x not in inputs else spy.Integer(0) + for x in hy.f + } sides = [] for q in surfaces: e = model_sympify(apply(q)).xreplace({spy.Symbol(x): v for x, v in ic.items()}) @@ -976,8 +1158,9 @@ def text(e, assign=assign): allowed_sides = [tuple(r["sides"]) for r in out] for r in out: r["surfaces"] = surfaces - r["entries"] = [j for j in range(n) if tuple(1 - v if i == j else v for i, v in enumerate(r["sides"])) - in allowed_sides] + r["entries"] = [ + j for j in range(n) if tuple(1 - v if i == j else v for i, v in enumerate(r["sides"])) in allowed_sides + ] return first + [r for r in out if r is not first[0]] def reduce(self, **kwargs): @@ -1162,9 +1345,24 @@ def _check_detect(model, *, cores, engine, trace, control, gauge, mode="local", raise InputError(f"`gauge` must be False, None or a sequence of names, not the string {gauge!r}") -def detect(model, *, scalings_only=False, equilibrate=None, reduce_cq=None, free_initial=None, - reconstruct=False, positive=None, verify=True, gauge=False, cores=1, control=None, - engine="modular", trace=False, mode="local", global_options=None): +def detect( + model, + *, + scalings_only=False, + equilibrate=None, + reduce_cq=None, + free_initial=None, + reconstruct=False, + positive=None, + verify=True, + gauge=False, + cores=1, + control=None, + engine="modular", + trace=False, + mode="local", + global_options=None, +): """Structural non-identifiabilities of a model, locally and, with ``mode="global"``, globally. Parameters @@ -1221,8 +1419,16 @@ def detect(model, *, scalings_only=False, equilibrate=None, reduce_cq=None, free ------- Symmetries """ - _check_detect(model, cores=cores, engine=engine, trace=trace, control=control, gauge=gauge, mode=mode, - global_options=global_options) + _check_detect( + model, + cores=cores, + engine=engine, + trace=trace, + control=control, + gauge=gauge, + mode=mode, + global_options=global_options, + ) if mode == "global": # the reduction before the count needs the closed forms reconstruct = True @@ -1237,11 +1443,22 @@ def detect(model, *, scalings_only=False, equilibrate=None, reduce_cq=None, free def run(pivots, cq_pivots): with _trace(trace): - return symmetry_detection(**model._kwargs(), gauge_preference=gauge, equilibrate=equilibrate, - reduce_cq=reduce_cq, free_initial=pivots, cq_pivots=cq_pivots, - reconstruct=reconstruct, positive=positive, verify=verify, - cores=cores, control=control or reconst_control(), - scalings_only=scalings_only, sym_engine=engine) + return symmetry_detection( + **model._kwargs(), + gauge_preference=gauge, + equilibrate=equilibrate, + reduce_cq=reduce_cq, + free_initial=pivots, + cq_pivots=cq_pivots, + reconstruct=reconstruct, + positive=positive, + verify=verify, + cores=cores, + control=control or reconst_control(), + scalings_only=scalings_only, + sym_engine=engine, + ) + try: res = Symmetries(pivot_choice(run, free_initial, reduce_cq), model) finally: @@ -1252,7 +1469,8 @@ def run(pivots, cq_pivots): if free_moiety and n_open: res.info["limits"] = list(res.info.get("limits") or []) + [ "a direction without a closed form moves the resting value of a conserved total; " - "reduce_cq=True reconstructs it in the total"] + "reduce_cq=True reconstructs it in the total" + ] if mode == "global": global_step(res, global_options, cores) return res @@ -1274,6 +1492,7 @@ def _reduced_positive(positive, red, states): """The declared domain in the chart of the reduction `red`: each new parameter with the domain the block solved, the other names as declared.""" import re + names, exprs = declared(positive) dom = {q: d for b in red.get("blocks") or [] for q, d in (b.get("solved_domain") or {}).items()} if names is None and all(d == "positive" for d in dom.values()): @@ -1285,9 +1504,23 @@ def _reduced_positive(positive, red, states): return out + [str(e) for e in exprs if {str(x) for x in e.free_symbols} <= coords] -def reduce(result, *, fixed=None, positive=None, d_poly=3, d_darboux=2, d_exp=2, separable=True, - zero_limits=False, alternatives=False, allow_open=True, allow_checked=True, - check=True, work_cap=4000, branch=None): +def reduce( + result, + *, + fixed=None, + positive=None, + d_poly=3, + d_darboux=2, + d_exp=2, + separable=True, + zero_limits=False, + alternatives=False, + allow_open=True, + allow_checked=True, + check=True, + work_cap=4000, + branch=None, +): """Reparametrization that removes the directions of a detection result. The model is described in the invariants of the directions, each a new parameter ``q_``. The @@ -1361,12 +1594,23 @@ def reduce(result, *, fixed=None, positive=None, d_poly=3, d_darboux=2, d_exp=2, if isinstance(result, Symmetries) and getattr(result.model, "unknown_inputs", None): # the directions the unknown inputs absorb, each with the proof that they do from .reduction.absorb import prepare + absorbed, notes = prepare(raw, result.model) - red = symmetry_reduction(absorbed, fixed=fixed, positive=positive, d_poly=d_poly, d_darboux=d_darboux, - d_exp=d_exp, separable_=separable, zero_compatibility=zero_limits, - alternatives=alternatives, work_cap=work_cap) + red = symmetry_reduction( + absorbed, + fixed=fixed, + positive=positive, + d_poly=d_poly, + d_darboux=d_darboux, + d_exp=d_exp, + separable_=separable, + zero_compatibility=zero_limits, + alternatives=alternatives, + work_cap=work_cap, + ) if notes: from .reduction.absorb import annotate + annotate(red, absorbed, notes) if check and isinstance(result, Symmetries) and isinstance(red, dict) and red.get("trafo"): red.setdefault("checks", {})["loop"] = _closed_loop(result, red) @@ -1382,13 +1626,14 @@ def attach_discrete(raw, red, positive, branch=None): `branch` replaced the trafo.""" if not isinstance(red, dict) or raw.get("discrete_symmetries") is None: if branch is not None: - raise InputError("`branch` needs a detection with mode=\"global\" that found a discrete symmetry") + raise InputError('`branch` needs a detection with mode="global" that found a discrete symmetry') return False d = raw["info"]["discrete"] red["discrete"] = { "symmetries": [e for e in raw["discrete_symmetries"] if e.get("preserves_domain") is not False], "fundamental_domain": d.get("fundamental_domain") or [], - "coordinates": (d.get("reduced") or {}).get("coordinates") or raw["info"].get("coordinates")} + "coordinates": (d.get("reduced") or {}).get("coordinates") or raw["info"].get("coordinates"), + } _branches(red, d, raw, positive, branch) return branch is not None @@ -1396,6 +1641,7 @@ def attach_discrete(raw, red, positive, branch=None): def _branches(red, d, raw, positive, branch): """The branch charts of the discrete symmetry in `red` (alternatives, or the trafo of the chosen `branch`).""" from .reduction.branches import branch_charts, pick_branch + section = (d.get("reduced") or {}).get("section") if d.get("reduced") and section != red.get("trafo"): # the maps are stated in the coordinates of the section that the global analysis took @@ -1409,8 +1655,15 @@ def _branches(red, d, raw, positive, branch): bs = red["discrete"]["branches"] if branch is None: red["alternatives"] = list(red.get("alternatives") or []) + [ - {"branch": b["branch"], "trafo": b["trafo"], "removed": red.get("removed"), - "remaining": red.get("remaining"), "unproven": b["unproven"]} for b in bs] + { + "branch": b["branch"], + "trafo": b["trafo"], + "removed": red.get("removed"), + "remaining": red.get("remaining"), + "unproven": b["unproven"], + } + for b in bs + ] return if not bs: raise InputError("`branch`: no branch charts, " + red["discrete"].get("why", "no discrete symmetry")) @@ -1418,8 +1671,7 @@ def _branches(red, d, raw, positive, branch): red["trafo"] = b["trafo"] red["discrete"]["branch"] = b if b["unproven"]: - warnings.warn(f"a claim of the branch {b['branch']} is not proven: " + "; ".join(b["unproven"]), - stacklevel=3) + warnings.warn(f"a claim of the branch {b['branch']} is not proven: " + "; ".join(b["unproven"]), stacklevel=3) def reduced_model(f, g, trafo, conditions, events, outer, equilibrate): @@ -1427,14 +1679,16 @@ def reduced_model(f, g, trafo, conditions, events, outer, equilibrate): reason it cannot take it. A key in the grid goes into the cells of the grid, a pinned resting value into `fixed`.""" from .detection.conditions import Grid, as_events from .rexpr import get_symbols, is_number, replace_symbols + outer = {str(k): str(v) for k, v in outer.items() if str(v).strip() != str(k)} fixed, why = [], None if equilibrate: # under equilibrate an entry for a state is the resting value of that state, known when it is a number for k in [k for k in outer if k in f]: if not is_number(outer[k]): - why = f"the reduction pins the resting value of {k} to {outer.pop(k)}, which `equilibrate` " \ - "does not take" + why = ( + f"the reduction pins the resting value of {k} to {outer.pop(k)}, which `equilibrate` does not take" + ) continue fixed.append(k) outer.pop(k) @@ -1443,14 +1697,24 @@ def reduced_model(f, g, trafo, conditions, events, outer, equilibrate): cells = [v for vals in grid.cols.values() for v in vals if isinstance(v, str)] hit = [k for k in outer if k in set(get_symbols(cells)) | set(grid.colnames())] sub = {k: outer[k] for k in hit} - grid = Grid(grid.rows, {c: [replace_symbols(list(sub), list(sub.values()), v) if isinstance(v, str) else v - for v in vals] for c, vals in grid.cols.items()}) + grid = Grid( + grid.rows, + { + c: [replace_symbols(list(sub), list(sub.values()), v) if isinstance(v, str) else v for v in vals] + for c, vals in grid.cols.items() + }, + ) conditions = {"rows": grid.rows, "cols": grid.cols} outer = {k: v for k, v in outer.items() if k not in set(grid.colnames()) and k not in sub} evs = as_events(events) - used = set(f) | set(get_symbols(list(f.values()) + [str(v) for x in (g if isinstance(g, (list, tuple)) else [g]) - for v in dict(x or {}).values()] + - [e["value"] for e in evs] + [e["time"] for e in evs])) + used = set(f) | set( + get_symbols( + list(f.values()) + + [str(v) for x in (g if isinstance(g, (list, tuple)) else [g]) for v in dict(x or {}).values()] + + [e["value"] for e in evs] + + [e["time"] for e in evs] + ) + ) names, vals = list(outer), list(outer.values()) def compose(inner): @@ -1461,6 +1725,7 @@ def compose(inner): # a symbol the model trafo replaced survives only inside the replaced values consumed = set(get_symbols(list(inner.values()))) return {**{k: v for k, v in outer.items() if k not in out and (k in used or k not in consumed)}, **out} + trafo = [compose(t) for t in trafo] if isinstance(trafo, (list, tuple)) else compose(trafo) return {"trafo": trafo, "conditions": conditions, "fixed": fixed, "why": why} @@ -1473,8 +1738,7 @@ def _reduced_copy(model, red, gauge, equilibrate): if rm["why"] is not None: return None, rm["why"] m.trafo, m.conditions = rm["trafo"], rm["conditions"] - m.fixed = list(dict.fromkeys(list(m.fixed or []) + list(gauge or []) + list(red.get("fixed") or []) + - rm["fixed"])) + m.fixed = list(dict.fromkeys(list(m.fixed or []) + list(gauge or []) + list(red.get("fixed") or []) + rm["fixed"])) return m, None @@ -1489,10 +1753,17 @@ def _closed_loop(result, red): return {"ok": None, "directions": None, "expected": want, "reason": "not run, " + why} def run(): - r = detect(m, equilibrate=bool(st.get("equilibrate")), reduce_cq=bool(st.get("reduce_cq")), - positive=st.get("positive", True), verify=bool(st.get("verify", True)), - engine=st.get("sym_engine", "modular"), control=st.get("control")) + r = detect( + m, + equilibrate=bool(st.get("equilibrate")), + reduce_cq=bool(st.get("reduce_cq")), + positive=st.get("positive", True), + verify=bool(st.get("verify", True)), + engine=st.get("sym_engine", "modular"), + control=st.get("control"), + ) return r.to_dict() + return loop_outcome(run, want) @@ -1503,14 +1774,27 @@ def loop_outcome(run, want): try: r = run() except ValueError as exc: - return {"ok": None, "directions": None, "expected": want, - "reason": "not run, " + ("the reduced model is not rational for the observability engine" - if "not rational" in str(exc) else str(exc).split("\n")[0])} + return { + "ok": None, + "directions": None, + "expected": want, + "reason": "not run, " + + ( + "the reduced model is not rational for the observability engine" + if "not rational" in str(exc) + else str(exc).split("\n")[0] + ), + } idle = [str(w.message) for w in rec if "had no effect" in str(w.message)] n = len(r.get("symmetries") or []) - out = {"directions": n, "expected": want, "rank": r.get("rank"), "dim": r.get("dim"), - "rank_status": ((r.get("info") or {}).get("rank_status") or {}).get("status"), - "ok": n == want and not idle} + out = { + "directions": n, + "expected": want, + "rank": r.get("rank"), + "dim": r.get("dim"), + "rank_status": ((r.get("info") or {}).get("rank_status") or {}).get("status"), + "ok": n == want and not idle, + } if idle: out["reason"] = idle[0] return out diff --git a/src/symident/detection/bound.py b/src/symident/detection/bound.py index dc684ae..60dc799 100644 --- a/src/symident/detection/bound.py +++ b/src/symident/detection/bound.py @@ -49,8 +49,7 @@ def _degs(e): def _rational(e): - return all(not a.is_Function for a in spy.preorder_traversal(e)) and \ - all(a.exp.is_Integer for a in e.atoms(spy.Pow)) + return all(not a.is_Function for a in spy.preorder_traversal(e)) and all(a.exp.is_Integer for a in e.atoms(spy.Pow)) @functools.lru_cache(maxsize=65536) @@ -121,8 +120,10 @@ def _model_degrees(f_items, g_items, x0_items): names = {} def rename(text): - return _NAME.sub(lambda m: m.group(0) if m.group(0) == "pi" else - names.setdefault(m.group(0), f"_n{len(names)}"), str(text)) + return _NAME.sub( + lambda m: m.group(0) if m.group(0) == "pi" else names.setdefault(m.group(0), f"_n{len(names)}"), str(text) + ) + items = [tuple((rename(k), rename(v)) for k, v in its) for its in (f_items, g_items, x0_items)] return _model_degrees_named(*items) @@ -160,14 +161,14 @@ def field_degrees(F, G, X): def no_degree(exprs): """Why `exprs` have no degree bound: the first term that is not rational, or their size; None otherwise.""" from ..sym.parse import to_r + try: es = [model_sympify(str(e)) for e in exprs] except SYMPY_FAILS as exc: sympy_fail(exc) return "an expression SymPy does not read" for e in es: - bad = next((a for a in spy.preorder_traversal(e) - if a.is_Function or (a.is_Pow and not a.exp.is_Integer)), None) + bad = next((a for a in spy.preorder_traversal(e) if a.is_Function or (a.is_Pow and not a.exp.is_Integer)), None) if bad is not None: return f"{to_r(bad)} is not rational" if sum(spy.count_ops(e) for e in es) > _ROW_OPS: @@ -280,16 +281,21 @@ def chain_degree(f, g, x0, events, order, gap_order, vector, times=None): """Degree bound of the cleared identity of the chain rows with events after the start, None where not rational.""" fs = list(f) if isinstance(f, (list, tuple)) else [f] * (len(events) + 1) try: - mds = [_model_degrees(tuple(sorted(fj.items())), tuple(sorted(g.items())), tuple(sorted(x0.items()))) - for fj in fs] + mds = [ + _model_degrees(tuple(sorted(fj.items())), tuple(sorted(g.items())), tuple(sorted(x0.items()))) for fj in fs + ] if any(md is None for md in mds): return None comps = [model_sympify(v) for v in vector.values()] x0e = [model_sympify(v) for v in x0.values()] - evs = [[(str(e["var"]), model_sympify(str(e["value"])), str(e.get("method", "replace"))) for e in grp] - for grp in events] - tau = [model_sympify(str(t)) if t not in (None, "") else spy.Integer(0) - for t in (list(times) if times else [None] * (len(evs) + 1))] + evs = [ + [(str(e["var"]), model_sympify(str(e["value"])), str(e.get("method", "replace"))) for e in grp] + for grp in events + ] + tau = [ + model_sympify(str(t)) if t not in (None, "") else spy.Integer(0) + for t in (list(times) if times else [None] * (len(evs) + 1)) + ] if not all(_rational(e) for e in comps + x0e + tau + [v for grp in evs for _, v, _ in grp]): return None states = {spy.Symbol(x) for fj in fs for x in fj} @@ -297,8 +303,11 @@ def chain_degree(f, g, x0, events, order, gap_order, vector, times=None): return None moving = [bool(t.free_symbols) for t in tau] # the derivative of each moving start time along v joins the vector - dirs = [sum((spy.diff(t, spy.Symbol(k)) * c for k, c in zip(vector, comps)), spy.Integer(0)) - for t, mv in zip(tau, moving) if mv] + dirs = [ + sum((spy.diff(t, spy.Symbol(k)) * c for k, c in zip(vector, comps)), spy.Integer(0)) + for t, mv in zip(tau, moving) + if mv + ] dV = _vector_degree(comps + dirs) M = int(gap_order) Gs = [max(_vector_degree(x0e) if x0e else 1, 1)] @@ -333,6 +342,7 @@ def chain_degree(f, g, x0, events, order, gap_order, vector, times=None): def drawn(points): """The most points a kernel check of the running session drew for the `points` that passed.""" from .. import state + ses = state.get("session") return max([int(points)] + list((ses.notes["draws"] if ses is not None else None) or [])) @@ -348,5 +358,10 @@ def kernel_bound(f, g, x0, order, vectors, q, points, events=None, gap_order=0, d = max(degs) draws = max(int(draws or points), points) # the passing points are `points` of the draws: a union over the subsets, each a uniform sample - return {"degree": d, "points": points, "draws": draws, "prime": int(q), - "probability": float(min(1.0, len(vectors) * math.comb(draws, points) * (min(1.0, d / q)) ** points))} + return { + "degree": d, + "points": points, + "draws": draws, + "prime": int(q), + "probability": float(min(1.0, len(vectors) * math.comb(draws, points) * (min(1.0, d / q)) ** points)), + } diff --git a/src/symident/detection/classify.py b/src/symident/detection/classify.py index d819038..fab383b 100644 --- a/src/symident/detection/classify.py +++ b/src/symident/detection/classify.py @@ -22,6 +22,7 @@ def orbit_kind(d): import sympy as spy from ..sym.parse import model_sympify + if d.get("type") == "scaling": return "scaling" gen = d.get("generator") @@ -100,16 +101,24 @@ def report_physical(result, znames, aux_names, sc, nz, P, aux_field, flag_joint= phys_coords = [z for z in znames if z not in aux] phys_set = set(phys_coords) result = dict(result) - result["non_identifiable"] = [d for d in result["non_identifiable"] - if any(s in phys_set for s in d.get("support", []))] + result["non_identifiable"] = [ + d for d in result["non_identifiable"] if any(s in phys_set for s in d.get("support", [])) + ] phys_cols = [i for i, z in enumerate(znames) if z in phys_set] piv = {int(x) for x in np.atleast_1d(sc["pivots"])} N = nullspace_basis(sc["ref"], [c for c in range(nz) if c not in piv], P) phys_null = rref_modp(N[phys_cols, :], P)["rank"] if phys_cols and N.shape[1] else 0 if sc.get("rank_s") is not None and sc["rank_s"] < sc["rank"]: aux_cols = [i for i, z in enumerate(znames) if z not in phys_set] - r_aux = int(_core.sym_series_rank(np.asarray(sc["ref"]["S"], dtype=np.int64), int(nz), - int(sc["ref"]["N"]), P, aux_cols)["rank"]) if aux_cols else 0 + r_aux = ( + int( + _core.sym_series_rank( + np.asarray(sc["ref"]["S"], dtype=np.int64), int(nz), int(sc["ref"]["N"]), P, aux_cols + )["rank"] + ) + if aux_cols + else 0 + ) phys_null = (nz - sc["rank_s"]) - (len(aux_cols) - r_aux) result["dim"] = len(phys_coords) result["coordinates"] = phys_coords @@ -124,8 +133,7 @@ def report_physical(result, znames, aux_names, sc, nz, P, aux_field, flag_joint= phys = {k: v for k, v in d["vector"].items() if k not in aux} if aux_field == "input_vector": # components, with the form they belong to for the rescaling to the generator - comp = (lambda k, v: scaling_component(v, k)) if d.get("type") == "scaling" else \ - (lambda k, v: str(v)) + comp = (lambda k, v: scaling_component(v, k)) if d.get("type") == "scaling" else (lambda k, v: str(v)) d[aux_field] = {k: comp(k, v) for k, v in d[aux_field].items()} d["input_form"] = {k: comp(k, v) for k, v in phys.items()} if flag_joint and any(set(get_symbols(str(e))) & aux for e in phys.values()): @@ -152,6 +160,7 @@ def eval_w(w): except ValueError: pass return eval_modq(w, env, P) + for d in scal_res.get("non_identifiable", []): names = [k for k in d["vector"] if k in zi] if not names: @@ -186,14 +195,33 @@ def eval_w(w): if moved: # a translated coordinate: the generator itself, not weights vec = {names[i]: wsym[i] if names[i] in shifts else scaling_component(wsym[i], names[i]) for i in order} - scaling.append({"support": supp, "vector": vec, "type": "general", "closed_form": True, - "exact": bool(d.get("exact", False))}) + scaling.append( + { + "support": supp, + "vector": vec, + "type": "general", + "closed_form": True, + "exact": bool(d.get("exact", False)), + } + ) continue - scaling.append({"support": supp, "vector": {names[i]: wsym[i] for i in order}, - "type": "scaling", "closed_form": True, "exact": bool(d.get("exact", False)), - **({"state_components": d["state_components"], - "lift_form": {names[i]: scaling_component(wsym[i], names[i]) for i in order}} - if d.get("state_components") else {})}) + scaling.append( + { + "support": supp, + "vector": {names[i]: wsym[i] for i in order}, + "type": "scaling", + "closed_form": True, + "exact": bool(d.get("exact", False)), + **( + { + "state_components": d["state_components"], + "lift_form": {names[i]: scaling_component(wsym[i], names[i]) for i in order}, + } + if d.get("state_components") + else {} + ), + } + ) return {"scaling": scaling, "Bmat": Bmat} diff --git a/src/symident/detection/closedform.py b/src/symident/detection/closedform.py index 926fbaf..cc3a1f5 100644 --- a/src/symident/detection/closedform.py +++ b/src/symident/detection/closedform.py @@ -53,8 +53,12 @@ def reconstruct_entry(sample_u, mons, residues, primes): rec = rat_recon(coef_res, list(primes)) if any(d == "0" for d in rec["den"]): return None - return {"num_coef_n": rec["num"][:n_mon], "num_coef_d": rec["den"][:n_mon], - "den_coef_n": rec["num"][n_mon:], "den_coef_d": rec["den"][n_mon:]} + return { + "num_coef_n": rec["num"][:n_mon], + "num_coef_d": rec["den"][:n_mon], + "den_coef_n": rec["num"][n_mon:], + "den_coef_d": rec["den"][n_mon:], + } def simplify(expr): diff --git a/src/symident/detection/conditions.py b/src/symident/detection/conditions.py index c7162e2..436f372 100644 --- a/src/symident/detection/conditions.py +++ b/src/symident/detection/conditions.py @@ -40,8 +40,9 @@ def __init__(self, rows, cols): self.cols = {str(k): list(v) for k, v in cols.items()} bad = [k for k, v in self.cols.items() if len(v) != len(self.rows)] if bad: - raise InputError(f"conditions: the column {bad[0]} has {len(self.cols[bad[0]])} entries " - f"for {len(self.rows)} rows") + raise InputError( + f"conditions: the column {bad[0]} has {len(self.cols[bad[0]])} entries for {len(self.rows)} rows" + ) @classmethod def from_any(cls, x): @@ -86,9 +87,13 @@ def as_events(events): return [] out = [] for e in events: - d = {"var": str(e["var"]), "time": num_str(e.get("time", "NA")), - "value": num_str(e["value"]), "method": str(e.get("method", "replace")), - "root": e.get("root")} + d = { + "var": str(e["var"]), + "time": num_str(e.get("time", "NA")), + "value": num_str(e["value"]), + "method": str(e.get("method", "replace")), + "root": e.get("root"), + } if e.get("cond") is not None: d["cond"] = [int(c) for c in e["cond"]] out.append(d) @@ -117,6 +122,7 @@ def resolve(val, ci): sub = cond_subs[ci] v = replace_symbols(list(sub), list(sub.values()), v) return v + return resolve @@ -145,14 +151,27 @@ def at_time(value, t): return replace_symbols(["time"], [str(t)], value) if "time" in get_symbols([str(value)]) else value -def resolve_conditions(conditions, events, initial, symbols, states, const_states=(), forcings=(), - equilibrate=False, cond_subs=None, cond_initial=None, n_cond_obs=0, renamed=()): +def resolve_conditions( + conditions, + events, + initial, + symbols, + states, + const_states=(), + forcings=(), + equilibrate=False, + cond_subs=None, + cond_initial=None, + n_cond_obs=0, + renamed=(), +): """Per-segment substitutions, initial values and events per condition; `renamed` columns substitute the state.""" n_grid = 0 if conditions is None else conditions.nrow Kcond = max(1, len(cond_subs or []), len(cond_initial or []), n_grid, n_cond_obs) if n_grid and cond_subs and len(cond_subs) != n_grid: - raise ValueError(f"the per-condition `trafo` list length " - f"({len(cond_subs)}) must match the condition grid rows ({n_grid}).") + raise ValueError( + f"the per-condition `trafo` list length ({len(cond_subs)}) must match the condition grid rows ({n_grid})." + ) if conditions is None: conditions = Grid([str(i + 1) for i in range(Kcond)], {}) conds = conditions.rows or [str(i + 1) for i in range(max(1, conditions.nrow))] @@ -178,9 +197,11 @@ def layout(ev, tstr): kn = [as_number(k) for k in post_keys] kn = [k for k in kn if k is not None] if any(kn[i] >= kn[i + 1] for i in range(len(kn) - 1)): - raise ValueError("with an event time given in parameters, the " - "list of events sets the order of the events and must list the numeric " - "times ascending.") + raise ValueError( + "with an event time given in parameters, the " + "list of events sets the order of the events and must list the numeric " + "times ascending." + ) seg_of = [1 if is_t0[i] else 2 + post_keys.index(key[i]) for i in range(len(ev))] return is_t0, seg_of, [num_str(t0)] + post_keys @@ -201,6 +222,7 @@ def cell(ci, col): def value(i, k=k, ev=ev, ev_time=ev_time): # an event value reads the clock at the event time return at_time(resolve(ev[i]["value"], k), ev_time[i]) + n_seg = len(seg_times) n_gaps = max(n_gaps, n_seg - 1) ev_var = [e["var"] for e in ev] @@ -257,6 +279,7 @@ def value(i, k=k, ev=ev, ev_time=ev_time): def before(v): return replace_symbols(at_pre, [f"({pre[x]})" for x in at_pre], v) if at_pre else v + for X in dyn_states: ops = [i for i in le_idx if ev_var[i] == X] if pre[X] == X and not ops and X not in forcings: @@ -268,8 +291,11 @@ def before(v): else: ev0 = [] ic0 = dummy_ic0 - seg_ev = [{"var": ev_var[i], "method": ev_method[i], "value": value(i)} - for i in range(len(ev)) if not is_switch[i] and seg_of[i] == j] + seg_ev = [ + {"var": ev_var[i], "method": ev_method[i], "value": value(i)} + for i in range(len(ev)) + if not is_switch[i] and seg_of[i] == j + ] subs_list.append(subs) rest_list.append(rest) ic0_list.append(ic0) @@ -279,10 +305,20 @@ def before(v): equil_list.append(bool(equilibrate)) chain_of.append(k + 1) pos_in_chain.append(j) - return {"subs": subs_list, "rest_subs": rest_list, "ic0": ic0_list, "seg_equil": equil_list, - "events0": ev0_list, "seg_events": seg_ev_list, "chain_of": chain_of, - "pos_in_chain": pos_in_chain, "conditions": conds, "n_conditions": len(conds), - "n_gaps": n_gaps, "times": time_list} + return { + "subs": subs_list, + "rest_subs": rest_list, + "ic0": ic0_list, + "seg_equil": equil_list, + "events0": ev0_list, + "seg_events": seg_ev_list, + "chain_of": chain_of, + "pos_in_chain": pos_in_chain, + "conditions": conds, + "n_conditions": len(conds), + "n_gaps": n_gaps, + "times": time_list, + } def scaling_component(w, var): @@ -307,6 +343,7 @@ def log_param_back(res, lp): def ren(v): return [th[X.index(x)] if x in X else x for x in v] + res = dict(res) res["coordinates"] = ren(res.get("coordinates") or []) out = [] @@ -323,8 +360,7 @@ def ren(v): continue vec = {k: scaling_component(v, k) for k, v in vec.items()} d["type"] = "general" - d["vector"] = {ren([k])[0]: str(log_param_backsub(str(v), k, X, th, b)) - for k, v in vec.items()} + d["vector"] = {ren([k])[0]: str(log_param_backsub(str(v), k, X, th, b)) for k, v in vec.items()} out.append(d) res["non_identifiable"] = out return res @@ -352,6 +388,7 @@ def event_pinned_states(events, conditions): def is_known(v): vals = [num_str(x) for x in conditions.cols[v]] if v in cols else [v] return bool(vals) and all(is_number(x) for x in vals) + pinned = [] for e in events: if e["method"] in ("replace", "add") and is_known(e["value"]): @@ -375,8 +412,14 @@ def initial_value_split(trafos, states, taken=()): conflict = [s for s in states if s in conflict and s != "time"] if not conflict: return none - taken = list(dict.fromkeys(list(taken) + list(states) + [k for tr in trafos for k in tr] + - [s for tr in trafos for s in get_symbols(list(tr.values()))])) + taken = list( + dict.fromkeys( + list(taken) + + list(states) + + [k for tr in trafos for k in tr] + + [s for tr in trafos for s in get_symbols(list(tr.values()))] + ) + ) to = [] for X in conflict: cand = f"{X}_init" @@ -415,12 +458,14 @@ def fix_dir(d): if d.get("support") is not None: d["support"] = ren(d["support"]) return d + raw = dict(raw) if raw.get("coordinates") is not None: raw["coordinates"] = ren(raw["coordinates"]) if isinstance(raw.get("kernel"), dict) and raw["kernel"].get("coords") is not None: - raw["kernel"] = dict(raw["kernel"], coords=[frm[to.index(z)] if z in to else z - for z in raw["kernel"]["coords"]]) + raw["kernel"] = dict( + raw["kernel"], coords=[frm[to.index(z)] if z in to else z for z in raw["kernel"]["coords"]] + ) if raw.get("non_identifiable") is not None: raw["non_identifiable"] = [fix_dir(d) for d in raw["non_identifiable"]] return raw diff --git a/src/symident/detection/core.py b/src/symident/detection/core.py index 36d4582..cef102d 100644 --- a/src/symident/detection/core.py +++ b/src/symident/detection/core.py @@ -56,6 +56,7 @@ def _clean(e): def _log_coordinates(trafo, exprs): """The coordinates the trafo passes only through b^theta, or none where that fails.""" from ..sym.charts import log_coordinates + trafos = [dict(t) for t in trafo if t] if isinstance(trafo, (list, tuple)) else [dict(trafo or {})] try: return log_coordinates(trafos, [str(e) for e in exprs]) @@ -89,14 +90,17 @@ def _clock_offset(fdyn, gset, cond_subs, conditions, tt0): gset = [_sub_or_none(sub, g) for g in gset] cond_subs = None if cond_subs is None else [{k: sub(v) for k, v in (cs or {}).items()} for cs in cond_subs] if conditions is not None: - conditions = Grid(conditions.rows, {c: [sub(v) if isinstance(v, str) else v for v in vals] - for c, vals in conditions.cols.items()}) + conditions = Grid( + conditions.rows, + {c: [sub(v) if isinstance(v, str) else v for v in vals] for c, vals in conditions.cols.items()}, + ) return fdyn, gset, cond_subs, conditions def _zeroed(before, after): """The right-hand sides `after`, "0" where a substitution of `before` makes one vanish identically.""" import sympy as spy + out = {} for k, v in after.items(): if v != before.get(k) and str(v) != "0": @@ -113,6 +117,7 @@ def _rest_idle_states(fdyn, forcings, zero=()): import sympy as spy from ..sym.parse import _make_local_parse + _, parse = _make_local_parse([f"{k} = {v}" for k, v in fdyn.items()]) at0 = {spy.Symbol(u): 0 for u in list(forcings) + list(zero)} out = [] @@ -131,6 +136,7 @@ def _ode_zeros(fdyn, forcings, known=(), nonzero=()): import sympy as spy from ..sym.parse import _make_local_parse + _, parse = _make_local_parse([f"{k} = {v}" for k, v in fdyn.items()]) rhs = {k: parse(str(v).replace("^", "**")) for k, v in fdyn.items()} zero = {spy.Symbol(u): 0 for u in list(forcings) + list(known)} @@ -139,6 +145,7 @@ def _ode_zeros(fdyn, forcings, known=(), nonzero=()): def vanishes(e): v = spy.cancel(spy.together(e)) return v == 0 or v.has(spy.nan, spy.zoo) + while True: cand = {} for k, e in rhs.items(): @@ -169,8 +176,7 @@ def _rest_zeros(fdyn, reactions, forcings, nonzero=()): zero = [] nonzero = [x for x in nonzero if x in fdyn] if reactions is not None: - zero, notes = equil_zero_branches(reactions["smatrix"], reactions["species"], reactions["rates"], - forcings) + zero, notes = equil_zero_branches(reactions["smatrix"], reactions["species"], reactions["rates"], forcings) for n in notes: session.note("branches", n) zero = [z for z in zero if z not in set(nonzero)] @@ -179,9 +185,12 @@ def _rest_zeros(fdyn, reactions, forcings, nonzero=()): zero = list(dict.fromkeys(zero + forced)) if not open_: return zero - session.note("branches", f"the resting states {', '.join(open_)}: the right-hand side of {open_[0]} " - f"vanishes at {open_[0]} = 0 and where another of them is zero; the result holds " - f"for {open_[0]} = 0") + session.note( + "branches", + f"the resting states {', '.join(open_)}: the right-hand side of {open_[0]} " + f"vanishes at {open_[0]} = 0 and where another of them is zero; the result holds " + f"for {open_[0]} = 0", + ) zero.append(open_[0]) @@ -196,8 +205,11 @@ def _note_signed_totals(totals, cq, positive): continue row = dec["C"][list(totals).index(name)] if (row > 1e-12).any() and (row < -1e-12).any(): - session.note("limits", f"the total {name} = {totals[name]} has coefficients of both signs; as a " - "coordinate it is taken positive") + session.note( + "limits", + f"the total {name} = {totals[name]} has coefficients of both signs; as a " + "coordinate it is taken positive", + ) def _zero_factor(fdyn, x, zero, forcings): @@ -206,6 +218,7 @@ def _zero_factor(fdyn, x, zero, forcings): import sympy as spy from ..sym.parse import _make_local_parse + _, parse = _make_local_parse([f"{k} = {v}" for k, v in fdyn.items()]) at0 = {spy.Symbol(u): 0 for u in list(forcings) + list(zero) if u != x} try: @@ -229,9 +242,12 @@ def _note_zero_branches(fdyn, zero, totals, forcings, free_initial): continue za = _zero_factor(fdyn, x, zero, forcings) if za is not None and za[1]: - session.note("branches", f"{x} rests at zero; the resting set also has a branch with {x} away from " - f"zero, where {str(za[0]).replace('**', '^')} = 0, which free_initial=['{x}'] " - "takes without reduce_cq") + session.note( + "branches", + f"{x} rests at zero; the resting set also has a branch with {x} away from " + f"zero, where {str(za[0]).replace('**', '^')} = 0, which free_initial=['{x}'] " + "takes without reduce_cq", + ) def _free_zero_states(fdyn, reactions, forcings, free_initial): @@ -244,8 +260,11 @@ def _free_zero_states(fdyn, reactions, forcings, free_initial): if za is None or not za[1]: raise InputError(f"`free_initial` names {x}, which rests at zero at every resting state") if hit: - session.note("branches", f"free_initial: {', '.join(hit)} {'rests' if len(hit) == 1 else 'rest'} away from " - "zero; the result holds on that branch of the resting set") + session.note( + "branches", + f"free_initial: {', '.join(hit)} {'rests' if len(hit) == 1 else 'rest'} away from " + "zero; the result holds on that branch of the resting set", + ) zero = _rest_zeros(fdyn, reactions, forcings, free_initial) return zero @@ -253,14 +272,21 @@ def _free_zero_states(fdyn, reactions, forcings, free_initial): def _drop_sinks(fdyn, g_exprs, trafo, events, reactions, totals, keep, zero=()): """The model without the states that no right-hand side, observable, event or trafo value holds.""" import sympy as spy + trafos = (trafo if isinstance(trafo, (list, tuple)) else [trafo]) if trafo is not None else [] rhs = list(fdyn.values()) if zero and not events: at0 = {spy.Symbol(z): 0 for z in zero} rhs = [to_r(model_sympify(e).xreplace(at0)) for e in rhs] - used = set(get_symbols(rhs + list(g_exprs) + - [str(v) for t in trafos if t for v in dict(t).values()] + - [str(e["value"]) for e in events] + [str(e["time"]) for e in events])) + used = set( + get_symbols( + rhs + + list(g_exprs) + + [str(v) for t in trafos if t for v in dict(t).values()] + + [str(e["value"]) for e in events] + + [str(e["time"]) for e in events] + ) + ) sinks = [s for s in fdyn if s not in used and s not in set(keep) and s not in set(zero)] if not sinks: return fdyn, trafo, events, reactions, totals, [] @@ -269,12 +295,16 @@ def _drop_sinks(fdyn, g_exprs, trafo, events, reactions, totals, keep, zero=()): def strip(t): return None if t is None else {k: v for k, v in dict(t).items() if k not in drop} + trafo = [strip(t) for t in trafo] if isinstance(trafo, (list, tuple)) else strip(trafo) events = [e for e in events if e["var"] not in drop] if reactions is not None: keep_cols = [j for j, sp in enumerate(reactions["species"]) if sp not in drop] - reactions = dict(reactions, species=[reactions["species"][j] for j in keep_cols], - smatrix=[[row[j] for j in keep_cols] for row in reactions["smatrix"]]) + reactions = dict( + reactions, + species=[reactions["species"][j] for j in keep_cols], + smatrix=[[row[j] for j in keep_cols] for row in reactions["smatrix"]], + ) if totals: totals = {k: v for k, v in totals.items() if not drop & set(get_symbols([str(v)]))} # a dropped state that still multiplies a state at zero becomes a known constant, so @@ -288,6 +318,7 @@ def _off_domain(exprs, positive, generic=()): import sympy as spy from ..sym.domain import is_positive + # the `generic` symbols take values of their own and count as positive every = positive is True pos = set(generic) | (set() if positive in (True, False, None) else set(positive)) @@ -314,8 +345,10 @@ def _off_domain(exprs, positive, generic=()): if is_positive(u, True if every else names) or (not every and is_positive(u, sorted(pos))): continue bad = [] if every else sym_sort([str(s) for s in u.free_symbols if str(s) not in pos]) - return (f"{str(a).replace('**', '^')} needs a positive {what} (`positive`): " - f"{', '.join(bad) or str(u)} not declared positive") + return ( + f"{str(a).replace('**', '^')} needs a positive {what} (`positive`): " + f"{', '.join(bad) or str(u)} not declared positive" + ) return None @@ -327,7 +360,7 @@ def _check_steps(kw): """ValueError for a call of floor(), ceiling() or round() in the model.""" texts = [] for key in ("f", "g", "trafo", "events"): - for x in (kw.get(key) if isinstance(kw.get(key), (list, tuple)) else [kw.get(key)]): + for x in kw.get(key) if isinstance(kw.get(key), (list, tuple)) else [kw.get(key)]: texts += [str(v) for v in (x.values() if isinstance(x, dict) else [x]) if v is not None] # conditions repeat the same texts; a text without the name of a step function holds no call of it for t in dict.fromkeys(texts): @@ -335,9 +368,11 @@ def _check_steps(kw): continue hit = [n for k, n in tokens(t) if k == "fun" and n in _STEPS] if hit: - raise ValueError(f"{hit[0]}() in {t} jumps at every integer of the argument and is constant " - "in between; symident does not analyze it: write the steps it takes with " - "piecewise() on their thresholds") + raise ValueError( + f"{hit[0]}() in {t} jumps at every integer of the argument and is constant " + "in between; symident does not analyze it: write the steps it takes with " + "piecewise() on their thresholds" + ) def _check_names(kw): @@ -361,15 +396,18 @@ def _check_input_starts(kw): trafo = kw.get("trafo") grid = Grid.from_any(kw.get("conditions")) for u in [str(u) for u in kw.get("forcings") or []]: - vals = [num_str(dict(t or {}).get(u, "0")).strip() - for t in (trafo if isinstance(trafo, (list, tuple)) else [trafo])] + vals = [ + num_str(dict(t or {}).get(u, "0")).strip() for t in (trafo if isinstance(trafo, (list, tuple)) else [trafo]) + ] if grid is not None and u in grid.colnames(): vals += [grid.cell(i, u) for i in range(grid.nrow)] bad = [v for v in vals if v not in ("0", u)] if bad: - raise ValueError(f"the input {u} starts at zero and cannot take the initial value {bad[0]}; an event " - f"sets it, such as {{'var': '{u}', 'time': 0, 'value': '{bad[0]}', " - "'method': 'replace'}") + raise ValueError( + f"the input {u} starts at zero and cannot take the initial value {bad[0]}; an event " + f"sets it, such as {{'var': '{u}', 'time': 0, 'value': '{bad[0]}', " + "'method': 'replace'}" + ) def _check_declared(kw, known): @@ -382,8 +420,12 @@ def _check_declared(kw, known): events = as_events(kw.get("events")) grid = Grid.from_any(kw.get("conditions")) totals = dict(kw.get("totals") or {}) - texts = [str(v) for t in trafos for v in t.values()] + [e["value"] for e in events] + \ - [e["time"] for e in events] + [str(v) for v in totals.values()] + texts = ( + [str(v) for t in trafos for v in t.values()] + + [e["value"] for e in events] + + [e["time"] for e in events] + + [str(v) for v in totals.values()] + ) if grid is not None: texts += [v for vals in grid.cols.values() for v in vals if isinstance(v, str)] names = states | eq | {str(k) for t in trafos for k in t} | set(get_symbols(list(dict.fromkeys(texts)))) @@ -391,19 +433,31 @@ def _check_declared(kw, known): names |= set(totals) unknown = {str(w) for w in kw.get("unknown_inputs") or []} checks = [ - ([u for u in known if u in states], "known input {} has an equation in `odes`; a known input is a " - "function of time without one"), + ( + [u for u in known if u in states], + "known input {} has an equation in `odes`; a known input is a function of time without one", + ), ([u for u in known if u not in eq], "known input {} enters no right-hand side or observable"), - ([str(u) for u in kw.get("forcings") or [] if str(u) not in states], - "input {} is not a state of `odes`; an input is a state that events set"), - ([e["var"] for e in events if e["var"] not in states and e["var"] not in unknown], - "an event changes {}, which is not a state of `odes`"), - ([c for c in (grid.colnames() if grid is not None else []) if c not in names], - "the condition column {} names no symbol of the model"), - ([str(x) for x in kw.get("fixed") or [] if str(x) not in names], "`fixed` names {}, which is no symbol of " - "the model"), - ([str(x) for x in kw.get("parameters") or [] if str(x) not in names], - "`parameters` names {}, which is no symbol of the model"), + ( + [str(u) for u in kw.get("forcings") or [] if str(u) not in states], + "input {} is not a state of `odes`; an input is a state that events set", + ), + ( + [e["var"] for e in events if e["var"] not in states and e["var"] not in unknown], + "an event changes {}, which is not a state of `odes`", + ), + ( + [c for c in (grid.colnames() if grid is not None else []) if c not in names], + "the condition column {} names no symbol of the model", + ), + ( + [str(x) for x in kw.get("fixed") or [] if str(x) not in names], + "`fixed` names {}, which is no symbol of the model", + ), + ( + [str(x) for x in kw.get("parameters") or [] if str(x) not in names], + "`parameters` names {}, which is no symbol of the model", + ), ] for bad, why in checks: if bad: @@ -412,15 +466,19 @@ def _check_declared(kw, known): if isinstance(pos, (list, tuple)): bad = [str(p) for p in pos if _NAME.fullmatch(str(p)) and str(p) not in names] if bad: - warnings.warn(f"`positive` names {', '.join(bad)}, which {'is' if len(bad) == 1 else 'are'} no " - "symbol of the model; ignored", stacklevel=3) + warnings.warn( + f"`positive` names {', '.join(bad)}, which {'is' if len(bad) == 1 else 'are'} no " + "symbol of the model; ignored", + stacklevel=3, + ) def _model_texts(kw): """The right-hand sides and observables of the detection arguments `kw`.""" gs = kw.get("g") - return [str(v) for v in dict(kw.get("f") or {}).values()] + \ - [str(v) for g in (gs if isinstance(gs, (list, tuple)) else [gs]) for v in dict(g or {}).values()] + return [str(v) for v in dict(kw.get("f") or {}).values()] + [ + str(v) for g in (gs if isinstance(gs, (list, tuple)) else [gs]) for v in dict(g or {}).values() + ] def _check_unknown_inputs(kw): @@ -436,21 +494,27 @@ def _check_unknown_inputs(kw): used = set(get_symbols(texts)) for w in unknown: if w in f: - raise ValueError(f"unknown input {w} has an equation in `odes`; an unknown input is a " - "function of time without one") + raise ValueError( + f"unknown input {w} has an equation in `odes`; an unknown input is a function of time without one" + ) if w in set(kw.get("forcings") or []) | set(kw.get("fixed") or []) | set(kw.get("parameters") or []): raise ValueError(f"unknown input {w} is also listed in `inputs`, `fixed` or `parameters`") if w not in used: raise ValueError(f"unknown input {w} enters no right-hand side or observable") for ev in as_events(kw.get("events")) or []: if str(ev.get("var")) in unknown: - raise ValueError(f"an event changes the unknown input {ev['var']}; an unknown input has no " - "events, since it is any function of time") + raise ValueError( + f"an event changes the unknown input {ev['var']}; an unknown input has no " + "events, since it is any function of time" + ) why = None if kw.get("sym_engine") == "symbolic": why = 'engine="symbolic"' - elif kw.get("trafo") is not None and any(w in dict(t or {}) for t in ( - kw["trafo"] if isinstance(kw["trafo"], (list, tuple)) else [kw["trafo"]]) for w in unknown): + elif kw.get("trafo") is not None and any( + w in dict(t or {}) + for t in (kw["trafo"] if isinstance(kw["trafo"], (list, tuple)) else [kw["trafo"]]) + for w in unknown + ): why = "a `trafo` entry for an unknown input" if why is not None: raise ValueError(f"unknown inputs are not supported together with {why} yet") @@ -463,8 +527,9 @@ def _input_jets(f, unknown, order, taken): names = [w] + [f"{w}_d{k}" for k in range(1, order)] clash = [n for n in names[1:] if n in taken] if clash: - raise ValueError(f"{clash[0]} names a symbol of the model and a time derivative of the " - f"unknown input {w}; rename it") + raise ValueError( + f"{clash[0]} names a symbol of the model and a time derivative of the unknown input {w}; rename it" + ) jets[w] = names chain = {} for names in jets.values(): @@ -492,19 +557,24 @@ def _with_input_jets(kw): break order *= 2 if ui and ui.get("short"): - session.note("limits", f"unknown inputs: the {ui['jet_order']} jets of each input are exact up to " - f"Lie order {ui['exact_order']}, below the orders the analysis took; the rank " - f"holds at Lie order {ui['exact_order']}") + session.note( + "limits", + f"unknown inputs: the {ui['jet_order']} jets of each input are exact up to " + f"Lie order {ui['exact_order']}, below the orders the analysis took; the rank " + f"holds at Lie order {ui['exact_order']}", + ) return res def _gauged(kw): """The gauged detection on the arguments `kw`, unknown inputs included.""" from ..gfp import all_primes + gp = kw["gauge_preference"] pref = None if gp is None else [gp] if isinstance(gp, str) else list(gp) - res = gauged_detection({k: v for k, v in kw.items() if k != "gauge_preference"}, pref, kw.get("fixed"), - kw.get("reconstruct")) + res = gauged_detection( + {k: v for k, v in kw.items() if k != "gauge_preference"}, pref, kw.get("fixed"), kw.get("reconstruct") + ) ses = state.get("session") if ses is not None and ses.depth == 1: ses.primes = all_primes() @@ -515,8 +585,14 @@ def _with_known_inputs(kw, known, order): """The arguments with each known input a chain of `order` jets whose initial values are fixed symbols.""" taken = set(get_symbols(_model_texts(kw))) | set(dict(kw.get("f") or {})) f, jets = _input_jets(dict(kw["f"]), known, int(order), taken) - kw = dict(kw, known_order={"names": list(known), "jet_order": int(order), - "states": [x for names in jets.values() for x in names]}) + kw = dict( + kw, + known_order={ + "names": list(known), + "jet_order": int(order), + "states": [x for names in jets.values() for x in names], + }, + ) start = {x: f"{x}_0" for names in jets.values() for x in names} clash = [v for v in start.values() if v in taken] if clash: @@ -524,8 +600,9 @@ def _with_known_inputs(kw, known, order): fixed = list(kw.get("fixed") or []) + list(start.values()) if kw.get("equilibrate"): # zero at rest like every input, the jets known from the start on - events = as_events(kw.get("events")) + [{"var": x, "time": "0", "value": v, "method": "replace", - "root": None} for x, v in start.items()] + events = as_events(kw.get("events")) + [ + {"var": x, "time": "0", "value": v, "method": "replace", "root": None} for x, v in start.items() + ] return dict(kw, f=f, fixed=fixed, events=events, forcings=list(kw.get("forcings") or []) + list(start)) trafo = kw.get("trafo") if isinstance(trafo, (list, tuple)): @@ -551,7 +628,7 @@ def _held(kw): for key in ("forcings", "fixed", "unknown_inputs"): held |= {str(u) for u in kw.get(key) or []} tr = kw.get("trafo") - for t in (tr if isinstance(tr, (list, tuple)) else [tr]): + for t in tr if isinstance(tr, (list, tuple)) else [tr]: held |= set(dict(t or {})) | _symbols_of(dict(t or {}).values()) grid = Grid.from_any(kw.get("conditions")) if grid is not None: @@ -566,8 +643,11 @@ def _excluded_coords(kw, hy): hg = hy["g"] if isinstance(hy["g"], (list, tuple)) else [hy["g"]] after = _symbols_of(list(hy["f"].values()) + [v for x in hg if x for v in dict(x).values()]) else: - after = {str(a) for e in list(hy.f.values()) + [v for x in hy.g for v in x.values()] + list(hy.sw.funcs) - for a in e.free_symbols} + after = { + str(a) + for e in list(hy.f.values()) + [v for x in hy.g for v in x.values()] + list(hy.sw.funcs) + for a in e.free_symbols + } return sym_sort(_model_symbols(kw) - after - _held(kw)) @@ -576,10 +656,16 @@ def _lost_coords(kw, kw2): return sym_sort(_model_symbols(kw) - _model_symbols(kw2) - _held(kw) - _held(kw2)) -def _with_excluded(res, names, positive, route="a coordinate of excluded regimes only", - proof="full rank on the coordinates of the allowed regimes"): +def _with_excluded( + res, + names, + positive, + route="a coordinate of excluded regimes only", + proof="full rank on the coordinates of the allowed regimes", +): """The result with each coordinate of `names` as a separate direction, exact: no observable depends on it.""" from .finalize import complete, display_form + info = res.get("info") if isinstance(res, dict) else None if not names or not isinstance(info, dict) or info.get("coordinates") is None: return res @@ -587,9 +673,22 @@ def _with_excluded(res, names, positive, route="a coordinate of excluded regimes if not names: return res info["coordinates"] = list(info["coordinates"]) + names - dirs = [{"type": "general", "generator": {z: "1"}, "weights": None, "degree": 0, "support": [z], - "explicit": True, "reason": None, "route": route, "level": "exact", - "state_components": None, "input_change": None} for z in names] + dirs = [ + { + "type": "general", + "generator": {z: "1"}, + "weights": None, + "degree": 0, + "support": [z], + "explicit": True, + "reason": None, + "route": route, + "level": "exact", + "state_components": None, + "input_change": None, + } + for z in names + ] res["symmetries"] = list(res.get("symmetries") or []) + complete(display_form(dirs), positive, info["coordinates"]) if res.get("dim") is None: return res @@ -612,6 +711,7 @@ def symmetry_detection(*args, **kw): """The detection on plain inputs (see _symmetry_detection); a model with switches that the declared signs leave open goes to the hybrid analysis.""" import inspect + known = [str(u) for u in kw.pop("known_inputs", None) or []] kw = dict(inspect.signature(_symmetry_detection).bind(*args, **kw).arguments) if state.get("session") is None: @@ -642,14 +742,22 @@ def _quality(raw): lv = [s.get("level") for s in syms] kinds = [s.get("kind") for s in syms] status = ((raw.get("info") or {}).get("rank_status") or {}).get("status") - return (_STATUS.get(status, 0), raw.get("rank") or 0, lv.count("exact"), lv.count("exact") + lv.count("verified"), - sum(x != "open" for x in lv), kinds.count("scaling"), kinds.count("scaling") + kinds.count("translation")) + return ( + _STATUS.get(status, 0), + raw.get("rank") or 0, + lv.count("exact"), + lv.count("exact") + lv.count("verified"), + sum(x != "open" for x in lv), + kinds.count("scaling"), + kinds.count("scaling") + kinds.count("translation"), + ) def _settled(raw): """Whether no pivot set gives a better result: a proven rank and exact scalings only.""" - return ((raw.get("info") or {}).get("rank_status") or {}).get("status") == "proven" and \ - all(s.get("level") == "exact" and s.get("kind") == "scaling" for s in raw.get("symmetries") or []) + return ((raw.get("info") or {}).get("rank_status") or {}).get("status") == "proven" and all( + s.get("level") == "exact" and s.get("kind") == "scaling" for s in raw.get("symmetries") or [] + ) def _n_open(raw): @@ -669,6 +777,7 @@ def alt(pivots): r = run(None, pivots) if reduce_cq else run(pivots, None) (r.get("info") or {}).pop("pivot_sets", None) return r + for pivots in sets.get("ties") or []: if _settled(raw): break @@ -689,6 +798,7 @@ def alt(pivots): def _with_kinds(res): """The result with the orbit geometry of each direction under "kind": scaling, translation or curved.""" from .classify import orbit_kind + for d in res.get("symmetries") or []: d["kind"] = orbit_kind(d) return res @@ -696,8 +806,11 @@ def _with_kinds(res): def _numeric_base_note(fixed): """The limit that holding b^n of a number b as a constant leaves in the result.""" - return ("a power b^n of the number " + ", ".join(str(b) for b in fixed.values()) - + " is held as a generic constant, with log(b) independent of the other constants") + return ( + "a power b^n of the number " + + ", ".join(str(b) for b in fixed.values()) + + " is held as a generic constant, with log(b) independent of the other constants" + ) def _detect_known(kw, known): @@ -723,17 +836,21 @@ def _detection(kw): regimes = kw.pop("regimes", None) hy = None if kw.get("f") is not None: - hy = hybrid_model({str(k): str(v) for k, v in dict(kw["f"]).items()}, kw.get("g"), - kw.get("positive", True), events=kw.get("events"), - inputs=kw.get("forcings") or (), taken=kw.get("parameters") or ()) + hy = hybrid_model( + {str(k): str(v) for k, v in dict(kw["f"]).items()}, + kw.get("g"), + kw.get("positive", True), + events=kw.get("events"), + inputs=kw.get("forcings") or (), + taken=kw.get("parameters") or (), + ) _check_unknown_inputs(kw) excluded = _excluded_coords(kw, hy) if hy is not None else [] if isinstance(hy, dict): kw.update(f=hy["f"], g=hy["g"]) hy = None if hy is None and regimes is not None: - raise ValueError("`regimes` names regimes, but the model has no switch that the " - "declared signs leave open") + raise ValueError("`regimes` names regimes, but the model has no switch that the declared signs leave open") outer = state.get("session") is None if outer: state.check_names() @@ -744,6 +861,7 @@ def _detection(kw): try: if hy is not None: from .hybrid import hybrid_detection, zero_restriction + kw2, zero, notes, setup = zero_restriction(hy, kw, regimes) for n in notes: session.note("limits", n) @@ -751,9 +869,13 @@ def _detection(kw): res = _detection(kw2) kw_res = kw2 switched = isinstance(res, dict) and bool((res.get("info") or {}).get("switching")) - res = _with_excluded(res, _lost_coords(kw, kw2), kw.get("positive", True), - "a coordinate that only states at zero read", - "full rank on the coordinates the states away from zero read") + res = _with_excluded( + res, + _lost_coords(kw, kw2), + kw.get("positive", True), + "a coordinate that only states at zero read", + "full rank on the coordinates the states away from zero read", + ) else: res = hybrid_detection(hy, kw, regimes, setup) elif kw.get("gauge_preference", False) is not False and not kw.get("scalings_only"): @@ -763,8 +885,13 @@ def _detection(kw): res = _with_excluded(res, excluded, kw.get("positive", True)) finally: ses.depth -= 1 - if outer and not switched and isinstance(res, dict) and isinstance(res.get("info"), dict) \ - and res["info"].get("bound") is None: + if ( + outer + and not switched + and isinstance(res, dict) + and isinstance(res.get("info"), dict) + and res["info"].get("bound") is None + ): res["info"]["bound"] = _kernel_bound(kw_res, res) if outer and isinstance(res, dict) and isinstance(res.get("info"), dict): res["info"]["zero_states"] = zero or None @@ -774,11 +901,16 @@ def _detection(kw): pj = res["info"].get("projection") or {} if pj.get("status") == "verified" and pj.get("probability") is None: pj["probability"] = _projection_bound(kw_res, res) - if outer and isinstance(res, dict) and isinstance(res.get("info"), dict) and \ - res.get("method") == "observability": + if ( + outer + and isinstance(res, dict) + and isinstance(res.get("info"), dict) + and res.get("method") == "observability" + ): res["info"]["rank_status"] = _rank_status(res) if outer and isinstance(res, dict) and isinstance(res.get("info"), dict): from .. import __version__ + res["info"]["limits"] = list(ses.notes["limits"]) res["info"]["errors"] = list(ses.notes["errors"]) res["info"]["branches"] = list(ses.notes["branches"]) @@ -787,10 +919,12 @@ def _detection(kw): st = res["info"].setdefault("settings", {}) if getattr(ses, "rest_leaves", None): st["rest_leaves"] = ses.rest_leaves - st.update(control=dict(ses.control), - switches={n: v for n, v in state.active().items() - if state.SWITCHES.get(n, ("",))[0] != "install"}, - primes=ses.primes, version=__version__) + st.update( + control=dict(ses.control), + switches={n: v for n, v in state.active().items() if state.SWITCHES.get(n, ("",))[0] != "install"}, + primes=ses.primes, + version=__version__, + ) res["info"]["assumptions"] = _assumptions(res) return res @@ -799,6 +933,7 @@ def _rest_check(multi, equil_zero, cond_zero, forcings, positive): """The resting balances solved at random parameter values, once per session: an InputError without a solution over the complex numbers, a warning and info["resting"] where no solution lies in the declared domain.""" from ..sym.restcheck import rest_check + ses = session.current() key = tuple(tuple(t.get("constraint_model") or ()) for t in multi.get("tapes") or []) if getattr(ses, "resting_key", None) == key: @@ -808,13 +943,17 @@ def _rest_check(multi, equil_zero, cond_zero, forcings, positive): def zero_of(ti): return fixed | set(cond_zero[ti] if ti < len(cond_zero) else []) + rep = rest_check(multi, zero_of, positive) ses.resting = rep if rep and rep.get("checked") and rep["points"] and rep["in_domain"] + rep["undecided"] < rep["points"]: n_out = rep["points"] - rep["in_domain"] - rep["undecided"] - warnings.warn(f"equilibrate: at {n_out} of {rep['points']} random parameter values the resting balances " - "have no solution in the declared domain (real, positive where declared positive); " - "info['resting'] has the counts, from a check at random points, not a proof", stacklevel=2) + warnings.warn( + f"equilibrate: at {n_out} of {rep['points']} random parameter values the resting balances " + "have no solution in the declared domain (real, positive where declared positive); " + "info['resting'] has the counts, from a check at random points, not a proof", + stacklevel=2, + ) def _rest_leaves(multi): @@ -834,7 +973,8 @@ def _rest_leaves(multi): leaves.setdefault(z, []).append(back.get(W, W).replace("**", "^")) session.current().rest_leaves = { "states": {x: sorted(set(v)) for x, v in sorted(leaves.items())}, - "drawn": {x: back.get(w, w).replace("**", "^") for x, w in sorted(inv.items())}} + "drawn": {x: back.get(w, w).replace("**", "^") for x, w in sorted(inv.items())}, + } def _checked_without_bound(res): @@ -852,12 +992,17 @@ def _assumptions(res): info = res["info"] b = info.get("bound") levels = [s.get("level") for s in res.get("symmetries") or []] - starts = {c["name"]: c["declared"] for c in (info.get("switching") or {}).get("conditions") or [] - if c.get("declared")} + starts = { + c["name"]: c["declared"] for c in (info.get("switching") or {}).get("conditions") or [] if c.get("declared") + } rs = info.get("rank_status") or {} - return {"domain": (info.get("settings") or {}).get("positive", True), "starts": starts or None, - "error_bound": b.get("probability") if isinstance(b, dict) and "verified" in levels else - (rs.get("probability") if rs.get("status") == "verified" else None)} + return { + "domain": (info.get("settings") or {}).get("positive", True), + "starts": starts or None, + "error_bound": b.get("probability") + if isinstance(b, dict) and "verified" in levels + else (rs.get("probability") if rs.get("status") == "verified" else None), + } def _past_premature_order(oam, out, tries=3): @@ -884,11 +1029,15 @@ def _rank_status(res): return st of = pj.get("of", "the unknown inputs") if pj.get("status") == "verified" and pj.get("probability") is not None: - return {"status": "verified", "probability": float(min(1.0, pj["probability"] + (st["probability"] or 0))), - "why": f"{st['why']}; the rank modulo {of} holds at a random point modulo a prime"} - why = {"differs": f"the rank modulo {of} differs between the base point and a random point", - "unchecked": f"the rank modulo {of} rests on the base point, where their columns may drop rank"}.get( - pj.get("status"), f"the rank modulo {of} holds at a random point, without an error bound") + return { + "status": "verified", + "probability": float(min(1.0, pj["probability"] + (st["probability"] or 0))), + "why": f"{st['why']}; the rank modulo {of} holds at a random point modulo a prime", + } + why = { + "differs": f"the rank modulo {of} differs between the base point and a random point", + "unchecked": f"the rank modulo {of} rests on the base point, where their columns may drop rank", + }.get(pj.get("status"), f"the rank modulo {of} holds at a random point, without an error bound") return {"status": "lower bound", "why": why, "probability": None} @@ -903,23 +1052,32 @@ def _rank_status_plain(res): return {"status": "proven", "why": info.get("rank_proof"), "probability": None} sw = (info.get("switching") or {}).get("uncertified") if sw: - return {"status": "lower bound", "probability": None, - "why": "the rule of the switches is not proven for every direction"} + return { + "status": "lower bound", + "probability": None, + "why": "the rule of the switches is not proven for every direction", + } fields = None if info.get("rank_fields") is not None: b = info.get("rank_fields_bound") or {} if b.get("probability") is not None: - return {"status": "verified", "probability": b["probability"], - "why": "invariant fields hold the kernel at every order, checked at random points " - "modulo a prime"} + return { + "status": "verified", + "probability": b["probability"], + "why": "invariant fields hold the kernel at every order, checked at random points modulo a prime", + } # without a bound of the fields, verified closed forms with a bound still verify the rank - fields = {"status": "lower bound", "probability": None, - "why": "invariant fields hold the kernel at every order, checked at random points modulo " - f"a prime without an error bound ({b.get('why') or 'not taken'})"} + fields = { + "status": "lower bound", + "probability": None, + "why": "invariant fields hold the kernel at every order, checked at random points modulo " + f"a prime without an error bound ({b.get('why') or 'not taken'})", + } syms = res.get("symmetries") or [] if info.get("engine") == "symbolic" and not info.get("lie_certified"): - why = "the Lie order of the symbolic engine is not proven sufficient" + \ - (f": {info['lie_certificate']}" if info.get("lie_certificate") else "") + why = "the Lie order of the symbolic engine is not proven sufficient" + ( + f": {info['lie_certificate']}" if info.get("lie_certificate") else "" + ) elif (info.get("unknown_inputs") or {}).get("short"): why = "the jet chains of the unknown inputs end below the Lie order reached" elif not info.get("lie_certified"): @@ -937,9 +1095,12 @@ def _rank_status_plain(res): elif not isinstance(info.get("bound"), dict) or info["bound"].get("probability") is None: why = "the closed forms have no error bound" else: - return {"status": "verified", "probability": info["bound"]["probability"], - "why": "every direction is closed and lies in the kernel; the rank holds unless a " - "verified closed form is wrong"} + return { + "status": "verified", + "probability": info["bound"]["probability"], + "why": "every direction is closed and lies in the kernel; the rank holds unless a " + "verified closed form is wrong", + } return fields or {"status": "lower bound", "why": why, "probability": None} @@ -957,10 +1118,16 @@ def _gap_settled(info): def _bound_needs_orders(info): """info["bound"] plus the chance of a wrong certified order, dropped where an unproven order leaves it open.""" b = info.get("bound") - fields = info.get("rank_fields") is not None and \ - (info.get("rank_fields_bound") or {}).get("probability") is not None - if not isinstance(b, dict) or b.get("probability") is None or info.get("engine") == "symbolic" or \ - info.get("rank_proven") is not None or fields: + fields = ( + info.get("rank_fields") is not None and (info.get("rank_fields_bound") or {}).get("probability") is not None + ) + if ( + not isinstance(b, dict) + or b.get("probability") is None + or info.get("engine") == "symbolic" + or info.get("rank_proven") is not None + or fields + ): return if not info.get("lie_certified"): why = "the Lie order is not proven sufficient" @@ -969,14 +1136,15 @@ def _bound_needs_orders(info): elif info.get("gap_certified") is False: why = "the gap order is not proven sufficient" elif info.get("order_bound") is None: - why = "the certified orders have no error bound" + \ - (f" ({info['order_bound_why']})" if info.get("order_bound_why") else "") + why = "the certified orders have no error bound" + ( + f" ({info['order_bound_why']})" if info.get("order_bound_why") else "" + ) else: - info["bound"] = dict(b, probability=float(min(1.0, b["probability"] + info["order_bound"])), - orders=float(info["order_bound"])) + info["bound"] = dict( + b, probability=float(min(1.0, b["probability"] + info["order_bound"])), orders=float(info["order_bound"]) + ) return - info["bound"] = dict(b, probability=None, applies=False, - why=f"{why}, and the check runs at the order reached") + info["bound"] = dict(b, probability=None, applies=False, why=f"{why}, and the check runs at the order reached") def _projection_bound(kw, res): @@ -996,11 +1164,11 @@ def _projection_bound(kw, res): def _kernel_bound(kw, res): """The kernel-check error bound of the verified directions, or why it does not apply; None without them.""" - vecs = [s["generator"] for s in res.get("symmetries") or [] - if s.get("level") == "verified" and s.get("generator")] + vecs = [s["generator"] for s in res.get("symmetries") or [] if s.get("level") == "verified" and s.get("generator")] if not vecs: return None from .bound import drawn + return _model_bound(kw, res, vecs, 2, int(res["info"].get("lie_order_used") or 0), drawn(2)) @@ -1008,6 +1176,7 @@ def _model_bound(kw, res, vecs, points, order, draws=None): """kernel_bound() of `vecs` over the model of `kw` up to Lie order `order`, worst over trafos and observables.""" from ..gfp import verify_prime from .bound import kernel_bound, no_degree + if (res.get("info") or {}).get("engine") == "symbolic": return {"applies": False, "why": "the symbolic engine takes the kernel exactly, up to the Lie order used"} if kw.get("equilibrate"): @@ -1041,8 +1210,9 @@ def _model_bound(kw, res, vecs, points, order, draws=None): x0 = {x: "0" if x in inputs else tr.get(x, x) for x in f} for e in evs: x, v = str(e["var"]), str(e["value"]) - x0[x] = {"add": f"({x0.get(x, x)}) + ({v})", "replace": v, - "multiply": f"({x0.get(x, x)})*({v})"}[e.get("method", "replace")] + x0[x] = {"add": f"({x0.get(x, x)}) + ({v})", "replace": v, "multiply": f"({x0.get(x, x)})*({v})"}[ + e.get("method", "replace") + ] # the rules of `sub` parsed once per trafo, the texts once per call memo = {"parsed": parsed} fs = {x: _subs(rhs, sub, memo) for x, rhs in f.items()} @@ -1050,11 +1220,13 @@ def _model_bound(kw, res, vecs, points, order, draws=None): for g in gs: gg = {str(k): _subs(str(v), sub, memo) for k, v in dict(g or {}).items()} grp = [[dict(e, value=_subs(str(e["value"]), sub, memo)) for e in g_] for g_ in later] - b = kernel_bound(fs, gg, x0, order, vecs, verify_prime(), points, events=grp, gap_order=gap_order, - draws=draws) + b = kernel_bound( + fs, gg, x0, order, vecs, verify_prime(), points, events=grp, gap_order=gap_order, draws=draws + ) if b is None: - why = no_degree(list(fs.values()) + list(gg.values()) + list(x0.values()) + - [c for v in vecs for c in v.values()]) + why = no_degree( + list(fs.values()) + list(gg.values()) + list(x0.values()) + [c for v in vecs for c in v.values()] + ) return {"applies": False, "why": why or "a term has no degree bound"} out = b if out is None or b["probability"] > out["probability"] else out return out @@ -1065,6 +1237,7 @@ def _log_back(expr, la): if la is None: return str(expr) import sympy as spy + at = {spy.Symbol(m["L"]): spy.log(spy.Symbol(m["v"])) for m in la["map"]} return to_r(model_sympify(str(expr)).xreplace(at)) @@ -1077,9 +1250,15 @@ def _scalings_without_jets(dirs, jets): vec = {k: v for k, v in (d.get("vector") or {}).items() if k not in every} if not vec: continue - out.append(dict(d, vector=vec, support=sym_sort(list(vec)), - input_vector={w: scaling_component(d["vector"].get(w, "0"), w) for w in jets}, - input_form={k: scaling_component(v, k) for k, v in vec.items()})) + out.append( + dict( + d, + vector=vec, + support=sym_sort(list(vec)), + input_vector={w: scaling_component(d["vector"].get(w, "0"), w) for w in jets}, + input_form={k: scaling_component(v, k) for k, v in vec.items()}, + ) + ) return out @@ -1089,6 +1268,7 @@ def _resolved_scalings(fdyn, gset, g_per_cond, res, inputs, fixed, jets, multi, coordinates of the compiled tapes `multi` (None: the free or `held` states and the parameters), with the jet weights; with `rest_zero`, the inputs at rest, a start at rest also holds the resting model.""" import sympy as spy + model, obs, xm, xo = [], [], [], [] for i, subs in enumerate(res["subs"]): sub = subst(list(subs), list(subs.values())) @@ -1097,21 +1277,35 @@ def _resolved_scalings(fdyn, gset, g_per_cond, res, inputs, fixed, jets, multi, model.append(eqn_lines(sub(dict(fdyn)))) g = gset[res["chain_of"][i] - 1] if g_per_cond else gset[0] obs.append(eqn_lines(sub(dict(g or {}))) or []) - xm.append([f"{k} = {sub(v)}" for k, v in (res["ic0"][i] if first else {}).items()] + - [f"{e['var']} = {sub(e['value'])}" for e in evs if e["method"] != "multiply"]) + xm.append( + [f"{k} = {sub(v)}" for k, v in (res["ic0"][i] if first else {}).items()] + + [f"{e['var']} = {sub(e['value'])}" for e in evs if e["method"] != "multiply"] + ) if first and rest_zero is not None and res["seg_equil"][i]: at_rest = {k: v for k, v in subs.items() if k not in set(rest_zero)} at_rest.update(res["rest_subs"][i]) at_rest.update({u: "0" for u in rest_zero}) rest = subst(list(at_rest), list(at_rest.values())) xm[-1] += [f"{k} = {rest(v)}" for k, v in fdyn.items()] - xo.append([f"_ = {sub(e['value'])}" for e in evs if e["method"] == "multiply"] + - ([f"_ = {res['times'][i]}"] if get_symbols([res["times"][i]]) else [])) - r = scaling_symmetries_multi(per_cond_model=model, per_cond_obs=obs, inputs=inputs or None, - fixed=fixed or None, logs=True, extra_model=xm, extra_obs=xo) + xo.append( + [f"_ = {sub(e['value'])}" for e in evs if e["method"] == "multiply"] + + ([f"_ = {res['times'][i]}"] if get_symbols([res["times"][i]]) else []) + ) + r = scaling_symmetries_multi( + per_cond_model=model, + per_cond_obs=obs, + inputs=inputs or None, + fixed=fixed or None, + logs=True, + extra_model=xm, + extra_obs=xo, + ) if r.get("skipped"): - session.note("limits", f"scalings: {r['skipped']} term(s) without polynomial form left out of the " - "scaling conditions; a scaling they forbid may be reported") + session.note( + "limits", + f"scalings: {r['skipped']} term(s) without polynomial form left out of the " + "scaling conditions; a scaling they forbid may be reported", + ) every = {x for names in jets.values() for x in names} if multi is not None: drop = set(multi.get("z_state_names") or []) if multi.get("joint_steady_state") else set() @@ -1120,9 +1314,17 @@ def _resolved_scalings(fdyn, gset, g_per_cond, res, inputs, fixed, jets, multi, coords = [back.get(z, z) for z in multi["znames"] if z not in drop | set(multi.get("nuisance") or [])] else: # at rest only the held states keep a value of their own - free = set(held) if held is not None else { - x for i, ic in enumerate(res["ic0"]) if res["pos_in_chain"][i] == 1 - for x in fdyn if x not in ic or x in get_symbols([ic[x]])} + free = ( + set(held) + if held is not None + else { + x + for i, ic in enumerate(res["ic0"]) + if res["pos_in_chain"][i] == 1 + for x in fdyn + if x not in ic or x in get_symbols([ic[x]]) + } + ) coords = [z for z in r["coordinates"] if (z in free or z not in fdyn) and z not in set(fixed) | every] rows, dirs = [], [] for d in r.get("non_identifiable") or []: @@ -1160,6 +1362,7 @@ def _subs(text, sub, memo=None): if not sub: return str(text) import sympy as spy + memo = {} if memo is None else memo if "rule" not in memo: memo["rule"] = {spy.Symbol(k): model_sympify(v) for k, v in sub.items()} @@ -1175,6 +1378,7 @@ def detection_with_primes(kw): import contextlib from ..gfp import NeedPrimesError, all_primes, use_primes + consts, degrees = [], [] while True: try: @@ -1193,13 +1397,35 @@ def detection_with_primes(kw): degrees += new_d -def _symmetry_detection(f=None, g=None, trafo=None, parameters=None, fixed=None, - gauge_preference=False, forcings=None, events=None, conditions=None, - equilibrate=False, reduce_cq=False, free_initial=None, reconstruct=False, - positive=True, verify=True, cores=1, control=None, scalings_only=False, - sym_engine="modular", reactions=None, totals=None, - regimes=None, unknown_inputs=None, jet_order=None, nuisance=None, known_order=None, - cq_pivots=None): +def _symmetry_detection( + f=None, + g=None, + trafo=None, + parameters=None, + fixed=None, + gauge_preference=False, + forcings=None, + events=None, + conditions=None, + equilibrate=False, + reduce_cq=False, + free_initial=None, + reconstruct=False, + positive=True, + verify=True, + cores=1, + control=None, + scalings_only=False, + sym_engine="modular", + reactions=None, + totals=None, + regimes=None, + unknown_inputs=None, + jet_order=None, + nuisance=None, + known_order=None, + cq_pivots=None, +): """The result dictionary of the detection on plain inputs; `cq_pivots` are the species that `reduce_cq` eliminates, chosen by structure when None.""" control = {**reconst_control(), **dict(control or {})} @@ -1208,9 +1434,16 @@ def _symmetry_detection(f=None, g=None, trafo=None, parameters=None, fixed=None, if gauge_preference is not False and scalings_only: warnings.warn("`gauge` applies only without `scalings_only` and is ignored.", stacklevel=2) t0clock = time.monotonic() - settings = {"positive": positive, "reduce_cq": bool(reduce_cq), "equilibrate": equilibrate, - "reconstruct": bool(reconstruct), "verify": bool(verify), "sym_engine": sym_engine, - "degree_cap": control["degree_cap"], "scalings_only": bool(scalings_only)} + settings = { + "positive": positive, + "reduce_cq": bool(reduce_cq), + "equilibrate": equilibrate, + "reconstruct": bool(reconstruct), + "verify": bool(verify), + "sym_engine": sym_engine, + "degree_cap": control["degree_cap"], + "scalings_only": bool(scalings_only), + } ic_from, ic_to = [], [] log_arg = None chart_coords = [] @@ -1230,8 +1463,9 @@ def deliver(raw, method): res["info"]["pivot_sets"] = dict(pivot_box) res["info"]["model_exprs"] = model_exprs_box["v"] res["info"]["model_rhs"] = model_exprs_box["rhs"] - res["info"]["log_coordinates"] = [c for c in model_exprs_box.get("log") or [] - if c in set(res["info"].get("coordinates") or ())] + res["info"]["log_coordinates"] = [ + c for c in model_exprs_box.get("log") or [] if c in set(res["info"].get("coordinates") or ()) + ] res["info"]["model_inputs"] = list(forcings) if jets: every = {x for names in jets.values() for x in names} @@ -1242,35 +1476,51 @@ def deliver(raw, method): lift = s.get("state_components") or {} ch = lift if any(w in lift for w in jets) else (s.get("input_change") or {}) # a lift in the log coordinate of an input has no closed form in the input here - s["input_change"] = {w: _log_back(ch.get(w, "0"), log_arg) for w in jets} \ - if s.get("level") == "exact" and not charted & set(lift) else None + s["input_change"] = ( + {w: _log_back(ch.get(w, "0"), log_arg) for w in jets} + if s.get("level") == "exact" and not charted & set(lift) + else None + ) if lift: # the states of the model, without the jets and the atoms of a recast - s["state_components"] = {k: v for k, v in lift.items() - if k in model_exprs_box["rhs"] and k not in every} or None + s["state_components"] = { + k: v for k, v in lift.items() if k in model_exprs_box["rhs"] and k not in every + } or None nu = raw.get("nuisance") or {} res["info"]["unknown_inputs"] = { - "names": list(jets), "jets": jets, "jet_order": int(jet_order), - "exact_order": nu.get("exact_order"), "short": bool(nu.get("short")), - "nuisance_rank": None if not nu else len(nu["names"]) - int(nu["pinned"])} + "names": list(jets), + "jets": jets, + "jet_order": int(jet_order), + "exact_order": nu.get("exact_order"), + "short": bool(nu.get("short")), + "nuisance_rank": None if not nu else len(nu["names"]) - int(nu["pinned"]), + } elif nuisance and raw.get("nuisance"): nu = raw["nuisance"] - res["info"]["nuisance"] = {"exact_order": nu["exact_order"], "short": bool(nu["short"]), - "rank": len(nu["names"]) - int(nu["pinned"])} + res["info"]["nuisance"] = { + "exact_order": nu["exact_order"], + "short": bool(nu["short"]), + "rank": len(nu["names"]) - int(nu["pinned"]), + } if known_order: - res["info"]["known_inputs"] = {"names": list(known_order["names"]), - "jet_order": int(known_order["jet_order"]), - "exact_order": int(known_order["jet_order"]) - 1, - "short": bool(raw.get("known_short"))} + res["info"]["known_inputs"] = { + "names": list(known_order["names"]), + "jet_order": int(known_order["jet_order"]), + "exact_order": int(known_order["jet_order"]) - 1, + "short": bool(raw.get("known_short")), + } if raw.get("known_short"): - session.note("limits", f"known inputs: the {known_order['jet_order']} jets of each input are " - f"exact up to Lie order {int(known_order['jet_order']) - 1}, below the orders " - "the analysis took") + session.note( + "limits", + f"known inputs: the {known_order['jet_order']} jets of each input are " + f"exact up to Lie order {int(known_order['jet_order']) - 1}, below the orders " + "the analysis took", + ) if raw.get("kernel") is not None and not state.get("inner") and not state.get("keep_kernel"): try: - res["info"]["gauge_suggestion"] = gauge_suggest(res["symmetries"], raw["kernel"], - res["info"]["coordinates"], - fixed=fixed) + res["info"]["gauge_suggestion"] = gauge_suggest( + res["symmetries"], raw["kernel"], res["info"]["coordinates"], fixed=fixed + ) except Exception as exc: swallow(exc, "gauge suggestion") res["info"]["gauge_suggestion"] = None @@ -1285,8 +1535,12 @@ def deliver(raw, method): raise ValueError("`observables` is an empty list; give one dict per condition.") jets = {} if unknown_inputs: - taken = set(get_symbols(list(fdyn.values()) + [v for x in gset if x for v in x.values()])) | \ - set(fdyn) | set(fixed) | set(parameters or []) + taken = ( + set(get_symbols(list(fdyn.values()) + [v for x in gset if x for v in x.values()])) + | set(fdyn) + | set(fixed) + | set(parameters or []) + ) fdyn, jets = _input_jets(fdyn, [str(w) for w in unknown_inputs], int(jet_order), taken) jet_start = {} if jets and equilibrate: @@ -1294,11 +1548,13 @@ def deliver(raw, method): jet_start = {x: f"{x}_0" for names in jets.values() for x in names} clash = [v for v in jet_start.values() if v in taken] if clash: - raise ValueError(f"{clash[0]} names a symbol of the model and the start value of an unknown " - "input; rename it") + raise ValueError( + f"{clash[0]} names a symbol of the model and the start value of an unknown input; rename it" + ) forcings = forcings + list(jet_start) - events = events + [{"var": x, "time": "0", "value": v, "method": "replace", "root": None} - for x, v in jet_start.items()] + events = events + [ + {"var": x, "time": "0", "value": v, "method": "replace", "root": None} for x, v in jet_start.items() + ] states = list(fdyn) def g_char(): @@ -1309,6 +1565,7 @@ def g_names(): def g_lines(k=0): return eqn_lines(gset[k]) + trafo_list = isinstance(trafo, (list, tuple)) zero = [] if equilibrate: @@ -1316,13 +1573,16 @@ def g_lines(k=0): zero = _free_zero_states(fdyn, reactions, forcings, held_free) _note_zero_branches(fdyn, zero, totals, forcings, held_free) fdyn, trafo, events, reactions, totals, held = _drop_sinks( - fdyn, g_char(), trafo, events, reactions, totals, forcings + list(free_initial or []), zero) + fdyn, g_char(), trafo, events, reactions, totals, forcings + list(free_initial or []), zero + ) fixed = list(dict.fromkeys(fixed + held)) states = list(fdyn) - trafo_vals = [] if trafo is None else ([v for t in trafo if t for v in dict(t).values()] - if trafo_list else list(dict(trafo).values())) - model_exprs_box["v"] = list(dict.fromkeys(list(fdyn.values()) + g_char() + - [str(v) for v in trafo_vals])) + trafo_vals = ( + [] + if trafo is None + else ([v for t in trafo if t for v in dict(t).values()] if trafo_list else list(dict(trafo).values())) + ) + model_exprs_box["v"] = list(dict.fromkeys(list(fdyn.values()) + g_char() + [str(v) for v in trafo_vals])) model_exprs_box["rhs"] = {k: str(v) for k, v in fdyn.items()} model_exprs_box["log"] = _log_coordinates(trafo, list(fdyn.values()) + g_char() + list(fdyn)) initial_box = {"v": None} @@ -1337,8 +1597,10 @@ def subst_model(fn): clash = [n for n in g_names() if n in states] if clash: - raise ValueError(f"observable(s) {', '.join(clash)} in `observables` have the " - f"name of a state in `odes`. Rename the observable(s) (e.g. {clash[0]}_obs).") + raise ValueError( + f"observable(s) {', '.join(clash)} in `observables` have the " + f"name of a state in `odes`. Rename the observable(s) (e.g. {clash[0]}_obs)." + ) parameters = list(parameters or []) free_initial = [str(x) for x in free_initial or []] if free_initial: @@ -1346,8 +1608,11 @@ def subst_model(fn): if bad: raise InputError(f"`free_initial` names {bad[0]}, which is not a state of `odes`") if free_initial and not (equilibrate and not reduce_cq): - warnings.warn("`free_initial` applies only with `equilibrate` and without `reduce_cq` " - "(the held-variable moiety parametrization); ignored.", stacklevel=2) + warnings.warn( + "`free_initial` applies only with `equilibrate` and without `reduce_cq` " + "(the held-variable moiety parametrization); ignored.", + stacklevel=2, + ) free_initial = [] cond_subs = None @@ -1360,8 +1625,7 @@ def subst_model(fn): trafos, ic_from, ic_to = ic_split["trafos"], ic_split["from"], ic_split["to"] is_state = set(states) cond_subs = [{k: v for k, v in tr.items() if k not in is_state} for tr in trafos] - cond_initial_box["v"] = [({k: v for k, v in tr.items() if k in is_state} or None) - for tr in trafos] + cond_initial_box["v"] = [({k: v for k, v in tr.items() if k in is_state} or None) for tr in trafos] trafo_syms = list(dict.fromkeys(s for tr in trafos for s in get_symbols(list(tr.values())))) elif trafo is not None: ic_split = initial_value_split([_clean(trafo)], states, taken=parameters + g_names()) @@ -1377,15 +1641,21 @@ def subst_model(fn): known |= set(get_symbols([e["value"] for e in events] + [e["time"] for e in events])) if conditions is not None: known |= set(conditions.colnames()) - known |= set(get_symbols([v for vals in conditions.cols.values() for v in vals - if isinstance(v, str)])) + known |= set(get_symbols([v for vals in conditions.cols.values() for v in vals if isinstance(v, str)])) trafo_hit = [k for k in trafo_subs if k in known] fdyn = _zeroed(fdyn, sub(fdyn)) subst_model(sub) if trafo_subs and conditions is not None: - conditions = Grid(conditions.rows, { - c: [replace_symbols(list(trafo_subs), list(trafo_subs.values()), v) if isinstance(v, str) else v - for v in vals] for c, vals in conditions.cols.items()}) + conditions = Grid( + conditions.rows, + { + c: [ + replace_symbols(list(trafo_subs), list(trafo_subs.values()), v) if isinstance(v, str) else v + for v in vals + ] + for c, vals in conditions.cols.items() + }, + ) if ic_entries: initial_box["v"] = sub({k: tr[k] for k in ic_entries}) if events and trafo_subs: @@ -1398,11 +1668,17 @@ def subst_model(fn): for e in events: e["value"] = replace_symbols(ic_from, ic_to, e["value"]) if conditions is not None: - over = [k for k in list(trafo_subs) + [k for cs in cond_subs or [] for k in cs] - if k in conditions.colnames() and k not in states] + over = [ + k + for k in list(trafo_subs) + [k for cs in cond_subs or [] for k in cs] + if k in conditions.colnames() and k not in states + ] if over: - warnings.warn(f"`trafo` replaces {', '.join(dict.fromkeys(over))}, which a condition column of that name " - "sets per condition; the column has no effect", stacklevel=2) + warnings.warn( + f"`trafo` replaces {', '.join(dict.fromkeys(over))}, which a condition column of that name " + "sets per condition; the column has no effect", + stacklevel=2, + ) if "time" not in states: tt0 = start_time(events, conditions, cond_subs, len(gset) if g_per_cond else 1) start = num_str(tt0) @@ -1428,30 +1704,47 @@ def subst_model(fn): if conditions is not None: keep = [c for c in conditions.colnames() if c not in set(states)] chr_ = [c for c in keep if conditions.is_character(c)] - hit = [s for s in get_symbols([str(v) for c in chr_ for v in conditions.cols[c]]) - if s in set(states) and s not in jets] if chr_ else [] + hit = ( + [ + s + for s in get_symbols([str(v) for c in chr_ for v in conditions.cols[c]]) + if s in set(states) and s not in jets + ] + if chr_ + else [] + ) if hit: - warnings.warn(f"condition-grid value(s) name the state(s) " - f"{', '.join(hit)}. A grid value is substituted into `odes`, where that name " - "is the running state and not an initial value. Pass it through a " - "per-condition `trafo` instead.", stacklevel=2) + warnings.warn( + f"condition-grid value(s) name the state(s) " + f"{', '.join(hit)}. A grid value is substituted into `odes`, where that name " + "is the running state and not an initial value. Pass it through a " + "per-condition `trafo` instead.", + stacklevel=2, + ) n_cond_obs = len(gset) if g_per_cond else 0 if g_per_cond: n_grid_g = 0 if conditions is None else conditions.nrow if n_grid_g and n_cond_obs != n_grid_g: - raise ValueError(f"the per-condition `observables` list length ({n_cond_obs}) " - f"must match the condition grid rows ({n_grid_g}).") + raise ValueError( + f"the per-condition `observables` list length ({n_cond_obs}) " + f"must match the condition grid rows ({n_grid_g})." + ) if cond_subs and n_cond_obs != len(cond_subs): - raise ValueError(f"the per-condition `observables` list length ({n_cond_obs}) " - f"must match the per-condition `trafo` list length ({len(cond_subs)}).") - ic_names = list(dict.fromkeys(list(initial_box["v"] or {}) + - [k for ci in (cond_initial_box["v"] or []) if ci for k in ci])) + raise ValueError( + f"the per-condition `observables` list length ({n_cond_obs}) " + f"must match the per-condition `trafo` list length ({len(cond_subs)})." + ) + ic_names = list( + dict.fromkeys(list(initial_box["v"] or {}) + [k for ci in (cond_initial_box["v"] or []) if ci for k in ci]) + ) if equilibrate and ic_names: # inputs are zero at rest whatever their initial value told = [x for x in ic_names if x not in set(forcings)] if told: - msg = ("`equilibrate` solves the steady state from f = 0; the " - f"initial condition(s) for {', '.join(told)} in `trafo` are ignored.") + msg = ( + "`equilibrate` solves the steady state from f = 0; the " + f"initial condition(s) for {', '.join(told)} in `trafo` are ignored." + ) warnings.warn(msg, stacklevel=2) session.note("limits", msg) initial_box["v"] = None @@ -1467,21 +1760,36 @@ def subst_model(fn): avoid_cq = free_exponent_bases(list(fdyn.values()) + g_char(), list(fdyn)) + told + list(zero) + forcings # an observed species stays a state seen = set(get_symbols(g_char())) - cq = substitute_cq(totals, fdyn, list(fdyn), parameters, avoid=avoid_cq, prefer=cq_pivots or (), - extra={x: int(x in seen) for x in fdyn}) + cq = substitute_cq( + totals, + fdyn, + list(fdyn), + parameters, + avoid=avoid_cq, + prefer=cq_pivots or (), + extra={x: int(x in seen) for x in fdyn}, + ) clash_cq = [s for s in cq["elim_states"] if s in set(told)] if clash_cq: - warnings.warn("a `trafo` initial condition was supplied for " - f"{', '.join(clash_cq)}, which `reduce_cq` would eliminate through a conserved " - "quantity, discarding that relation. Forcing reduce_cq=False so the supplied " - "initial values are used as given.", stacklevel=2) + warnings.warn( + "a `trafo` initial condition was supplied for " + f"{', '.join(clash_cq)}, which `reduce_cq` would eliminate through a conserved " + "quantity, discarding that relation. Forcing reduce_cq=False so the supplied " + "initial values are used as given.", + stacklevel=2, + ) reduce_cq = False settings["reduce_cq"] = False + # a logarithm positive in the full model stays positive where the conserved quantities hold def off_domain(): ic_texts = [str(v) for d in [initial_box["v"]] + list(cond_initial_box["v"] or []) if d for v in d.values()] - return _off_domain(list(fdyn.values()) + g_char() + ic_texts + [str(e["value"]) for e in events], - positive, generic=list(fixed) + list(forcings)) + return _off_domain( + list(fdyn.values()) + g_char() + ic_texts + [str(e["value"]) for e in events], + positive, + generic=list(fixed) + list(forcings), + ) + off_full = off_domain() if reduce_cq and totals else None cq_moved = [] if reduce_cq and totals: @@ -1489,8 +1797,7 @@ def off_domain(): parameters = cq["parameters"] if cq["cq_info"]: cq_totals = [ci["total_name"] for ci in cq["cq_info"]] - subst_model(subst([ci["elim_state"] for ci in cq["cq_info"]], - [ci["recon_expr"] for ci in cq["cq_info"]])) + subst_model(subst([ci["elim_state"] for ci in cq["cq_info"]], [ci["recon_expr"] for ci in cq["cq_info"]])) # an event on a species of a total changes the total: the total is a state without dynamics events, cq_moved = cq_events(events, totals, cq["cq_info"]) for t in cq_moved: @@ -1513,14 +1820,21 @@ def off_domain(): if trafo_subs: miss = [k for k in trafo_subs if k not in trafo_hit] if miss: - warnings.warn(f"`trafo` entr{'y' if len(miss) == 1 else 'ies'} " - f"{', '.join(miss)} {'does' if len(miss) == 1 else 'do'} not occur in the " - "model and had no effect. Note that the `total` parameters of a conserved " - "quantity only exist with `reduce_cq`.", stacklevel=2) - if any(re.search(r"\b(abs|sign|max|min|pmax|pmin|ifelse|Heaviside)\s*\(", x) - for x in list(fdyn.values()) + g_char()): - sc = sign_chart(dict(fdyn), [dict(x or {}) for x in gset], - True if positive is True else ([] if positive is False else list(positive))) + warnings.warn( + f"`trafo` entr{'y' if len(miss) == 1 else 'ies'} " + f"{', '.join(miss)} {'does' if len(miss) == 1 else 'do'} not occur in the " + "model and had no effect. Note that the `total` parameters of a conserved " + "quantity only exist with `reduce_cq`.", + stacklevel=2, + ) + if any( + re.search(r"\b(abs|sign|max|min|pmax|pmin|ifelse|Heaviside)\s*\(", x) for x in list(fdyn.values()) + g_char() + ): + sc = sign_chart( + dict(fdyn), + [dict(x or {}) for x in gset], + True if positive is True else ([] if positive is False else list(positive)), + ) if sc.get("why") is not None: raise ValueError(f"{sc['why']}.") fdyn = {k: to_r(v) for k, v in sc["f"].items()} @@ -1528,19 +1842,23 @@ def off_domain(): off = None if cq_totals and off_full is None else off_domain() if positive is not False and method != "scaling" and sym_engine != "symbolic": # under equilibrate a dose leaves the state to the power recast, whose resting model stays rational - ev_ic = [] if equilibrate else \ - [{e["var"]: e["value"]} for e in events if e["method"] in ("replace", "multiply")] + ev_ic = ( + [] if equilibrate else [{e["var"]: e["value"]} for e in events if e["method"] in ("replace", "multiply")] + ) # condition columns and constant states without events become numbers per condition per_cond = set(conditions.colnames()) if conditions is not None else set() - for cs in (cond_subs or []): + for cs in cond_subs or []: per_cond |= set(cs) | set(get_symbols(list(cs.values()))) moved = {e["var"] for e in events} per_cond |= {k for k, r in fdyn.items() if eval_numeric(r) == 0 and k not in moved} - lc = log_arg_chart(dict(fdyn), [dict(x or {}) for x in gset], - True if positive is True else list(positive), - list(dict.fromkeys(parameters + g_names() + ic_to)), - [dict(initial_box["v"] or {})] + - [dict(x or {}) for x in (cond_initial_box["v"] or [])] + ev_ic, skip=per_cond) + lc = log_arg_chart( + dict(fdyn), + [dict(x or {}) for x in gset], + True if positive is True else list(positive), + list(dict.fromkeys(parameters + g_names() + ic_to)), + [dict(initial_box["v"] or {})] + [dict(x or {}) for x in (cond_initial_box["v"] or [])] + ev_ic, + skip=per_cond, + ) if lc is not None and lc.get("why") is not None: raise ValueError(f"{lc['why']}.") if lc is not None: @@ -1549,24 +1867,28 @@ def off_domain(): clashes = set(forcings) if conditions is not None: clashes |= set(conditions.colnames()) - for cs in (cond_subs or []): + for cs in cond_subs or []: clashes |= set(cs) | set(get_symbols(list(cs.values()))) clash_l = [v for v in vs if v in clashes] if clash_l: - raise ValueError(f"{', '.join(clash_l)} appear(s) inside log() or " - "under a fractional power and is analyzed as exp(log_); " - "inputs and conditions on it are not supported.") + raise ValueError( + f"{', '.join(clash_l)} appear(s) inside log() or " + "under a fractional power and is analyzed as exp(log_); " + "inputs and conditions on it are not supported." + ) def from_py(e): return {k: to_r(v) for k, v in e.items()} if e else None + fdyn = from_py(lc["f"]) states = list(fdyn) gset = [from_py(x) for x in lc["g"]] lognum = list(lc.get("consts") or []) if events: for e in events: - ce = log_arg_event(e["var"], e["value"], e["method"], lc["map"], - True if positive is True else list(positive)) + ce = log_arg_event( + e["var"], e["value"], e["method"], lc["map"], True if positive is True else list(positive) + ) if ce.get("why") is not None: raise ValueError(f"{ce['why']}.") e["var"] = ce["var"] @@ -1591,8 +1913,9 @@ def from_py(e): raise ValueError("root events are not supported; give the event a time.") sym_time = [e["time"] for e in events if not is_number(e["time"])] if sym_time and method == "observability" and sym_engine != "modular": - raise ValueError(f"an event time given in parameters " - f"({', '.join(dict.fromkeys(sym_time))}) needs the modular engine.") + raise ValueError( + f"an event time given in parameters ({', '.join(dict.fromkeys(sym_time))}) needs the modular engine." + ) initial = initial_box["v"] cond_initial = cond_initial_box["v"] @@ -1601,17 +1924,19 @@ def from_py(e): extra_syms += get_symbols(list(initial.values())) if events: extra_syms += get_symbols([e["value"] for e in events] + [e["time"] for e in events]) - for x in (cond_initial or []): + for x in cond_initial or []: if x is not None: extra_syms += get_symbols(list(x.values())) extra_syms += trafo_syms - symbols = list(dict.fromkeys(states + g_names() + get_symbols(list(fdyn.values()) + g_char()) + - extra_syms)) + symbols = list(dict.fromkeys(states + g_names() + get_symbols(list(fdyn.values()) + g_char()) + extra_syms)) const_states = [k for k, r in fdyn.items() if eval_numeric(r) == 0] # a constant state set by an event to a value of another state holds that value, not the running state while True: - dep = {e["var"] for e in events or [] if e["var"] in const_states and - set(get_symbols([str(e["value"])])) & (set(states) - set(const_states))} + dep = { + e["var"] + for e in events or [] + if e["var"] in const_states and set(get_symbols([str(e["value"])])) & (set(states) - set(const_states)) + } if not dep: break const_states = [k for k in const_states if k not in dep] @@ -1620,8 +1945,11 @@ def from_py(e): if equilibrate: # a signed net rate such as -k*(x - u) rests at zero without a dead producer; the states at zero in the # model before reduce_cq stay there - equil_zero = [s for s in list(zero) + _rest_zeros(fdyn, reactions if has_net else None, forcings, - free_initial) if s in states] + equil_zero = [ + s + for s in list(zero) + _rest_zeros(fdyn, reactions if has_net else None, forcings, free_initial) + if s in states + ] equil_zero = list(dict.fromkeys(equil_zero)) held_state_params = {} if equilibrate and not reduce_cq and totals: @@ -1630,13 +1958,21 @@ def from_py(e): if x in set(forcings): raise InputError(f"`free_initial` names {x}, an input, which rests at zero") if x in set(bases): - raise InputError(f"`free_initial` names {x}, the base of a free exponent, whose resting value " - "the steady state solves; give another state of the total") + raise InputError( + f"`free_initial` names {x}, the base of a free exponent, whose resting value " + "the steady state solves; give another state of the total" + ) avoid_fv = list(dict.fromkeys(equil_zero + forcings + bases)) # an observed species holds the free resting value first seen = set(get_symbols(g_char())) - dec = pivot_decomposition(totals, states, parameters, avoid=avoid_fv, prefer=free_initial, - extra={x: int(x not in seen) for x in states}) + dec = pivot_decomposition( + totals, + states, + parameters, + avoid=avoid_fv, + prefer=free_initial, + extra={x: int(x not in seen) for x in states}, + ) piv = [p for p in dec["basis"] if p in states and p not in set(equil_zero) | set(forcings)] held_state_params = {p: p for p in piv} settings["free_initial"] = list(piv) @@ -1650,13 +1986,25 @@ def from_py(e): for t in cq_moved: if t not in set(const_states): held_state_params.setdefault(t, t) - res = resolve_conditions(conditions, events, initial, symbols, states, const_states, - forcings, equilibrate=equilibrate, cond_subs=cond_subs, - cond_initial=cond_initial, n_cond_obs=n_cond_obs, renamed=list(jets)) + res = resolve_conditions( + conditions, + events, + initial, + symbols, + states, + const_states, + forcings, + equilibrate=equilibrate, + cond_subs=cond_subs, + cond_initial=cond_initial, + n_cond_obs=n_cond_obs, + renamed=list(jets), + ) seg_obs = [g_lines(c - 1) for c in res["chain_of"]] if g_per_cond else None cond_zero = [] if equilibrate and method == "observability": from ..par import process_map + subs_z = [] for i in range(len(res["subs"])): sub = dict(res["subs"][i]) @@ -1676,20 +2024,34 @@ def zero_one(i): net = dict(reactions, rates=list(rates)) z = _rest_zeros(rhs, net, forcings) return [s for s in z if s in states and s not in equil_zero] + nzc = min(max(1, int(cores)), len(uk)) zs = process_map(zero_one, uk, nzc) cond_zero = [zs[uk.index(keys.index(k))] for k in keys] model_syms = get_symbols(list(fdyn.values()) + g_char()) - pinned_ic = list(dict.fromkeys((states if equilibrate else ic_names) + - event_pinned_states(events, conditions) + - grid_pinned_states(conditions, [s for s in states if s not in jets]) + - [s for s in forcings + fixed + const_states if s in states])) + pinned_ic = list( + dict.fromkeys( + (states if equilibrate else ic_names) + + event_pinned_states(events, conditions) + + grid_pinned_states(conditions, [s for s in states if s not in jets]) + + [s for s in forcings + fixed + const_states if s in states] + ) + ) grid_pars = [] if conditions is not None: - grid_pars = [c for c in conditions.colnames() if c not in set(states) - and conditions.is_numeric(c) and c in set(model_syms)] - pinned_par = list(dict.fromkeys(list(trafo_subs) + [k for cs in (cond_subs or []) for k in cs] + - [s for s in fixed if s not in set(states)] + grid_pars)) + grid_pars = [ + c + for c in conditions.colnames() + if c not in set(states) and conditions.is_numeric(c) and c in set(model_syms) + ] + pinned_par = list( + dict.fromkeys( + list(trafo_subs) + + [k for cs in (cond_subs or []) for k in cs] + + [s for s in fixed if s not in set(states)] + + grid_pars + ) + ) codim_spec = len(pinned_ic) + len([p for p in pinned_par if p]) if sym_engine == "symbolic" and method == "observability": if equilibrate: @@ -1697,20 +2059,36 @@ def zero_one(i): if res["n_gaps"] > 0: raise ValueError('engine="symbolic" handles single-segment conditions only.') sr = observability_sympy_multi( - model=eqn_lines(fdyn), observation=g_lines(), condition_subs=res["subs"], - condition_ic0=res["ic0"], condition_obs=seg_obs, condition_rest_subs=res["rest_subs"], - fixed=fixed or None, parameters=parameters or None) + model=eqn_lines(fdyn), + observation=g_lines(), + condition_subs=res["subs"], + condition_ic0=res["ic0"], + condition_obs=seg_obs, + condition_rest_subs=res["rest_subs"], + fixed=fixed or None, + parameters=parameters or None, + ) if not sr.get("ok"): - raise ValueError('engine="symbolic": ' + - str(sr.get("why") or "could not build the symbolic system.")) - sr = dict(sr, method="observability", engine="symbolic", - lie_order_used=int(sr["lie_order"]), conditions=int(res["n_conditions"]), - segments=int(res["n_conditions"]), gap_order_used=0) + raise ValueError('engine="symbolic": ' + str(sr.get("why") or "could not build the symbolic system.")) + sr = dict( + sr, + method="observability", + engine="symbolic", + lie_order_used=int(sr["lie_order"]), + conditions=int(res["n_conditions"]), + segments=int(res["n_conditions"]), + gap_order_used=0, + ) from .observability.proof import prove_symbolic + prove_symbolic(sr, sr.pop("systems")) dirs = sr["non_identifiable"] - if sr.get("rank_proven") is None and dirs and all(d.get("exact") for d in dirs) and \ - len(dirs) == sr["dim"] - sr["rank"]: + if ( + sr.get("rank_proven") is None + and dirs + and all(d.get("exact") for d in dirs) + and len(dirs) == sr["dim"] - sr["rank"] + ): sr["rank_proven"], sr["rank_proof"] = len(dirs), "proven symmetries" sr["non_identifiable"] = relabel_directions(sr["non_identifiable"]) return deliver(sr, method) @@ -1724,21 +2102,33 @@ def zero_one(i): multi = {"ok": False, "nonrational": [off]} else: multi = compile_observability_tape_multi( - model=eqn_lines(fdyn), observation=g_lines(), condition_subs=res["subs"], - condition_ic0=res["ic0"], condition_obs=seg_obs, condition_rest_subs=res["rest_subs"], - fixed=fixed or None, parameters=parameters or None, equilibrate=equilibrate, - seg_equilibrate=list(res["seg_equil"]), forcings=forcings or None, - condition_events=res["seg_events"], condition_t0_events=res["events0"], + model=eqn_lines(fdyn), + observation=g_lines(), + condition_subs=res["subs"], + condition_ic0=res["ic0"], + condition_obs=seg_obs, + condition_rest_subs=res["rest_subs"], + fixed=fixed or None, + parameters=parameters or None, + equilibrate=equilibrate, + seg_equilibrate=list(res["seg_equil"]), + forcings=forcings or None, + condition_events=res["seg_events"], + condition_t0_events=res["events0"], condition_times=res["times"] if res["n_gaps"] > 0 else None, - keep_coords=chart_coords or None, joint_steady_state=equilibrate, + keep_coords=chart_coords or None, + joint_steady_state=equilibrate, joint_fixed_states=equil_zero if equilibrate and equil_zero else None, held_state_params=held_state_params if equilibrate and held_state_params else None, - const_states=const_states, positive=positive, - condition_chain=res["chain_of"] if res["n_gaps"] > 0 else None) + const_states=const_states, + positive=positive, + condition_chain=res["chain_of"] if res["n_gaps"] > 0 else None, + ) if multi.get("ok") and any(_OP_SPOW in list(t["op"]) for t in multi["tapes"]): session.current().notes["limits"].append( "a free power of a state that starts at 0 is expanded in t and (c t^k)^n; the stopping rule " - "of the Lie order does not apply there, so the order is not proven sufficient") + "of the Lie order does not apply there, so the order is not proven sufficient" + ) if multi.get("ok") and jets: # the k-th Lie derivative of an observable holds the input and the input derivatives up to order k # a jet state under a log chart is a nuisance coordinate in the log coordinate of the chart @@ -1746,11 +2136,18 @@ def zero_one(i): def nm(x): return logs.get(jet_start.get(x, x), jet_start.get(x, x)) - _mark_nuisance(multi, {"states": [nm(x) for names in jets.values() for x in names], - "kept": [nm(w) for w in jets], - "tops": [nm(names[-1]) for names in jets.values()], - "exact_order": int(jet_order) - 1, "prolonged": not jet_start, - "jet_states": list(jet_start)}) + + _mark_nuisance( + multi, + { + "states": [nm(x) for names in jets.values() for x in names], + "kept": [nm(w) for w in jets], + "tops": [nm(names[-1]) for names in jets.values()], + "exact_order": int(jet_order) - 1, + "prolonged": not jet_start, + "jet_states": list(jet_start), + }, + ) elif multi.get("ok") and nuisance: _mark_nuisance(multi, nuisance) if multi.get("ok") and known_order: @@ -1759,9 +2156,18 @@ def nm(x): multi["nuisance_order"] = top if multi.get("nuisance_order") is None else min(int(multi["nuisance_order"]), top) multi["known_jet_states"] = list(known_order.get("states") or []) if method == "scaling": - r = _resolved_scalings(fdyn, gset, g_per_cond, res, [u for u in forcings if u not in jet_start], fixed, jets, - multi if multi.get("ok") else None, held_state_params if equilibrate else None, - forcings if equilibrate else None) + r = _resolved_scalings( + fdyn, + gset, + g_per_cond, + res, + [u for u in forcings if u not in jet_start], + fixed, + jets, + multi if multi.get("ok") else None, + held_state_params if equilibrate else None, + forcings if equilibrate else None, + ) if jets: r = dict(r, non_identifiable=_scalings_without_jets(r.get("non_identifiable") or [], jets)) return deliver(r, "scaling") @@ -1774,9 +2180,10 @@ def nm(x): "hyperbolic and inverse trigonometric and hyperbolic functions, free power " "exponents x^n, and log() and fractional powers of arguments that are positive " "for the coordinates declared `positive`; observables may be a*log(h) + offset " - "with a number a; anything else is not rational.\n " + - "\n ".join(str(x) for x in (multi.get("nonrational") or [])) + - "\nUse the symbolic engine for other functions.") + "with a number a; anything else is not rational.\n " + + "\n ".join(str(x) for x in (multi.get("nonrational") or [])) + + "\nUse the symbolic engine for other functions." + ) if equilibrate and multi.get("equilibrate"): _rest_check(multi, equil_zero, cond_zero, forcings, positive) @@ -1784,10 +2191,21 @@ def nm(x): def oam(): return observability_analytic_multi( - multi, closed_form=reconstruct, cores=cores, equil_zero_states=equil_zero, - cond_zero_states=cond_zero, t0events=res["events0"], n_conditions=res["n_conditions"], - chain_of=res["chain_of"], n_gaps=res["n_gaps"], implicit_steady_state=equilibrate, - control=control, verify=verify, codim_spec=codim_spec) + multi, + closed_form=reconstruct, + cores=cores, + equil_zero_states=equil_zero, + cond_zero_states=cond_zero, + t0events=res["events0"], + n_conditions=res["n_conditions"], + chain_of=res["chain_of"], + n_gaps=res["n_gaps"], + implicit_steady_state=equilibrate, + control=control, + verify=verify, + codim_spec=codim_spec, + ) + out = oam() if isinstance(out, dict) and out.get("rerun_blocks"): with state.options(stacked_first=False): @@ -1796,17 +2214,27 @@ def oam(): out = log_param_back(out, multi.get("log_params")) if out is None: if equilibrate: - hint = "declare each conserved quantity in `totals`" if reduce_cq else \ - "reduce conserved moieties (`reduce_cq`)" - raise ValueError("the implicit steady-state path could not be " - "evaluated (e.g. a singular resting Jacobian from an unreduced " - f"conserved moiety). {hint[0].upper()}{hint[1:]} or " - "supply an explicit steady state through `trafo`.") - raise ValueError("the observability kernel could not be evaluated at " - "any generic point (a denominator vanishes at every point tried).") + hint = ( + "declare each conserved quantity in `totals`" + if reduce_cq + else "reduce conserved moieties (`reduce_cq`)" + ) + raise ValueError( + "the implicit steady-state path could not be " + "evaluated (e.g. a singular resting Jacobian from an unreduced " + f"conserved moiety). {hint[0].upper()}{hint[1:]} or " + "supply an explicit steady state through `trafo`." + ) + raise ValueError( + "the observability kernel could not be evaluated at " + "any generic point (a denominator vanishes at every point tried)." + ) out["non_identifiable"] = relabel_directions(out["non_identifiable"]) if verify and isinstance(out.get("verification"), dict) and out["verification"].get("ok") is False: - warnings.warn("`verify`: the rank still grows past the Lie or gap order used; " - "the directions may be over-reported; " - f"inspect info['verification'] ({out['verification'].get('reason')}).", stacklevel=2) + warnings.warn( + "`verify`: the rank still grows past the Lie or gap order used; " + "the directions may be over-reported; " + f"inspect info['verification'] ({out['verification'].get('reason')}).", + stacklevel=2, + ) return deliver(out, method) diff --git a/src/symident/detection/cq.py b/src/symident/detection/cq.py index 0acbcc0..616b14b 100644 --- a/src/symident/detection/cq.py +++ b/src/symident/detection/cq.py @@ -83,6 +83,7 @@ def augment(r, seen): match[j] = r return True return False + for r in rows: augment(r, set()) return {r: species[j] for j, r in match.items()} @@ -95,11 +96,15 @@ def _free_initial_error(prefer, C, rows, species, totals): shared = [names[i] for i in rows if sum(abs(C[i, j]) > 1e-12 for j in cols) >= 2] within = [names[i] for i in rows if all(abs(C[k, j]) <= 1e-12 for k in rows if k != i for j in cols)] if len(shared) == 1 and shared[0] in within: - return InputError(f"`free_initial` names {', '.join(prefer)}, which the single total {shared[0]} = " - f"{totals[shared[0]]} holds; give one state per total") - return InputError(f"`free_initial` names {', '.join(prefer)}, whose resting values the totals " - f"{', '.join(names[i] for i in rows)} do not leave independent; give one state per total, " - "with the coefficients of the chosen states linearly independent") + return InputError( + f"`free_initial` names {', '.join(prefer)}, which the single total {shared[0]} = " + f"{totals[shared[0]]} holds; give one state per total" + ) + return InputError( + f"`free_initial` names {', '.join(prefer)}, whose resting values the totals " + f"{', '.join(names[i] for i in rows)} do not leave independent; give one state per total, " + "with the coefficients of the chosen states linearly independent" + ) def pivot_decomposition(totals, states, parameters=(), avoid=(), prefer=(), extra=None): @@ -120,8 +125,9 @@ def pivot_decomposition(totals, states, parameters=(), avoid=(), prefer=(), extr keep.append(i) rows = keep avoid, parameters = set(avoid), set(parameters) - w = _pivot_weight(C, _coef_matrix(totals, states, shift=0.377)[0], species, rows, avoid | parameters, - dict(extra or {})) + w = _pivot_weight( + C, _coef_matrix(totals, states, shift=0.377)[0], species, rows, avoid | parameters, dict(extra or {}) + ) pos = {s: k for k, s in enumerate(states)} order = sorted(species, key=lambda s: (w[s], pos.get(s, len(pos)))) prefer = [str(s) for s in prefer or []] @@ -129,12 +135,12 @@ def pivot_decomposition(totals, states, parameters=(), avoid=(), prefer=(), extr dup = [s for k, s in enumerate(prefer) if s in prefer[:k]] if dup: raise InputError(f"`free_initial` names {dup[0]} twice; give one state per total") - bad = [s for s in prefer if s not in species or - not any(abs(C[i, species.index(s)]) > 1e-12 for i in rows)] + bad = [s for s in prefer if s not in species or not any(abs(C[i, species.index(s)]) > 1e-12 for i in rows)] if bad: held = ", ".join(f"{names[i]} = {totals[names[i]]}" for i in rows) - raise InputError(f"`free_initial` names {bad[0]}, which is in no conserved total" - + (f" ({held})" if rows else "")) + raise InputError( + f"`free_initial` names {bad[0]}, which is in no conserved total" + (f" ({held})" if rows else "") + ) if _rank(C[np.ix_(rows, [species.index(s) for s in prefer])]) < len(prefer): raise _free_initial_error(prefer, C, rows, species, totals) basis = _greedy_basis(C, rows, species, order, prefer) @@ -142,8 +148,8 @@ def pivot_decomposition(totals, states, parameters=(), avoid=(), prefer=(), extr def exchanges(b): """(position, species) pairs whose exchange keeps the columns `b` a basis.""" X = np.linalg.solve(C[np.ix_(rows, [species.index(x) for x in b])], C[rows]) - return [(k, s) for s in order if s not in b for k in range(len(b)) - if abs(X[k, species.index(s)]) > 1e-9] + return [(k, s) for s in order if s not in b for k in range(len(b)) if abs(X[k, species.index(s)]) > 1e-9] + ties, more = [], [] if not prefer and rows: # bases one exchange apart, breadth first from the greedy one: those of equal weight tie with it @@ -151,7 +157,7 @@ def exchanges(b): while queue and len(ties) < PIVOT_CHOICES - 1: b = queue.pop(0) for k, s in exchanges(b): - alt = sorted(b[:k] + [s] + b[k + 1:], key=lambda x: pos.get(x, len(pos))) + alt = sorted(b[:k] + [s] + b[k + 1 :], key=lambda x: pos.get(x, len(pos))) if frozenset(alt) in seen: continue seen.add(frozenset(alt)) @@ -162,12 +168,20 @@ def exchanges(b): more.append(alt) more.sort(key=lambda b: sum(w[x] for x in b)) basis = sorted(basis, key=lambda x: pos.get(x, len(pos))) - ties = ties[:PIVOT_CHOICES - 1] - more = more[:max(0, PIVOT_CHOICES - 1 - len(ties))] + ties = ties[: PIVOT_CHOICES - 1] + more = more[: max(0, PIVOT_CHOICES - 1 - len(ties))] match = _assign(C, rows, species, basis) pivots = [match.get(i) for i in range(len(names))] - return {"C": C, "species": species, "pivots": pivots, "sets": sets, "rows": rows, "basis": basis, - "ties": ties, "valid": more} + return { + "C": C, + "species": species, + "pivots": pivots, + "sets": sets, + "rows": rows, + "basis": basis, + "ties": ties, + "valid": more, + } def substitute_cq(totals, f, states, parameters, avoid=(), prefer=(), extra=None): @@ -191,8 +205,12 @@ def substitute_cq(totals, f, states, parameters, avoid=(), prefer=(), extra=None sympy_fail(exc) sol = None if sol is None or any(x.free_symbols & set(unknowns) for x in sol): - raise InputError("the conserved totals " + ", ".join(names[i] for i in rows) + - " cannot be solved for the species " + ", ".join(elim)) + raise InputError( + "the conserved totals " + + ", ".join(names[i] for i in rows) + + " cannot be solved for the species " + + ", ".join(elim) + ) recon = {e: "(" + str(spy.cancel(x)).replace("**", "^") + ")" for e, x in zip(elim, sol)} cq_info = [] for i in rows: @@ -221,6 +239,7 @@ def cq_events(events, totals, cq_info): through the totals. """ from .conditions import compose_event + recon = {ci["elim_state"]: ci["recon_expr"] for ci in cq_info} names = [ci["total_name"] for ci in cq_info] held = {t: set(get_symbols([str(totals[t])])) for t in names} @@ -228,6 +247,7 @@ def cq_events(events, totals, cq_info): def through(text): return replace_symbols(keys, vals, str(text)) if keys else str(text) + out, changed, groups = [], [], {} for e in events: key = (str(e["time"]), tuple(e["cond"]) if e.get("cond") is not None else None, e.get("root")) @@ -255,8 +275,10 @@ def through(text): v = " + ".join(parts) if v == 0: continue - out.append({k: e0[k] for k in e0 if k not in ("var", "value", "method", "time")} | - {"var": t, "time": through(e0["time"]), "value": str(v).replace("**", "^"), "method": "add"}) + out.append( + {k: e0[k] for k in e0 if k not in ("var", "value", "method", "time")} + | {"var": t, "time": through(e0["time"]), "value": str(v).replace("**", "^"), "method": "add"} + ) changed.append(t) return out, list(dict.fromkeys(changed)) @@ -277,8 +299,10 @@ def check_conserved(totals, f): sympy_fail(exc) if bad is not None: name, e, d = bad - raise InputError(f"the total {name} = {e} is not conserved: the time derivative under " - f"the right-hand sides is {str(d).replace('**', '^')}, not zero") + raise InputError( + f"the total {name} = {e} is not conserved: the time derivative under " + f"the right-hand sides is {str(d).replace('**', '^')}, not zero" + ) def _primitive(v): @@ -325,6 +349,7 @@ def _extreme_rays(basis, n): def dot(a, y): return sum(x * z for x, z in zip(a, y)) + for a in A: if a in start: continue @@ -372,6 +397,7 @@ def root(i): block[i] = block[block[i]] i = block[i] return i + for i in range(k): for j in range(i): if supp[i] & supp[j]: @@ -406,6 +432,7 @@ def independent(r): return False ech.append((pc, [x / v[pc] for x in v])) return True + for r in rays: if len(chosen) == k: break @@ -434,6 +461,7 @@ def conserved_totals(smatrix, species): """Conserved quantities of a stoichiometry (rows reactions, columns species) as totals.""" from sympy.polys.domains import QQ from sympy.polys.matrices import DomainMatrix + n = len(species) rows = {} for i, r in enumerate(smatrix): @@ -476,14 +504,22 @@ def exact_totals(totals, odes): def conserved_totals_of_odes(odes): """The linear conservation laws of the right-hand sides `odes` (state to expression) as totals.""" from ..sym.exact import _conserved + try: laws = _conserved([f"{k} = {v}" for k, v in odes.items()], {spy.Symbol(str(k)) for k in odes}) except SYMPY_FAILS as exc: sympy_fail(exc) return {} states = list(odes) - vecs = [[Fraction(int(spy.Rational(law.get(spy.Symbol(str(k)), 0)).p), - int(spy.Rational(law.get(spy.Symbol(str(k)), 0)).q)) for k in states] for law in laws] + vecs = [ + [ + Fraction( + int(spy.Rational(law.get(spy.Symbol(str(k)), 0)).p), int(spy.Rational(law.get(spy.Symbol(str(k)), 0)).q) + ) + for k in states + ] + for law in laws + ] out = {} for v in canonical_laws(vecs, len(states)): total = _total_text(states, v) @@ -525,8 +561,10 @@ def _exact_lp(M, c): zero, one = Fraction(0), Fraction(1) # columns: w, then the slacks of M w <= 0, then those of w <= 1, then the right-hand side T = [list(row) + [one if k == i else zero for k in range(m)] + [zero] * (n + 1) for i, row in enumerate(M)] - T += [[one if k == j else zero for k in range(n)] + [zero] * m + [one if k == j else zero for k in range(n)] + [one] - for j in range(n)] + T += [ + [one if k == j else zero for k in range(n)] + [zero] * m + [one if k == j else zero for k in range(n)] + [one] + for j in range(n) + ] basis = list(range(n, 2 * n + m)) z = list(c) + [zero] * (m + n + 1) while True: @@ -645,8 +683,10 @@ def equil_zero_branches(smatrix, species, rates, forcings): if not br: return list(dict.fromkeys(taken + zero)), notes r = br[0] - notes.append(f"the reaction of {' + '.join(r)} drains them: at rest one of them is zero " - f"({' or '.join(f'{x} = 0' for x in r)}); the result holds for {r[0]} = 0") + notes.append( + f"the reaction of {' + '.join(r)} drains them: at rest one of them is zero " + f"({' or '.join(f'{x} = 0' for x in r)}); the result holds for {r[0]} = 0" + ) taken.append(r[0]) @@ -662,6 +702,7 @@ def reduced_by_totals(odes, observables, events, totals, eliminated): def through(o): return None if o is None else {str(k): replace_symbols(keys, vals, str(v)) for k, v in dict(o).items()} + f = {k: v for k, v in cq["f"].items() if k not in recon} obs = [through(o) for o in observables] if isinstance(observables, (list, tuple)) else through(observables) events, moved = cq_events(events, totals, cq["cq_info"]) if events else ([], []) diff --git a/src/symident/detection/discrete.py b/src/symident/detection/discrete.py index 333d66c..cd245a4 100644 --- a/src/symident/detection/discrete.py +++ b/src/symident/detection/discrete.py @@ -62,16 +62,18 @@ def _fiber_terms(): # why a call of msolve gave no count, by kind, since the last reset -_FAILURES = set() +_FAILURES: set = set() # the work caps that stopped a proof of a map since the last reset, as reasons -_CAPPED = set() -_FAILED = {"memory": "msolve ran out of memory ({gib:g} GiB of address space per call)", - "size": "a system past the caps of msolve ({unknowns} unknowns, {terms:,} terms)", - "work": "msolve reached the cap msolve_entries of {entries:,} nonzero entries of the matrices of F4", - "dimension": "the equations of the fiber have a component of positive dimension up to order {order}, which " - "the denominators and coordinates do not exclude", - "quotient": "the quotient of a block has more than {cap} standard monomials", - "error": "msolve stopped with an error"} +_CAPPED: set = set() +_FAILED = { + "memory": "msolve ran out of memory ({gib:g} GiB of address space per call)", + "size": "a system past the caps of msolve ({unknowns} unknowns, {terms:,} terms)", + "work": "msolve reached the cap msolve_entries of {entries:,} nonzero entries of the matrices of F4", + "dimension": "the equations of the fiber have a component of positive dimension up to order {order}, which " + "the denominators and coordinates do not exclude", + "quotient": "the quotient of a block has more than {cap} standard monomials", + "error": "msolve stopped with an error", +} _NO_FINITE_COUNT = "msolve found no finite count: " + _FAILED["dimension"] @@ -92,9 +94,18 @@ def no_count_reason(order): return _NO_FINITE_COUNT.format(order=order) gib = work.MSOLVE_MEMORY / (1 << 30) cap = work.cap - why = [_FAILED[k].format(order=order, gib=gib, cap=5000, unknowns=cap("msolve_unknowns"), - terms=cap("msolve_terms"), entries=int(cap("msolve_entries"))) - for k in ("memory", "work", "size", "dimension", "quotient", "error") if k in _FAILURES] + why = [ + _FAILED[k].format( + order=order, + gib=gib, + cap=5000, + unknowns=cap("msolve_unknowns"), + terms=cap("msolve_terms"), + entries=int(cap("msolve_entries")), + ) + for k in ("memory", "work", "size", "dimension", "quotient", "error") + if k in _FAILURES + ] return f"msolve found no finite count up to order {order}: " + "; ".join(why) @@ -105,6 +116,7 @@ class CapError(Exception): # ---- the equations of the fiber ------------------------------------------------------------ + class FiberTooLargeError(Exception): """The equations of the fiber have more than _FIBER_TERMS terms, or more than _FIBER_UNKNOWNS unknowns (the arguments n, "unknowns"): no count is taken.""" @@ -112,6 +124,7 @@ class FiberTooLargeError(Exception): class _Dual: """A value and the gradient over the coordinates, modulo p.""" + __slots__ = ("v", "d", "p") def __init__(self, v, d, p): @@ -165,7 +178,7 @@ def __pow__(self, e): def __eq__(self, x): return self.v == self._of(x).v - __hash__ = None + __hash__ = None # type: ignore[assignment] def _ser_mul(a, b, n, zero, limit=None): @@ -199,7 +212,7 @@ def _mul_add(acc, x, y, room): else: items, step = list(x.items()), max(1, room // max(1, len(y))) for s in range(0, len(items), step): - acc = acc + x.ring.dtype(items[s:s + step]) * y + acc = acc + x.ring.dtype(items[s : s + step]) * y if _terms(acc) > room: raise FiberTooLargeError(room) if _terms(acc) > room: @@ -228,6 +241,7 @@ def power(i, e): if (i, e) not in cache: cache[(i, e)] = check(xs[i] if e == 1 else _ser_mul(power(i, e - 1), xs[i], n, zero, limit)) return cache[(i, e)] + ns = len(xs) for m, c in P.items(): coef = one * c @@ -245,6 +259,7 @@ def power(i, e): class _Eps: """A power series in the formal gap variable eps, truncated after a fixed degree, over the coefficients of any ring: the gaps between events are eps times the given gaps, as in the local analysis.""" + __slots__ = ("c",) def __init__(self, c): @@ -271,8 +286,9 @@ def __rsub__(self, x): def __mul__(self, x): if not isinstance(x, _Eps): return _Eps([a * x for a in self.c]) - return _Eps([sum((self.c[i] * x.c[k - i] for i in range(1, k + 1)), self.c[0] * x.c[k]) - for k in range(len(self.c))]) + return _Eps( + [sum((self.c[i] * x.c[k - i] for i in range(1, k + 1)), self.c[0] * x.c[k]) for k in range(len(self.c))] + ) __rmul__ = __mul__ @@ -376,8 +392,12 @@ def __init__(self, parts, coords, positive=True): segs = [seg for part in parts for seg in part["segments"]] texts = [] for seg in segs: - texts += list(seg["f"].values()) + list(seg["g"].values()) + \ - [v for v in (seg.get("ic") or {}).values() if v is not None] + [seg.get("on") or "0"] + texts += ( + list(seg["f"].values()) + + list(seg["g"].values()) + + [v for v in (seg.get("ic") or {}).values() if v is not None] + + [seg.get("on") or "0"] + ) texts += [e["value"] for e in seg.get("events") or []] + [seg.get("t") or "0"] allsyms = set().union(*[model_sympify(str(e)).free_symbols for e in texts]) states = {spy.Symbol(x) for seg in segs for x in seg["f"]} @@ -390,8 +410,11 @@ def __init__(self, parts, coords, positive=True): self.parts = [self._part(part, rng) for part in parts] self.labels = [lab for part in self.parts for seg in part["segs"] for lab in seg["labels"]] # the rows of the copies with a free start: their values at sigma(theta) need the image of the start - self.free_rows = {k for k, (part, seg, _) in enumerate((p, s_, y) for p in self.parts for s_ in p["segs"] - for y in s_["labels"]) if part["segs"][0].get("free")} + self.free_rows = { + k + for k, (part, seg, _) in enumerate((p, s_, y) for p in self.parts for s_ in p["segs"] for y in s_["labels"]) + if part["segs"][0].get("free") + } self.has_events = any(len(part["segs"]) > 1 for part in self.parts) # the jets of unknown inputs: free starts that are no coordinates, with values drawn or set (uinputs.py) self.inputs = [(pi, i) for pi, part in enumerate(self.parts) for i in part["segs"][0]["inputs"]] @@ -423,8 +446,10 @@ def _start_power(self, pi): sp, seg = part["spow"], part["segs"][0] v, vy = startpow.valuations(seg["F"], seg["G"], len(part["st"]), sp["N"], part["known"]) if v[sp["base"]] is not None and v[sp["base"]] < sp["k"]: - raise ValueError(f"discrete(): {sp['state']}^{sp['alpha']} enters the dynamics of {sp['state']} below " - f"the order {sp['k']} of {sp['state']}") + raise ValueError( + f"discrete(): {sp['state']}^{sp['alpha']} enters the dynamics of {sp['state']} below " + f"the order {sp['k']} of {sp['state']}" + ) sp["v"], sp["vy"] = v, vy a = self.cs[sp["alpha_index"]] if not is_positive(a, self.positive): @@ -440,12 +465,14 @@ def _part(self, part, rng): def frac(e): num, den = spy.fraction(spy.cancel(spy.together(model_sympify(str(e)).xreplace(self.known)))) return _dict(num, gens), _dict(den, gens) + def poly(text): e = spy.cancel(model_sympify(str(text)).xreplace(self.known)) num, den = spy.fraction(e) if not den.is_number or (num.free_symbols - set(cs)): raise ValueError(f"discrete() needs event times polynomial in the coordinates, not {e}") return e + t0 = poly(part["segments"][0].get("t", "0")) # each segment is expanded at the segment start, or, where the start holds coordinates, at the start of the # condition: there the series of a later start tells the time of the event @@ -454,8 +481,11 @@ def poly(text): for j, seg in enumerate(part["segments"]): if list(seg["f"]) != [str(x) for x in st]: raise ValueError("discrete(): the segments of a condition have other states") - s = {"F": [frac(seg["f"][str(x)]) for x in st], "G": [frac(v) for v in seg["g"].values()], - "labels": [f"{seg.get('label', '')}{y}" for y in seg["g"]]} + s = { + "F": [frac(seg["f"][str(x)]) for x in st], + "G": [frac(v) for v in seg["g"].values()], + "labels": [f"{seg.get('label', '')}{y}" for y in seg["g"]], + } if j == 0: # the start of each state: a coordinate, a number, or a rational function of the coordinates; without # initial values (a copy switched into a regime) every state starts free, a number at the point @@ -485,25 +515,40 @@ def poly(text): if free and seg.get("on") is not None: N, D = frac(seg["on"]) ns = len(st) - lin = [i for i in range(ns) if max(m[i] for m in N) == 1 and - all(not any(m[:i] + m[i + 1:ns]) or m[i] == 0 for m in N if m[i] == 1)] + lin = [ + i + for i in range(ns) + if max(m[i] for m in N) == 1 + and all(not any(m[:i] + m[i + 1 : ns]) or m[i] == 0 for m in N if m[i] == 1) + ] lin = lin or [i for i in range(ns) if max(m[i] for m in N) == 1] if not lin: raise ValueError(f"discrete() needs the switching surface {seg['on']} = 0 linear in a state") i = lin[0] def drop(m, i=i): - return m[:i] + (0,) + m[i + 1:] - s["on"] = (i, {drop(m): c for m, c in N.items() if m[i] == 1}, - {m: c for m, c in N.items() if m[i] == 0}, N, D) + return m[:i] + (0,) + m[i + 1 :] + + s["on"] = ( + i, + {drop(m): c for m, c in N.items() if m[i] == 1}, + {m: c for m, c in N.items() if m[i] == 0}, + N, + D, + ) # a state with a numeric start whose right-hand side reads only such states (the jets of a known # input, the clock) has a known series: it enters as numbers, not as unknowns ns, known = len(st), set() while True: - more = {i for i in range(ns) if i not in known and s["x0"][i][0] is not None and - s["x0"][i][0].is_number and - all(not e or j_ in known for P in s["F"][i] for m in P for j_, e in enumerate(m[:ns])) and - all(not any(m[ns:]) for P in s["F"][i] for m in P)} + more = { + i + for i in range(ns) + if i not in known + and s["x0"][i][0] is not None + and s["x0"][i][0].is_number + and all(not e or j_ in known for P in s["F"][i] for m in P for j_, e in enumerate(m[:ns])) + and all(not any(m[ns:]) for P in s["F"][i] for m in P) + } if not more: break known |= more @@ -579,8 +624,11 @@ def _known_series(self, pi, order): def start(v): v = spy.Rational(v) return Fraction(int(v.p), int(v.q)) - xs = [[start(seg["x0"][i][0])] + [zero] * order if i in known else [zero] * (order + 1) - for i in range(len(part["st"]))] + + xs = [ + [start(seg["x0"][i][0])] + [zero] * order if i in known else [zero] * (order + 1) + for i in range(len(part["st"])) + ] nop = [zero] * len(self.params) for k in range(order): for i in sorted(known): @@ -615,8 +663,10 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): continue if i in seg["inputs"]: v = (self.input_values or {}).get((pi, i), seg["inputs"][i]) - xs.append([one * (Fraction(int(v.p), int(v.q)) if isinstance(v, spy.Rational) else v)] - + [zero] * order) + xs.append( + [one * (Fraction(int(v.p), int(v.q)) if isinstance(v, spy.Rational) else v)] + + [zero] * order + ) continue d = _eval(den, cvals, zero) if d == 0: @@ -635,8 +685,9 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): # the layers S^m of the free power of a state at 0, one per k orders o, z = _Eps([one] + [zero] * (order // sp["k"])), _Eps([zero] * (order // sp["k"] + 1)) xs = [[o * c for c in x] for x in xs] - if not startpow.layered_flow(seg["F"], xs, params, order, o, z, kser, sp, - val[self.cs[sp["alpha_index"]]]): + if not startpow.layered_flow( + seg["F"], xs, params, order, o, z, kser, sp, val[self.cs[sp["alpha_index"]]] + ): return None else: sp = None @@ -660,8 +711,11 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): xs = [_shift(x, -off, order, gap, one, zero) for x in xs] else: xs = [[w] + [z] * order for w in w0] - if sp is None and (j == 0 or seg["off"] is None) and not _flow(seg["F"], xs, params, order, o, z, - kser, meter, weight): + if ( + sp is None + and (j == 0 or seg["off"] is None) + and not _flow(seg["F"], xs, params, order, o, z, kser, meter, weight) + ): return None if pi == 0 and j == 0: # the series of the states at the start of the first condition, for the exact count @@ -708,7 +762,7 @@ def jacobian(self, order, p, gap=0): key = (p, gap) have = self._jac.get(key) if have is not None and have[0] >= order: - return None if have[1] is None else [y[:order + 1] for y in have[1]] + return None if have[1] is None else [y[: order + 1] for y in have[1]] m = len(self.cs) cv = self._jac_point(p) one, zero = _Dual(1, [0] * m, p), _Dual(0, [0] * m, p) @@ -772,8 +826,12 @@ def _rank_rows(self, cap, p, skip, pins): # the pins of least degree first least = sorted(range(len(pv)), key=lambda i: _pin_degree(self.pins[i])) rows += [(("pin", i), list(pv[i].d)) for i in least] - rows += [((j, k), list(ys[j][k][0].d) if isinstance(ys[j][k], list) else list(ys[j][k].d)) - for k in range(cap + 1) for j in range(len(ys)) if k < len(ys[j])] + rows += [ + ((j, k), list(ys[j][k][0].d) if isinstance(ys[j][k], list) else list(ys[j][k].d)) + for k in range(cap + 1) + for j in range(len(ys)) + if k < len(ys[j]) + ] for key, row in rows: for b, c in zip(basis, piv): if row[c]: @@ -817,6 +875,7 @@ def adds(row): basis.append([x * inv % p for x in row]) piv.append(c) return True + for row in seed: adds(row) orders = [0] * len(ys) @@ -856,8 +915,9 @@ def _jet_names(self, orders, order, gap): if sp is not None: row0 = sum(len(seg["labels"]) for part_ in self.parts[:pi] for seg in part_["segs"]) seg = part["segs"][0] - sp["need"] = startpow.needs(seg["F"], seg["G"], len(part["st"]), sp, - orders[row0:row0 + len(seg["G"])], part["known"]) + sp["need"] = startpow.needs( + seg["F"], seg["G"], len(part["st"]), sp, orders[row0 : row0 + len(seg["G"])], part["known"] + ) jets.update(self._spow_jets(pi, order, kser)) continue for j, seg in enumerate(part["segs"]): @@ -891,6 +951,7 @@ def prolonged(self, orders, gap=0): zero_in = set() if self.inputs: from .uinputs import unread_jets + zero_in = unread_jets(self, orders) jets = {key: v for key, v in jets.items() if (key[0], key[2]) not in zero_in or key[3] > 0} if len(names) + len(jets) > _FIBER_UNKNOWNS: @@ -903,6 +964,7 @@ def prolonged(self, orders, gap=0): def in_ring(P): return R.from_dict({mm + pad: c for mm, c in P.items()}) if P else R.zero + eqs, outs = [], [] sat = [cof[str(c)] for c in self.cs] @@ -920,6 +982,7 @@ def add_sat(e): e = _lead(e) if not e.is_ground: sat.append(e) + row = 0 for pi, part in enumerate(self.parts): kser = self._known_series(pi, order) @@ -964,15 +1027,20 @@ def add_sat(e): pre = [_at_gap(x, in_ring(seg["dt"]), gap, R.one, R.zero) for x in xs] xs = [] for i in range(len(part["st"])): + def jet(k, i=i): return _Eps([g[jets[(pi, j, i, k, m)]] for m in range(gap + 1)]) + ws = [jet(k) for k in range(1, order + 1)] w0 = pre[i] if (pi, j, i, 0, 0) in jets: w0 = jet(0) # the state at the event: the series at the anchor where the start holds coordinates - at = _at_gap([w0] + ws, in_ring(seg["off"]), gap, R.one, R.zero) \ - if seg["off"] is not None else w0 + at = ( + _at_gap([w0] + ws, in_ring(seg["off"]), gap, R.one, R.zero) + if seg["off"] is not None + else w0 + ) if i in seg["event"]: N, D = seg["event"][i] nv, dv = _value(N, pre, params, o, z), _value(D, pre, params, o, z) @@ -992,6 +1060,7 @@ def jet(k, i=i): def layers(key): return _Eps([g[jets[key + (m,)]] if key + (m,) in jets else R.zero for m in range(L)]) + for i in range(len(xs)): if i == sp["N"]: xs[i] = [z] * (order + 1) @@ -1000,9 +1069,21 @@ def layers(key): else: xs[i] = [o * xs[i][0]] + [layers((pi, 0, i, k)) for k in range(1, order + 1)] Q = [o] + [layers(("q", pi, q)) for q in range(1, sp["need"][sp["N"]] - sp["k"] + 1)] - startpow.layered_equations(seg["F"], xs, params, sp["need"], o, z, kser, sp, - cof[str(self.cs[sp["alpha_index"]])], Q, add_eq, add_sat, - _fiber_terms()) + startpow.layered_equations( + seg["F"], + xs, + params, + sp["need"], + o, + z, + kser, + sp, + cof[str(self.cs[sp["alpha_index"]])], + Q, + add_eq, + add_sat, + _fiber_terms(), + ) for i, (N, D) in enumerate(seg["F"]): if (j == 0 and i in kser) or sp is not None: continue @@ -1017,8 +1098,12 @@ def layers(key): mser = _ser_poly(M, xs, params, n, o, z, _fiber_terms()) eser = _ser_poly(E, xs, params, n, o, z, _fiber_terms()) add_sat(eser[0]) - outs.append(([[_rdict(c) for c in _coeffs(e)] for e in eser], - [[_rdict(c) for c in _coeffs(m)] for m in mser])) + outs.append( + ( + [[_rdict(c) for c in _coeffs(e)] for e in eser], + [[_rdict(c) for c in _coeffs(m)] for m in mser], + ) + ) return list(jets.values()), [_rdict(e) for e in eqs if e], outs, [_rdict(f) for f in sat] @@ -1031,7 +1116,7 @@ def _dict(e, syms): return _rdict(_sparse_ring(tuple(syms)).from_expr(e)) -_RINGS = {} +_RINGS: dict = {} def _sparse_ring(syms): @@ -1076,16 +1161,22 @@ def __init__(self, series, orders, positive=True, gap=0, proj=None): jets, static, outs, sat = series.prolonged(self.orders, self.gap) except FiberTooLargeError as exc: # a series past the limit: the equations have more terms, and no count is taken - self.too_large, self.allnames, self.static, self.outs, self.sat = \ - _fiber_terms() + 1, list(self.names), [], [], [] + self.too_large, self.allnames, self.static, self.outs, self.sat = ( + _fiber_terms() + 1, + list(self.names), + [], + [], + [], + ) self.unknowns = exc.args[0] if exc.args[1:] == ("unknowns",) else None self.sep_mode = {} return self.allnames = self.names + jets # the monomials as (variable, exponent) pairs: the system has hundreds of variables and few terms self.static = [_sparse(P) for P in static] - self.outs = [([[_sparse(c) for c in row] for row in E], [[_sparse(c) for c in row] for row in M]) - for E, M in outs] + self.outs = [ + ([[_sparse(c) for c in row] for row in E], [[_sparse(c) for c in row] for row in M]) for E, M in outs + ] self.sat = [] for f in (_sparse(_clear(f)) for f in sat): if f not in self.sat: @@ -1174,6 +1265,7 @@ def find(i): parent[i] = parent[parent[i]] i = parent[i] return i + for P in polys + sat: vs = sorted({v for mm in P for v, _ in mm}) for a, b_ in zip(vs, vs[1:]): @@ -1204,8 +1296,12 @@ def _ms_block(self, idx, polys, sat, p): # brackets, so si_w multiplies each term eqs.append(_ms_sparse(fac, self.allnames, "si_w") + "-1") proj = getattr(self, "proj", m) - return {"names": [self.allnames[i] for i in idx], "sep": [self.names[i] for i in idx if i < m], - "proj": [self.names[i] for i in idx if i < proj], "eqs": eqs} + return { + "names": [self.allnames[i] for i in idx], + "sep": [self.names[i] for i in idx if i < m], + "proj": [self.names[i] for i in idx if i < proj], + "eqs": eqs, + } def _monomial_eliminate(polys, sat, m, p=0): @@ -1240,6 +1336,7 @@ def target(P): if all(w != v for w, _ in mo) and (v >= m or all(w < m for w, _ in mo)): return v, div(-b, a), mo return None + while True: hit = next((t for P in polys for t in [target(P)] if t is not None), None) if hit is None: @@ -1311,7 +1408,7 @@ def _decode(d): for j in range(len(start) - 1): P = {} for t in range(start[j], start[j + 1]): - P[tuple(zip(var[tstart[t]:tstart[t + 1]], ex[tstart[t]:tstart[t + 1]]))] = coef[t] + P[tuple(zip(var[tstart[t] : tstart[t + 1]], ex[tstart[t] : tstart[t + 1]]))] = coef[t] out.append(P) return out @@ -1326,6 +1423,7 @@ def _reduce_mod(polys, sat, nv, m0, p): def _reduce_q(polys, sat, nv, m0, p=0): """_reduce() in Python, over Q (p = 0) or GF(p).""" + def div(a, b): return a * pow(b, -1, p) % p if p else Fraction(a) / b @@ -1345,6 +1443,7 @@ def linear_var(P): if len(vs) != 1 or any(mm and (len(mm) != 1 or mm[0][1] != 1) for mm in P): return None return vs.pop() + polys, sat = [dict(P) for P in polys], [dict(f) for f in sat] alive = [bool(P) for P in polys] salive = [True] * len(sat) @@ -1409,8 +1508,12 @@ def linear_var(P): for mm in P: if len(mm) == 1 and mm[0][1] == 1: v = mm[0][0] - if v >= m0 and v not in insat and count.get(v) == 1 and \ - sum(1 for nn in P if any(w == v for w, _ in nn)) == 1: + if ( + v >= m0 + and v not in insat + and count.get(v) == 1 + and sum(1 for nn in P if any(w == v for w, _ in nn)) == 1 + ): hit = (j, v) break if hit: @@ -1426,7 +1529,7 @@ def linear_var(P): def _eval(P, x, zero=Fraction(0)): - return sum((c * math.prod((xi ** e for xi, e in zip(x, m) if e), start=zero + 1) for m, c in P.items()), zero) + return sum((c * math.prod((xi**e for xi, e in zip(x, m) if e), start=zero + 1) for m, c in P.items()), zero) def _msolve(names, p, eqs, flags, sep=()): @@ -1469,8 +1572,11 @@ def parse_rational(txt): """msolve output over Q with every quotient of integers, a / 2^k or a / b, as an exact Fraction.""" # a match starts only at the first digit of a number: otherwise each start inside a long integer scans the # rest of it, quadratic in the number of digits - txt = re.sub(r"(? _STAGE_ROOTS: return None - roots = [-f.all_coeffs()[1] / spy.Integer(f.all_coeffs()[0]) for f, _ in spy.factor_list(sq)[1] - if f.degree() == 1] + roots = [-f.all_coeffs()[1] / spy.Integer(f.all_coeffs()[0]) for f, _ in spy.factor_list(sq)[1] if f.degree() == 1] if len(roots) != sq.degree(): return None @@ -1698,6 +1808,7 @@ def ev(coeffs, x): for c in reversed(coeffs): acc = acc * x + int(c) return acc + out = [] for r in roots: t = Fraction(int(r.p), int(r.q)) @@ -1757,8 +1868,9 @@ def _staged_count(fib, idx, polys, sat, p): return None n = 1 for sub in _components(keep, rp, rs): - k = _staged_count(fib, sub, [P for P in rp if _vars(P) & set(sub)], - [f for f in rs if _vars(f) & set(sub)], p) + k = _staged_count( + fib, sub, [P for P in rp if _vars(P) & set(sub)], [f for f in rs if _vars(f) & set(sub)], p + ) if k is None: return None n *= k @@ -1778,8 +1890,11 @@ def _block_count(fib, idx, polys, sat, p): if data[0] == -1: return 0 deg = int(data[1][2]) - if len(b["proj"]) < len(b["names"]) and getattr(fib, "proj", len(fib.names)) < len(fib.names) and \ - deg <= _PROJ_POINTS: + if ( + len(b["proj"]) < len(b["names"]) + and getattr(fib, "proj", len(fib.names)) < len(fib.names) + and deg <= _PROJ_POINTS + ): # the count of a projection: the distinct values of the projected coordinates on the points k = _projected_count(data, b["proj"]) return deg if k is None else k @@ -1799,6 +1914,7 @@ def _projected_count(data, proj): def poly(cs): return spy.Poly(list(reversed([spy.Integer(int(c)) for c in cs])) or [0], T, domain="QQ") + w = spy.Poly(spy.sqf_part(poly(par[1][0][1]).as_expr()), T, domain="QQ") n = w.degree() try: @@ -1817,6 +1933,7 @@ def poly(cs): def vec(P): c = P.all_coeffs()[::-1] return [Fraction(int(x.p), int(x.q)) for x in c] + [Fraction(0)] * (n - len(c)) + # a reduced echelon basis: each row is zero at the pivots of the others rows = {} @@ -1836,6 +1953,7 @@ def add(P): rows[q] = [a - f * b for a, b in zip(r, v)] rows[piv] = v return True + basis = [spy.Poly(1, T, domain="QQ")] add(basis[0]) k = 0 @@ -1857,6 +1975,7 @@ def find(i): parent[i] = parent[parent[i]] i = parent[i] return i + for P in list(polys) + list(sat): vs = sorted(_vars(P) & parent.keys()) for a, b in zip(vs, vs[1:]): @@ -1882,8 +2001,21 @@ def _gb_count(names, p, eqs, sep=(), cap=5000, exact=False, dims=None): fi, fo = os.path.join(td, "in.ms"), os.path.join(td, "out.ms") with open(fi, "w") as fh: fh.write(",".join(names) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") - r = work.run_msolve([msolve._msolve_binary(), "-f", fi, "-o", fo, "-g", "2", "-l", "2" if exact else "44", - "-t", str(msolve._MSOLVE_THREADS)]) + r = work.run_msolve( + [ + msolve._msolve_binary(), + "-f", + fi, + "-o", + fo, + "-g", + "2", + "-l", + "2" if exact else "44", + "-t", + str(msolve._MSOLVE_THREADS), + ] + ) txt = "" if os.path.exists(fo): with open(fo) as fh: @@ -1899,8 +2031,11 @@ def _gb_count(names, p, eqs, sep=(), cap=5000, exact=False, dims=None): lead = [next(iter(P)) for P in gb] basis = _standard_monomials([dict(m) for m in lead], len(names), cap) if basis is None: - _failed(kind="dimension" if _standard_monomials([dict(m) for m in lead], len(names), 0, finite=True) is None - else "quotient") + _failed( + kind="dimension" + if _standard_monomials([dict(m) for m in lead], len(names), 0, finite=True) is None + else "quotient" + ) return None if dims is not None: dims.append(len(basis)) @@ -2002,10 +2137,12 @@ def _distinct_eigenvalues(M, p, rng): def _gcd_mod(a, b, p): """The monic gcd of two polynomials mod p, coefficients from the constant term up.""" + def trim(x): while x and not x[-1]: x = x[:-1] return x + a, b = trim(list(a)), trim(list(b)) while b: inv = pow(b[-1], -1, p) @@ -2024,7 +2161,7 @@ def _standard_monomials(lead, nv, cap, finite=False): pure = {} for e in lead: if len(e) == 1: - (v, k), = e.items() + ((v, k),) = e.items() pure[v] = min(pure.get(v, k), k) if len(pure) < nv: return None @@ -2065,8 +2202,12 @@ def _boxes_of_maps(fib, pt, maps, check=True): here = fib.values(pt) for im in imgs[1:]: there = fib.values(im) - if here is None or there is None or [r for k, r in enumerate(here) if k not in fib.series.free_rows] != \ - [r for k, r in enumerate(there) if k not in fib.series.free_rows]: + if ( + here is None + or there is None + or [r for k, r in enumerate(here) if k not in fib.series.free_rows] + != [r for k, r in enumerate(there) if k not in fib.series.free_rows] + ): return None return [[(v, v) for v in t] for t in vals] @@ -2078,6 +2219,7 @@ def domain_point(fib, rng): # ---- the rational univariate representation over GF(p) ------------------------------------- + def _rur(fib, point, p): """{"deg", "elim", "den", "par", "lin", "vnames"} of the fiber of `point` (integers mod p), None on failure.""" try: @@ -2098,12 +2240,21 @@ def _rur(fib, point, p): _, _, deg, vnames, lin, par = data[1] if deg <= 0 or par[0] != 1: return None - blocks.append({"deg": int(deg), "elim": [int(c) % p for c in par[1][0][1]], - "den": [int(c) % p for c in par[1][1][1]], - "par": [[int(c) % p for c in q[0][1]] for q in par[1][2]], "lin": [int(c) % p for c in lin], - "vnames": list(vnames)}) - return {"deg": math.prod(b["deg"] for b in blocks), "blocks": blocks, - "fixed": {n: int(v) % p for n, v in sysd["fixed"].items()}} + blocks.append( + { + "deg": int(deg), + "elim": [int(c) % p for c in par[1][0][1]], + "den": [int(c) % p for c in par[1][1][1]], + "par": [[int(c) % p for c in q[0][1]] for q in par[1][2]], + "lin": [int(c) % p for c in lin], + "vnames": list(vnames), + } + ) + return { + "deg": math.prod(b["deg"] for b in blocks), + "blocks": blocks, + "fixed": {n: int(v) % p for n, v in sysd["fixed"].items()}, + } def _pmod(a, f, p): @@ -2214,8 +2365,10 @@ def _charpolys_block(rur, p, names=None): P = np.identity(k, dtype=object) s = [] for _ in range(k): - P = np.array([[sum(int(P[i, l]) * int(M[l, j]) for l in range(k)) % p for j in range(k)] - for i in range(k)], dtype=object) + P = np.array( + [[sum(int(P[i, l]) * int(M[l, j]) for l in range(k)) % p for j in range(k)] for i in range(k)], + dtype=object, + ) s.append(sum(int(P[i, i]) for i in range(k)) % p) e_ = [1] for m in range(1, k + 1): @@ -2246,6 +2399,7 @@ def ev(coeffs, x): for c in reversed(coeffs): acc = (acc * x + c) % p return acc + out = [] for t in _gf_roots(list(reversed(rur["elim"])), p): dv = ev(rur["den"], t) @@ -2261,6 +2415,7 @@ def ev(coeffs, x): # ---- interpolation of the coefficients ------------------------------------------------------- + class _Sampler: """Characteristic polynomials of the fiber at integer points, memoized per point and prime.""" @@ -2273,7 +2428,7 @@ def __init__(self, fib, meter=None): self.checks = None def point(self): - return tuple(self.rng.randint(2, 10 ** 6) for _ in self.fib.syms) + return tuple(self.rng.randint(2, 10**6) for _ in self.fib.syms) def points(self, n): """The first `n` points of one pool, shared by every coefficient.""" @@ -2285,7 +2440,7 @@ def moved_point(self, base, i): """`base` with coordinate i changed, the same for every coefficient.""" if i not in self.moved: pt = list(base) - pt[i] = self.rng.randint(2, 10 ** 6) + pt[i] = self.rng.randint(2, 10**6) self.moved[i] = tuple(pt) return self.moved[i] @@ -2390,14 +2545,12 @@ def interpolate(oracle, sam, base, primes, cap=_DEG_CAP): def _recon(sols, primes, mons, syms): """The rational function from the coefficient vectors modulo the first primes, None where none is bounded.""" - rec = rat_recon(np.array(sols, dtype=np.int64).T, primes[:len(sols)]) + rec = rat_recon(np.array(sols, dtype=np.int64).T, primes[: len(sols)]) if any(dd == "0" for dd in rec["den"]): return None coef = [spy.Rational(int(n), int(dd)) for n, dd in zip(rec["num"], rec["den"])] - num = sum((c * spy.Mul(*[s ** e for s, e in zip(syms, m)]) for c, m in zip(coef[:len(mons)], mons)), - spy.Integer(0)) - den = sum((c * spy.Mul(*[s ** e for s, e in zip(syms, m)]) for c, m in zip(coef[len(mons):], mons)), - spy.Integer(0)) + num = sum((c * spy.Mul(*[s**e for s, e in zip(syms, m)]) for c, m in zip(coef[: len(mons)], mons)), spy.Integer(0)) + den = sum((c * spy.Mul(*[s**e for s, e in zip(syms, m)]) for c, m in zip(coef[len(mons) :], mons)), spy.Integer(0)) return None if den == 0 else spy.cancel(num / den) @@ -2420,10 +2573,11 @@ def _holds(oracle, sam, r, p): # ---- the maps ------------------------------------------------------------------------------ + def _rational_roots(coeffs, Z): """The roots in Q(theta) of Z^k + sum c_j Z^j, without repeats.""" k = len(coeffs) - poly = Z ** k + sum((c * Z ** j for j, c in enumerate(coeffs)), spy.Integer(0)) + poly = Z**k + sum((c * Z**j for j, c in enumerate(coeffs)), spy.Integer(0)) num = spy.fraction(spy.together(poly))[0] out = [] for fac, _ in spy.factor_list(num, Z)[1]: @@ -2484,7 +2638,9 @@ def coeff(nm, j): def oracle(pt, p): c = sam.at(pt, p) return None if c is None else c[nm][j] + return oracle + size = {} for nm in fib.names: sup = set() @@ -2505,8 +2661,11 @@ def oracle(pt, p): roots[fib.syms[fib.names.index(nm)]] = rs lab = _labels(sam, roots, sam.points(1)[0], primes[1]) # separated: no two points of rational branches share a label - if lab is not None and len(lab) == sum(1 for fp in sam.points_of(sam.points(1)[0], primes[1]) - if _on_roots(sam, roots, fp, sam.points(1)[0], primes[1])): + if lab is not None and len(lab) == sum( + 1 + for fp in sam.points_of(sam.points(1)[0], primes[1]) + if _on_roots(sam, roots, fp, sam.points(1)[0], primes[1]) + ): labels = lab break if labels is None: @@ -2524,7 +2683,9 @@ def oracle(pt, p): if not ls or lab not in ls: return None return ls[lab][nm] + return oracle + for s, nm in zip(fib.syms, fib.names): if s in sig: continue @@ -2608,6 +2769,7 @@ def swapped(pairs): for i, j in pairs: v[i], v[j] = v[j], v[i] return v + base = vals(pt) if base is None: return [] @@ -2667,6 +2829,7 @@ def _block_map(F, H, X, x0, th): def coeffs(e): num = spy.fraction(spy.together(e))[0] return spy.Poly(spy.expand(num), *X).coeffs() if num != 0 else [] + for x in block: rhs = sum((spy.diff(phi[x], y) * F[y] for y in X), spy.Integer(0)) eqs += coeffs(F[x].xreplace(both) - rhs) @@ -2699,8 +2862,12 @@ def _state_map(f, g, ic, sig, states): own = {} for x in X if ic is not None else (): q = model_sympify(str(ic.get(str(x), x))) - if q == x or (q.is_Symbol and q in sig and q not in used and - sum(model_sympify(str(ic.get(str(y), y))) == q for y in X) == 1): + if q == x or ( + q.is_Symbol + and q in sig + and q not in used + and sum(model_sympify(str(ic.get(str(y), y))) == q for y in X) == 1 + ): own[q] = x phi = {x: x for x in X} for q, x in own.items(): @@ -2724,6 +2891,7 @@ def holds(phi): # phi at theta maps x0(theta) to x0(sigma(theta)) for the given initial values at0 = {y: x0[y] for y in given} return all(spy.cancel(phi[x].xreplace(at0) - x0[x].xreplace(th)) == 0 for x in given) + try: if holds(phi): return phi @@ -2735,7 +2903,7 @@ def holds(phi): continue c = spy.cancel(R.xreplace({**th, **phi}) / R) if c.is_Rational and c not in (0, 1): - alt[x] = x ** c + alt[x] = x**c if alt != phi and holds(alt): return alt blk = _block_map(F, H, X, x0, th) @@ -2750,15 +2918,19 @@ def holds(phi): # the terms of a row bound those of the equation from it, before the row is put over one denominator bound = max((_term_bound(h) for h in rows), default=0) if bound > cap: - _CAPPED.add(f"a map of the states was not solved from the outputs: their Lie derivatives expand to " - f"up to {bound:.3g} terms, past the cap state_map_terms of {cap:,}") + _CAPPED.add( + f"a map of the states was not solved from the outputs: their Lie derivatives expand to " + f"up to {bound:.3g} terms, past the cap state_map_terms of {cap:,}" + ) return None eqs += [spy.fraction(spy.together(h.xreplace(img) - h))[0] for h in rows] rows = [sum((spy.diff(h, y) * F[y] for y in F), spy.Integer(0)) for h in rows] bound = max((_term_bound(e) for e in eqs), default=0) if bound > cap: - _CAPPED.add(f"a map of the states was not solved from the outputs: their equations expand to up to " - f"{bound:.3g} terms, past the cap state_map_terms of {cap:,}") + _CAPPED.add( + f"a map of the states was not solved from the outputs: their equations expand to up to " + f"{bound:.3g} terms, past the cap state_map_terms of {cap:,}" + ) return None eqs = [spy.expand(e) for e in eqs] if any(e != 0 and spy.Poly(e, *P.values()).total_degree() > 1 for e in eqs): @@ -2798,6 +2970,7 @@ def state_map_proof(parts, sig, states, positive=True): out = _state_map_proof(parts, sig, states, positive) if out is None and any(seg.get("inputs") for part in parts for seg in part["segments"]): from .uinputs import input_state_map + out = input_state_map(parts, sig, states) return out @@ -2898,8 +3071,10 @@ def fundamental_domain(coords, states, maps): """Per map the inequality theta_c < sigma_c(theta) on the first coordinate c it moves in one order of the coordinates, parameters with simple images first: theta is the least of the orbit in that order.""" syms = [spy.Symbol(c) for c in coords] - order = sorted(syms, key=lambda x: (str(x) in set(states), sum(spy.count_ops(sig.get(x, x)) for sig in maps), - coords.index(str(x)))) + order = sorted( + syms, + key=lambda x: (str(x) in set(states), sum(spy.count_ops(sig.get(x, x)) for sig in maps), coords.index(str(x))), + ) out = [] for sig in maps: c = next(x for x in order if sig.get(x, x) != x) @@ -2920,10 +3095,13 @@ def choose_order(series, positive, start, cap, floor=1, proj=None, lowest=False, # at the orders of the rank criterion the system is square and has extra solutions; one order higher it is # smaller in count and faster to solve. Every observable starts at the highest of these orders: an observable # whose next coefficient adds no rank in the coordinates can still remove points, where the start is given - base = ([c + 1 for c in crit] if lowest else [max(crit) + 1] * len(crit)) if crit else \ - [max(1, start)] * len(series.labels) + base = ( + ([c + 1 for c in crit] if lowest else [max(crit) + 1] * len(crit)) + if crit + else [max(1, start)] * len(series.labels) + ) rng = session.current().rng("discrete order", tuple(series.coords)) - point = {spy.Symbol(c): spy.Integer(rng.randint(2, 10 ** 6)) for c in series.coords} + point = {spy.Symbol(c): spy.Integer(rng.randint(2, 10**6)) for c in series.coords} prev = found = None for t in range(min(cap, raises) + 1): orders = [n + t for n in base] @@ -2976,8 +3154,9 @@ def pinned_count(series, positive, floor, names=None): `cert` None where the route does not apply or no count is below twice the orbit.""" out = {"why": None, "orders": None, "count": None, "cert": None, "fiber": None, "functions": None} cap = 2 * len(series.coords) - if series.has_events or any(seg.get("free") or seg.get("on") is not None - for part in series.parts for seg in part["segs"]): + if series.has_events or any( + seg.get("free") or seg.get("on") is not None for part in series.parts for seg in part["segs"] + ): out["why"] = "the count of the proven functions covers models without events, switches and free starts" return out crit = series.output_orders(cap, PRIMES[0]) @@ -3017,7 +3196,7 @@ def _pin_sets(series, p): basis.append([x * inv % p for x in row]) piv.append(c) first.append(i) - first += [i for i in order if i not in first][:len(first)] + first += [i for i in order if i not in first][: len(first)] return [sorted(first), every] if len(first) < len(every) else [every] @@ -3032,7 +3211,7 @@ def _pinned_once(series, positive, floor, crit, cap): out["why"] = "the proven functions do not lower the orders of the rank criterion" return out rng = session.current().rng("discrete pinned", tuple(series.coords)) - point = {spy.Symbol(c): spy.Integer(rng.randint(2, 10 ** 6)) for c in series.coords} + point = {spy.Symbol(c): spy.Integer(rng.randint(2, 10**6)) for c in series.coords} fib = cc = None # one order above the criterion first, as in choose_order(): at the criterion the starts often have extra points; # at most to the order of the rank criterion of the outputs alone, one below the first count without pins @@ -3044,8 +3223,11 @@ def _pinned_once(series, positive, floor, crit, cap): break out.update(orders=fib.orders, count=cc, fiber=fib) if cc is None or cc >= 2 * floor: - out["why"] = (f"the count of the proven functions is {cc}, not below {2 * floor}" if cc is not None else - "msolve gave no count of the proven functions") + out["why"] = ( + f"the count of the proven functions is {cc}, not below {2 * floor}" + if cc is not None + else "msolve gave no count of the proven functions" + ) return out out["cert"] = count_certificate(fib, floor, base, within=(floor, 2 * floor)) if out["cert"]["bound"] is None: @@ -3084,9 +3266,14 @@ def _candidate_stage(series, parts, states, positive, meter): gap = _DEEPER if series.has_events else 0 found = candidates(series, order, gap, PRIMES[0], meter) out = [(sig, None if series.start_powers else state_map_proof(parts, sig, states, positive)) for sig in found] - return out, {"order": order, "found": len(found), "proven": sum(pf is not None for _, pf in out), - "seconds": round(time.monotonic() - t0, 2), "permutations": meter.spent, - "complete_search": not meter.over} + return out, { + "order": order, + "found": len(found), + "proven": sum(pf is not None for _, pf in out), + "seconds": round(time.monotonic() - t0, 2), + "permutations": meter.spent, + "complete_search": not meter.over, + } def analyze(parts, coords, positive, states, order=None, start=None, points=_POINTS, inputs=(), experiments=None): @@ -3118,6 +3305,7 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI # the exact count first, with the group of the proven candidates: where it holds, the fiber is the orbit and # neither the count nor the reconstruction is needed from .fieldproof import exact_fiber + proof, tried = None, None # the constants of the model that are no coordinates enter the exact count as known symbols, in the base field consts = sorted(str(x) for x in series.known) @@ -3197,8 +3385,10 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI elif me is not None and me.get("used"): # one experiment gave no count: the maps of the fiber of one are not reconstructed k = cc - limits.append("the count is that of several experiments; the maps of the fiber of one were not " - "reconstructed, since msolve gave no count of it") + limits.append( + "the count is that of several experiments; the maps of the fiber of one were not " + "reconstructed, since msolve gave no count of it" + ) elif cc is not None and cgrp is not None and len(cgrp) == cc and len(proven) == len(cand): # the proven candidates account for every point counted: the fiber has no other map to reconstruct k, maps = cc, [] @@ -3222,18 +3412,24 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI fib, stable, cc = Fiber(series, [n + 2 for n in fib.orders], positive, gap=fib.gap + 2), False, None timing["maps"] = round(time.monotonic() - t2, 2) if false: - limits.append(f"{len(false)} of the maps of the fiber at order {fib.order} change the coefficients up " - f"to order {fib.order + _DEEPER}: the count is that of the equations up to order " - f"{fib.order}, more than the values with the same output") + limits.append( + f"{len(false)} of the maps of the fiber at order {fib.order} change the coefficients up " + f"to order {fib.order + _DEEPER}: the count is that of the equations up to order " + f"{fib.order}, more than the values with the same output" + ) maps = [sig for sig in maps if all(sig is not f for f in false)] if maps is None and mmeter.over: limits.append(f"the closed forms of the maps were not found: {mmeter.reason()}") elif getattr(fib, "unknowns", None): - limits.append(f"the equations of the fiber at order {fib.order} have {fib.unknowns} unknowns, more than the " - f"{_FIBER_UNKNOWNS} a count takes") + limits.append( + f"the equations of the fiber at order {fib.order} have {fib.unknowns} unknowns, more than the " + f"{_FIBER_UNKNOWNS} a count takes" + ) elif getattr(fib, "too_large", None): - limits.append(f"the equations of the fiber at order {fib.order} have more than {_fiber_terms()} terms, the " - "most a count takes (switch FIBER_TERMS)") + limits.append( + f"the equations of the fiber at order {fib.order} have more than {_fiber_terms()} terms, the " + "most a count takes (switch FIBER_TERMS)" + ) else: limits.append(no_count_reason(fib.order)) # the candidates join the maps of the fiber @@ -3241,6 +3437,7 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI every = list(maps or []) # numerical monodromy proposes the maps that the reconstruction over Q misses (detection.monodromy) from .monodromy import proposals + t2 = time.monotonic() mono, mono_maps = proposals(series, fib, k, every + [sig for sig, _ in cand]) if mono is not None: @@ -3265,13 +3462,26 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI route, single = None, complete and not (me or {}).get("final") and not (me or {}).get("used") if me is not None and (me.get("used") or me.get("final")): route = me - elif me is not None and me.get("count") and orbit and not false and orbit <= me["count"] < 2 * orbit and \ - all(e["level"] == "exact" for e in out) and (forced or not complete): + elif ( + me is not None + and me.get("count") + and orbit + and not false + and orbit <= me["count"] < 2 * orbit + and all(e["level"] == "exact" for e in out) + and (forced or not complete) + ): route, complete, k = me, True, orbit # the exact count: the field fixed by the exact maps inside the field of the output coefficients # again with the group of all exact maps, where the reconstruction found more of them - if grp is not None and not spow and not (proof and proof["exact"]) and \ - (tried is None or len(grp) != len(tried)) and not (route is not None and complete) and not series.inputs: + if ( + grp is not None + and not spow + and not (proof and proof["exact"]) + and (tried is None or len(grp) != len(tried)) + and not (route is not None and complete) + and not series.inputs + ): t3 = time.monotonic() # the functions the first search proved in the field of the outputs hold for any group pre = (proof or {}).get("proven", []) @@ -3294,8 +3504,9 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI t4 = time.monotonic() if route is not None: # the experiments over Q: below twice the orbit, or at most their count modulo the prime - cb = count_certificate(route["fiber"], route["count"], route["crit"], - within=(orbit, 2 * orbit) if complete else None) + cb = count_certificate( + route["fiber"], route["count"], route["crit"], within=(orbit, 2 * orbit) if complete else None + ) if cb["bound"] is None and single: # the count of one experiment equals the orbit as well and may verify where the experiments do not one = count_certificate(fib, k, series.output_orders(2 * len(coords), PRIMES[0])) @@ -3306,8 +3517,10 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI timing["verified"] = round(time.monotonic() - t4, 2) if k is not None and orbit is not None and orbit < k: for c, g in power_coordinates(series).items(): - limits.append(f"{c} enters only as {c}^{g}: the fiber holds {c} -> zeta*{c} with zeta^{g} = 1, maps " - "over Q(zeta) that the reconstruction over Q does not give") + limits.append( + f"{c} enters only as {c}^{g}: the fiber holds {c} -> zeta*{c} with zeta^{g} = 1, maps " + "over Q(zeta) that the reconstruction over Q does not give" + ) relevant = [e for e in out if e.get("preserves_domain") is not False and e["level"] != "open"] # the fiber is the orbit of the group: a map that keeps the domain keeps the point inside, one that never does # moves it out @@ -3318,17 +3531,30 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI count_domain = 1 + sum(keeps) limits += sorted(_CAPPED) if series.capped is not None: - limits.append(f"the Taylor coefficients of the outputs up to order {series.capped} were not formed: " - f"{series.meter.reason()}; the stages that need the orders of the rank criterion were skipped") - info = {"order": fib.order, "orders": dict(zip(series.labels, fib.orders)), "gap_order": fib.gap, - "order_stable": stable, "count": k, "count_domain": count_domain, "count_bound": cb and cb["bound"], - "counts": counts, "limits": limits, - "closed_forms": maps is not None, - "count_final": complete, - "fundamental_domain": fundamental_domain(coords, states, [ - {spy.Symbol(s): model_sympify(v) for s, v in e["map"].items()} for e in relevant]), - "candidates": cinfo, "timing": timing, "monodromy": mono, - "certificate": certificate(out, orbit, k, counts, complete, cb, proof, route, _pinned_info(pinned))} + limits.append( + f"the Taylor coefficients of the outputs up to order {series.capped} were not formed: " + f"{series.meter.reason()}; the stages that need the orders of the rank criterion were skipped" + ) + info = { + "order": fib.order, + "orders": dict(zip(series.labels, fib.orders)), + "gap_order": fib.gap, + "order_stable": stable, + "count": k, + "count_domain": count_domain, + "count_bound": cb and cb["bound"], + "counts": counts, + "limits": limits, + "closed_forms": maps is not None, + "count_final": complete, + "fundamental_domain": fundamental_domain( + coords, states, [{spy.Symbol(s): model_sympify(v) for s, v in e["map"].items()} for e in relevant] + ), + "candidates": cinfo, + "timing": timing, + "monodromy": mono, + "certificate": certificate(out, orbit, k, counts, complete, cb, proof, route, _pinned_info(pinned)), + } if me is not None: info["experiments"] = _route_info(me) if spow: @@ -3339,13 +3565,21 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI def _entry(sig, proofs, maps, mono_maps, fib, syms, parts, states, positive, spow): """The result entry of the map `sig`: the state maps from `proofs` (by id) or proven here, and the stages that found it.""" - entry = {"map": {str(s): str(e) for s, e in sig.items() if e != s}, - "changes": [str(s) for s in syms if sig[s] != s]} + entry = { + "map": {str(s): str(e) for s, e in sig.items() if e != s}, + "changes": [str(s) for s in syms if sig[s] != s], + } pf = proofs[id(sig)] if id(sig) in proofs else None if spow else state_map_proof(parts, sig, states, positive) entry["level"] = "exact" if pf is not None else "checked" - entry["found_by"] = [w for w, hit in (("candidates", id(sig) in proofs), - ("fiber", any(sig is m for m in maps or [])), - ("monodromy", any(sig is m for m in mono_maps))) if hit] + entry["found_by"] = [ + w + for w, hit in ( + ("candidates", id(sig) in proofs), + ("fiber", any(sig is m for m in maps or [])), + ("monodromy", any(sig is m for m in mono_maps)), + ) + if hit + ] entry["state_maps"] = pf entry["preserves_domain"], entry["domain_conditions"] = domain_conditions(fib, sig) entry["fixed_set"] = fixed_set(sig) @@ -3361,16 +3595,26 @@ def _start_power_info(info, spow): for sp in spow: pf = sp["proof"] premises += pf["premises"] - info["start_powers"].append({ - "state": sp["state"], "exponent": sp["alpha"], "order": sp["k"], "leading": pf["leading"], - "observable": pf["observable"], "index": pf["index"], "coefficient": pf["coefficient"], - "premises": list(pf["premises"])}) + info["start_powers"].append( + { + "state": sp["state"], + "exponent": sp["alpha"], + "order": sp["k"], + "leading": pf["leading"], + "observable": pf["observable"], + "index": pf["index"], + "coefficient": pf["coefficient"], + "premises": list(pf["premises"]), + } + ) cert.setdefault("proven", []).append( f"every point of the fiber in the domain has the exponent {sp['alpha']} of the point, by the lowest " - f"exponent other than an integer of {pf['observable']}") + f"exponent other than an integer of {pf['observable']}" + ) info["limits"].append( "the series of " + ", ".join(f"{sp['state']}^{sp['alpha']}" for sp in spow) + " are in t and in the " - "layers (t^k)^(m alpha), with the normalized power (x/c_x)^alpha (info['discrete']['start_powers'])") + "layers (t^k)^(m alpha), with the normalized power (x/c_x)^alpha (info['discrete']['start_powers'])" + ) if premises: cert["premise"] = "; ".join(premises) if cert.get("complete") in ("exact", "verified"): @@ -3382,6 +3626,7 @@ def _experiments(parts, coords, series, positive, floor, experiments, timing): """multiexp.count(), timed.""" from . import multiexp + t = time.monotonic() me = multiexp.count(parts, coords, series, positive, floor, experiments) timing["experiments"] = round(time.monotonic() - t, 2) @@ -3391,14 +3636,14 @@ def _experiments(parts, coords, series, positive, floor, experiments, timing): def _final(me, floor, proven, cand): """Whether the count of the experiments is below twice the orbit of the proven candidates, all proven: the orbit divides the size of the fiber, which the count bounds.""" - return me is not None and bool(me.get("count")) and len(proven) == len(cand) and \ - floor <= me["count"] < 2 * floor + return me is not None and bool(me.get("count")) and len(proven) == len(cand) and floor <= me["count"] < 2 * floor def _verified(series, syms, large): """fewcoef.verified_functions() with the threads of msolve for the kernels, within the cap verified_entries of work.CAPS on the entries of the matrices reduced.""" from . import fewcoef, ioproj + rng = session.current().rng("discrete verified", tuple(series.coords)) log, threads = [], ioproj.THREADS[0] ioproj.THREADS[0] = max(1, int(msolve._MSOLVE_THREADS)) @@ -3416,8 +3661,10 @@ def _add_relation_bound(pinned, verified): coefficient.""" if verified is None: return - pinned["relation"] = {k: verified.get(k) for k in ("terms", "reference", "functions", "exist", "checks", - "trials", "kernels", "degree", "height", "why")} + pinned["relation"] = { + k: verified.get(k) + for k in ("terms", "reference", "functions", "exist", "checks", "trials", "kernels", "degree", "height", "why") + } cb = pinned["cert"] used = [f for f in pinned["functions"] or [] if f in verified["checks"]] if cb is None or cb["bound"] is None or not used: @@ -3434,13 +3681,23 @@ def _pinned_info(pinned): return None cb = pinned["cert"] or {} fib = pinned["fiber"] - out = {"functions": pinned["functions"], "orders": dict(zip(fib.series.labels, fib.orders)) if fib else None, - "count_modp": pinned["count"], "count": cb.get("count"), "count_bound": cb.get("bound"), - "count_bits": cb.get("bits"), "bezout": cb.get("bezout"), "why": pinned["why"]} + out = { + "functions": pinned["functions"], + "orders": dict(zip(fib.series.labels, fib.orders)) if fib else None, + "count_modp": pinned["count"], + "count": cb.get("count"), + "count_bound": cb.get("bound"), + "count_bits": cb.get("bits"), + "bezout": cb.get("bezout"), + "why": pinned["why"], + } if pinned.get("relation") is not None: # the bound of the count over Q alone, and that of the verified relation, whose sum is count_bound - out.update(relation=pinned["relation"], relation_bound=pinned.get("relation_bound"), - count_bound_q=cb.get("count_bound", cb.get("bound"))) + out.update( + relation=pinned["relation"], + relation_bound=pinned.get("relation_bound"), + count_bound_q=cb.get("count_bound", cb.get("bound")), + ) return out @@ -3498,19 +3755,26 @@ def _domain_counts(fib, maps, k, points, coords, proven=None): elements `proven` of a group of proven maps whose orbit has `k` points, the fiber at a point is the orbit of the point.""" rng = session.current().rng("discrete domain", tuple(coords)) - pts = [domain_point(fib, rng) for _ in range(points)] if isinstance(points, int) else \ - [{spy.Symbol(str(k_)): spy.Rational(str(v)) for k_, v in dict(pt).items()} for pt in points] + pts = ( + [domain_point(fib, rng) for _ in range(points)] + if isinstance(points, int) + else [{spy.Symbol(str(k_)): spy.Rational(str(v)) for k_, v in dict(pt).items()} for pt in points] + ) def count_at(pt): if proven is not None: boxes = _boxes_of_maps(fib, pt, proven, check=False) if boxes is not None: return None, boxes - cc = complex_count(fib, {s: v for s, v in pt.items()}, PRIMES[0]) \ - if all(v.q % PRIMES[0] for v in pt.values()) else None + cc = ( + complex_count(fib, {s: v for s, v in pt.items()}, PRIMES[0]) + if all(v.q % PRIMES[0] for v in pt.values()) + else None + ) # where the maps account for every point counted, the point and the images are the fiber, exactly boxes = _boxes_of_maps(fib, pt, maps) if maps is not None and cc == k == len(maps) + 1 else None return cc, boxes if boxes is not None else real_points(fib, pt) + # msolve gains little from threads: the points run as processes of one thread each workers = max(1, min(int(msolve._MSOLVE_THREADS), len(pts))) with msolve.msolve_threads(1): @@ -3522,13 +3786,20 @@ def count_at(pt): counts = [] for pt, (cc, boxes) in zip(pts, done): if boxes is None: - counts.append({"point": {str(s): str(v) for s, v in pt.items()}, "complex": cc, "real": None, - "in_domain": None}) + counts.append( + {"point": {str(s): str(v) for s, v in pt.items()}, "complex": cc, "real": None, "in_domain": None} + ) continue dom = [in_domain(fib, b) for b in boxes] - counts.append({"point": {str(s): str(v) for s, v in pt.items()}, "complex": cc, "real": len(boxes), - "in_domain": sum(d is True for d in dom), - "undecided": sum(d is None for d in dom)}) + counts.append( + { + "point": {str(s): str(v) for s, v in pt.items()}, + "complex": cc, + "real": len(boxes), + "in_domain": sum(d is True for d in dom), + "undecided": sum(d is None for d in dom), + } + ) return counts @@ -3542,8 +3813,7 @@ def _fiber_degrees(fib): whose degrees in theta come from the recursion of the series on degree bounds; None at a pole.""" A = Atoms() try: - outs = fib.series._outputs([Deg(A, 1) for _ in fib.series.cs], fib.order, 0, Deg.const(A, 1), - Deg.const(A, 0)) + outs = fib.series._outputs([Deg(A, 1) for _ in fib.series.cs], fib.order, 0, Deg.const(A, 1), Deg.const(A, 0)) except ZeroDivisionError: outs = None if outs is None: @@ -3559,8 +3829,12 @@ def _fiber_degrees(fib): for (E, M), b, n in zip(fib.outs, bnum, fib.orders): for k in range(n + 1): for m in range(len(M[k])): - terms = [_sparse_deg(E[l_][a]) + b[k - l_][m - a] for l_ in range(k + 1) for a in range(m + 1) - if a < len(E[l_]) and E[l_][a] and m - a < len(b[k - l_]) and b[k - l_][m - a] is not None] + terms = [ + _sparse_deg(E[l_][a]) + b[k - l_][m - a] + for l_ in range(k + 1) + for a in range(m + 1) + if a < len(E[l_]) and E[l_][a] and m - a < len(b[k - l_]) and b[k - l_][m - a] is not None + ] if M[k][m]: terms.append(_sparse_deg(M[k][m]) + dq) if terms: @@ -3588,8 +3862,12 @@ def _x_bezout(fib): # the leading coefficient of the base of a free power is a factor of the saturation in the jets return None # a coordinate pinned to the value at the point is the equation x_i = theta_i, of degree one - pinned = [i for i in range(len(series.cs)) for n, d in series.pins - if d == {(0,) * len(series.cs): 1} and n == {tuple(int(j == i) for j in range(len(series.cs))): 1}] + pinned = [ + i + for i in range(len(series.cs)) + for n, d in series.pins + if d == {(0,) * len(series.cs): 1} and n == {tuple(int(j == i) for j in range(len(series.cs))): 1} + ] # the rows of the outputs, and the rows of the pins before those of the outputs: the smaller product got = [_row_degrees(series, series.rank_rows(2 * len(series.cs), PRIMES[0], skip=sorted(set(pinned))))] if series.pins: @@ -3608,10 +3886,19 @@ def _x_bezout(fib): vals = dict(zip(gens, start + list(series.params))) def ev(Pd): - return sum((spy.Rational(c.numerator, c.denominator) * spy.prod([g ** e for g, e in zip(gens, m)]) - for m, c in Pd.items()), spy.Integer(0)).xreplace(vals) - dens = [spy.fraction(spy.together(v))[1] for v in start] + [ev(D) for _, D in seg["F"]] + \ - [ev(E) for _, E in seg["G"]] + return sum( + ( + spy.Rational(c.numerator, c.denominator) * spy.prod([g**e for g, e in zip(gens, m)]) + for m, c in Pd.items() + ), + spy.Integer(0), + ).xreplace(vals) + + dens = ( + [spy.fraction(spy.together(v))[1] for v in start] + + [ev(D) for _, D in seg["F"]] + + [ev(E) for _, E in seg["G"]] + ) for d in dens: sat = sat * spy.fraction(spy.together(d))[0] * spy.fraction(spy.together(d))[1] syms = [spy.Symbol(c) for c in series.coords] @@ -3689,6 +3976,7 @@ def count_certificate(fib, k, crit, within=None): return out if series.inputs: from .uinputs import count_certificate as with_inputs + return with_inputs(fib, k, out) if crit is None or any(o < c for o, c in zip(fib.orders, crit)): out["why"] = "the orders are below those of the rank criterion" @@ -3712,13 +4000,14 @@ def count_certificate(fib, k, crit, within=None): return out out["bits"] = bits rng = session.current().rng("verified count", tuple(fib.coords)) - pt = {s: spy.Integer(rng.randint(1, 2 ** bits)) for s in fib.syms} + pt = {s: spy.Integer(rng.randint(1, 2**bits)) for s in fib.syms} # msolve over Q per block, plain and then with the separating form k2 = q_count(fib, pt) out["count"] = k2 if not k2: - out["why"] = f"no finite count over Q at the random integer point of {bits} bits" + \ - (f": {no_count_reason(fib.order)}" if k2 is None and "size" in _FAILURES else "") + out["why"] = f"no finite count over Q at the random integer point of {bits} bits" + ( + f": {no_count_reason(fib.order)}" if k2 is None and "size" in _FAILURES else "" + ) return out if within is None and k2 != k: out["why"] = f"the count over Q at a random integer point is {k2}, not {k}" @@ -3743,20 +4032,32 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= exact = exact or {"exact": False, "why": None} bound = None if exact.get("exact") else cb.get("bound") out = { - "invariance": [{"map": e["map"], "proven": e["level"] == "exact", "state_maps": e.get("state_maps")} - for e in entries], + "invariance": [ + {"map": e["map"], "proven": e["level"] == "exact", "state_maps": e.get("state_maps")} for e in entries + ], "identities": "f(phi(x), sigma(theta)) = Dphi(x) f(x, theta), h(phi(x), sigma(theta)) = h(x, theta) and " - "phi(x0(theta)) = x0(sigma(theta)), in every segment and through every event, as identities " - "of rational functions over Q, or over Q(i) for a map with complex coefficients, checked by " - "cancellation", - "orbit": orbit, "count": k, "prime": PRIMES[0], "counts_at_points": agree, - "proven": ["the invariance of every map at level exact", - f"the orbit of a generic point under the group of the exact maps has {orbit} points"], - "exact": exact, "count_bound": bound, "count_bound_why": None if exact.get("exact") else cb.get("why"), - "count_bits": cb.get("bits"), "bezout": cb.get("bezout")} + "phi(x0(theta)) = x0(sigma(theta)), in every segment and through every event, as identities " + "of rational functions over Q, or over Q(i) for a map with complex coefficients, checked by " + "cancellation", + "orbit": orbit, + "count": k, + "prime": PRIMES[0], + "counts_at_points": agree, + "proven": [ + "the invariance of every map at level exact", + f"the orbit of a generic point under the group of the exact maps has {orbit} points", + ], + "exact": exact, + "count_bound": bound, + "count_bound_why": None if exact.get("exact") else cb.get("why"), + "count_bits": cb.get("bits"), + "bezout": cb.get("bezout"), + } if exact.get("exact"): - out["proven"].append("the field fixed by the exact maps lies in the field of the output coefficients, so " - f"the fiber at a generic point is the orbit of {orbit} points") + out["proven"].append( + "the field fixed by the exact maps lies in the field of the output coefficients, so " + f"the fiber at a generic point is the orbit of {orbit} points" + ) out["complete"] = "exact" return out if pinned is not None: @@ -3766,51 +4067,74 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= out["proven"].append( f"the {len(pinned['functions'])} functions under pinned lie in the field of the output coefficients (the " "relations and generators under exact" - + (", and for the functions under pinned.relation the relation of the projection there, verified" if - pinned.get("relation_bound") is not None else "") + + ( + ", and for the functions under pinned.relation the relation of the projection there, verified" + if pinned.get("relation_bound") is not None + else "" + ) + "), so they take one value on the fiber, which lies in the solutions of these functions and the output " - "coefficients up to the orders under pinned") + "coefficients up to the orders under pinned" + ) if complete: - out["proven"].append(f"the orbit of {orbit} point{'' if orbit == 1 else 's'} divides the size of the " - f"fiber, and a count below {2 * orbit} leaves the orbit") + out["proven"].append( + f"the orbit of {orbit} point{'' if orbit == 1 else 's'} divides the size of the " + f"fiber, and a count below {2 * orbit} leaves the orbit" + ) if route is not None: K, fi = route["experiments"], route["first_integrals"] - out["route"] = {"experiments": K, "orders": route["orders"], "count": route["count"], - "first_integrals": fi} + out["route"] = {"experiments": K, "orders": route["orders"], "count": route["count"], "first_integrals": fi} out["proven"].append( "no nonconstant rational first integral at a generic point: the eigenvalues of the Jacobian at an " f"equilibrium over {fi['field']} at one point of the parameters are linearly independent over Z " - "(Cong, Llibre and Zhang 2011, Theorem 1), and a first integral at a generic point would give one there") + "(Cong, Llibre and Zhang 2011, Theorem 1), and a first integral at a generic point would give one there" + ) out["proven"].append( f"so the values of the parameters and the starts of the first of {K} experiments with shared parameters " - "and free starts, over their fiber, are the fiber of one experiment") + "and free starts, over their fiber, are the fiber of one experiment" + ) if complete: - out["proven"].append(f"the orbit of {orbit} point{'' if orbit == 1 else 's'} divides the size of the " - f"fiber, and a count below {2 * orbit} leaves the orbit") + out["proven"].append( + f"the orbit of {orbit} point{'' if orbit == 1 else 's'} divides the size of the " + f"fiber, and a count below {2 * orbit} leaves the orbit" + ) if bound is None: - out["axiom"] = ("the number of solutions modulo the prime at a random point equals the number over the " - "complex numbers at a generic point; no error bound is proven") + out["axiom"] = ( + "the number of solutions modulo the prime at a random point equals the number over the " + "complex numbers at a generic point; no error bound is proven" + ) why = [w for w in (exact.get("why"), cb.get("why")) if w] out["count_bound_why"] = "; ".join(why) or None elif used: n = cb["count"] top = max(pinned["orders"].values()) - out["bounded"] = (f"the count of the proven functions and the output coefficients up to order {top} over Q " - f"at a random integer point is {n}, so the fiber at a generic point has at most {n} " - f"point{'' if n == 1 else 's'}, except with probability at most {bound:.3g}" - + (f", of which {pinned['relation_bound']:.3g} for the verified relation" - if pinned.get("relation_bound") is not None else "")) + out["bounded"] = ( + f"the count of the proven functions and the output coefficients up to order {top} over Q " + f"at a random integer point is {n}, so the fiber at a generic point has at most {n} " + f"point{'' if n == 1 else 's'}, except with probability at most {bound:.3g}" + + ( + f", of which {pinned['relation_bound']:.3g} for the verified relation" + if pinned.get("relation_bound") is not None + else "" + ) + ) elif route is not None: n = cb["count"] - out["bounded"] = (f"the count of the {route['experiments']} experiments over Q at a random integer point is " - f"{n}, at least the number of values of the parameters and the starts of the first there, so " - f"the fiber of one experiment at a generic point has at most {n} point" - f"{'' if n == 1 else 's'}, except with probability at most {bound:.3g}") + out["bounded"] = ( + f"the count of the {route['experiments']} experiments over Q at a random integer point is " + f"{n}, at least the number of values of the parameters and the starts of the first there, so " + f"the fiber of one experiment at a generic point has at most {n} point" + f"{'' if n == 1 else 's'}, except with probability at most {bound:.3g}" + ) else: - out["bounded"] = (f"the fiber at a generic point has at most {k} points, except with probability at most " - f"{bound:.3g} (the count over Q at a random integer point)") - out["complete"] = ("verified" if bound is not None else "axiom") if complete else \ - ("no" if k is not None and orbit is not None and orbit < k else "open") + out["bounded"] = ( + f"the fiber at a generic point has at most {k} points, except with probability at most " + f"{bound:.3g} (the count over Q at a random integer point)" + ) + out["complete"] = ( + ("verified" if bound is not None else "axiom") + if complete + else ("no" if k is not None and orbit is not None and orbit < k else "open") + ) return out @@ -3853,29 +4177,43 @@ def resting_start(f, ic, inputs, coords): odd = [str(x) for x, e in zip(U, bal) if not e.is_polynomial(*U)] if odd: from .rationalize import NotRationalError - raise NotRationalError("discrete() under equilibrate needs a resting state with one rational closed form in " - f"the coordinates; the balances of {', '.join(odd)} are not rational in the states") + + raise NotRationalError( + "discrete() under equilibrate needs a resting state with one rational closed form in " + f"the coordinates; the balances of {', '.join(odd)} are not rational in the states" + ) cap = work.CAPS["rest_bezout"] bezout = math.prod(max(1, spy.Poly(e, *U).total_degree()) for e in bal if e != 0) if bezout > cap: - raise ValueError(f"discrete() under equilibrate does not solve the balances of {', '.join(map(str, U))}: " - f"their Bezout number {bezout} in the states is past the cap rest_bezout of {cap}") + raise ValueError( + f"discrete() under equilibrate does not solve the balances of {', '.join(map(str, U))}: " + f"their Bezout number {bezout} in the states is past the cap rest_bezout of {cap}" + ) block = _largest_block(bal, U) cap = work.CAPS["rest_block"] if block > cap: - raise ValueError(f"discrete() under equilibrate does not solve the balances of {', '.join(map(str, U))}: " - f"their largest coupled block of {block} states is past the cap rest_block of {cap}") + raise ValueError( + f"discrete() under equilibrate does not solve the balances of {', '.join(map(str, U))}: " + f"their largest coupled block of {block} states is past the cap rest_block of {cap}" + ) sols = _solve_balances(bal, U) - sols = [s for s in sols if set(s) >= set(U) and not any(v.has(spy.I) or v.free_symbols & set(U) - for v in s.values())] + sols = [ + s for s in sols if set(s) >= set(U) and not any(v.has(spy.I) or v.free_symbols & set(U) for v in s.values()) + ] if sols: best = max(sum(s[x] != 0 for x in U) for s in sols) sols = [s for s in sols if sum(s[x] != 0 for x in U) == best] # an exponential of the coordinates is left to the rational form of the fiber (rationalize) - if len(sols) != 1 or not all(_rational(sols[0][x].replace(lambda a: isinstance(a, spy.exp) and _rational( - a.args[0]), lambda a: spy.Integer(2))) for x in U): - raise ValueError("discrete() under equilibrate needs a resting state with one rational closed form in the " - f"coordinates; the balances of {', '.join(map(str, U))} have {len(sols)} such solutions") + if len(sols) != 1 or not all( + _rational( + sols[0][x].replace(lambda a: isinstance(a, spy.exp) and _rational(a.args[0]), lambda a: spy.Integer(2)) + ) + for x in U + ): + raise ValueError( + "discrete() under equilibrate needs a resting state with one rational closed form in the " + f"coordinates; the balances of {', '.join(map(str, U))} have {len(sols)} such solutions" + ) out.update({str(x): str(spy.cancel(sols[0][x])) for x in U}) return out diff --git a/src/symident/detection/elim.py b/src/symident/detection/elim.py index 0fba91b..e4765eb 100644 --- a/src/symident/detection/elim.py +++ b/src/symident/detection/elim.py @@ -27,8 +27,13 @@ def __init__(self, rel, order): state_names = {str(rel.X[j]) for j in states} self.params = [n for n in rel.names if n not in state_names] self.order = order - self.names = list(self.params) + [f"si_x{j}" for j in self.unknown] + [f"si_d{j}" for j in self.unknown] + \ - [f"si_u{j}" for j in self.known] + [f"si_y{r}_{k}" for r in range(len(rel.y)) for k in range(order + 1)] + self.names = ( + list(self.params) + + [f"si_x{j}" for j in self.unknown] + + [f"si_d{j}" for j in self.unknown] + + [f"si_u{j}" for j in self.known] + + [f"si_y{r}_{k}" for r in range(len(rel.y)) for k in range(order + 1)] + ) self.at = {n: i for i, n in enumerate(self.names)} self.ctx = flint.fmpz_mpoly_ctx.get(tuple(self.names), "lex") self.gens = self.ctx.gens() @@ -258,8 +263,11 @@ def run(self): for r2, eq in self.y_eqs.items(): if r2 != r: nxt = self.eliminate(nxt, eq, R.at[f"si_y{r2}_{y_orders[r2]}"]) - cand = sorted((_deg(self.y_eqs[r], R.at[f"si_x{j}"]), _deg(nxt, R.at[f"si_x{j}"]), j) for j in self.x_eqs - if _deg(self.y_eqs[r], R.at[f"si_x{j}"]) > 0) + cand = sorted( + (_deg(self.y_eqs[r], R.at[f"si_x{j}"]), _deg(nxt, R.at[f"si_x{j}"]), j) + for j in self.x_eqs + if _deg(self.y_eqs[r], R.at[f"si_x{j}"]) > 0 + ) v = cand[0][2] vi = R.at[f"si_x{v}"] del self.x_eqs[v] @@ -323,8 +331,13 @@ def _resultant(f, g, v): if df > 1: n = dg cf += [zero] * (n + 1 - len(cf)) - M = [[sum((cf[j + k + 1] * cg[i - k] - cg[j + k + 1] * cf[i - k] for k in range(min(i, n - 1 - j) + 1)), zero) - for j in range(n)] for i in range(n)] + M = [ + [ + sum((cf[j + k + 1] * cg[i - k] - cg[j + k + 1] * cf[i - k] for k in range(min(i, n - 1 - j) + 1)), zero) + for j in range(n) + ] + for i in range(n) + ] else: n = df + dg M = [[zero] * n for _ in range(n)] @@ -362,6 +375,7 @@ def entry(row, power): k, c = row d = power - k return c[d] if 0 <= d < len(c) else zero + out = [] for last in (1, 0): powers = list(range(size, 1, -1)) + [last] @@ -393,6 +407,7 @@ def minor(row, cols): out = out if out is not None else one - one cache[key] = out return out + return minor(0, 0) @@ -432,7 +447,7 @@ def relation_projection(rel, R, P): for r in range(ny): if ms[r] >= 0: e += [m[off_known + len(R.known) + r * (R.order + 1) + k] for k in range(ms[r] + 1)] - known = dict(zip(R.known, m[off_known:off_known + len(R.known)])) + known = dict(zip(R.known, m[off_known : off_known + len(R.known)])) if any(k and j not in inputs for j, k in known.items()): return None e += [known.get(j, 0) for j in inputs] @@ -446,8 +461,9 @@ def normalized(coefs): """The index of the reference coefficient, a monomial if one is, else one of fewest terms, and the order of the others by terms and degree.""" ref = min(range(len(coefs)), key=lambda j: (len(coefs[j]), max(sum(m) for m in coefs[j]), j)) - order = sorted((j for j in range(len(coefs)) if j != ref), - key=lambda j: (len(coefs[j]), max(sum(m) for m in coefs[j]), j)) + order = sorted( + (j for j in range(len(coefs)) if j != ref), key=lambda j: (len(coefs[j]), max(sum(m) for m in coefs[j]), j) + ) return ref, order @@ -477,6 +493,7 @@ def grad(co): d[tuple(mm)] = d.get(tuple(mm), 0) + c * m[v] out.append(val(d, theta) if d else 0) return out + r0, dr = val(coefs[ref], theta), grad(coefs[ref]) if not r0: return [], [] @@ -499,7 +516,7 @@ def grad(co): first.append(j) else: rest.append(j) - return first, first + rest[:len(first)] + return first, first + rest[: len(first)] def eliminate_relations(rel, rng, terms=math.inf): diff --git a/src/symident/detection/fewcoef.py b/src/symident/detection/fewcoef.py index da54643..2f6e027 100644 --- a/src/symident/detection/fewcoef.py +++ b/src/symident/detection/fewcoef.py @@ -286,7 +286,7 @@ def _rank_select(found, order, n, q, rng): basis.append([x * inv % q for x in row]) piv.append(c) first.append(e) - return first, first + [e for e in order if e not in first][:len(first)] + return first, first + [e for e in order if e not in first][: len(first)] class _Bounds: @@ -314,11 +314,14 @@ def height(P): t = [{k: sum(m[v] * dict(funcs[v].exps).get(k, 0) for v in range(len(funcs))) for k in used} for m in pr.mons] T = {k: max(tj[k] for tj in t) for k in used} self.r = len(pr.mons) - self.degree = sum(sum(m[v] * dN[v] for v in range(len(funcs))) + sum((T[k] - tj[k]) * dF[k] for k in used) - for m, tj in zip(pr.mons, t)) - self.height = math.lgamma(self.r + 1) / math.log(2) + \ - sum(sum(m[v] * hN[v] for v in range(len(funcs))) + sum((T[k] - tj[k]) * hF[k] for k in used) - for m, tj in zip(pr.mons, t)) + self.degree = sum( + sum(m[v] * dN[v] for v in range(len(funcs))) + sum((T[k] - tj[k]) * dF[k] for k in used) + for m, tj in zip(pr.mons, t) + ) + self.height = math.lgamma(self.r + 1) / math.log(2) + sum( + sum(m[v] * hN[v] for v in range(len(funcs))) + sum((T[k] - tj[k]) * hF[k] for k in used) + for m, tj in zip(pr.mons, t) + ) self.rows_degree = sum(dF.values()) def trial(self, extra_degree=0, extra_height=0.0, hi=None): @@ -338,6 +341,7 @@ def verified_functions(series, syms, large, cap, rng, log): the matrices reduced. `exist` bounds the probability that no relation exists on the support, `checks` per function that it differs from the coefficient of the relation; both are those of _TRIALS independent trials.""" from . import fieldproof + end = work.ticks() + cap out = {"functions": [], "exist": None, "checks": {}, "why": None, "kernels": 0, "terms": None} rel = fieldproof._relations(series, syms) @@ -382,14 +386,19 @@ def stop(why): # the rank of the coefficients found on the axis lines: the rank the functions verified aim at target = rref_modp(np.array(list(grads.values()), dtype=np.int64).reshape(-1, n), p)["rank"] # the simplest entries first: the fewest exponent vectors in the ranges - order = sorted((e for e, rg in ranges.items() if e != r0 and any(L or H for L, H in rg) and - math.prod(H - L + 1 for L, H in rg) <= _BOX), - key=lambda e: (math.prod(H - L + 1 for L, H in ranges[e]), sum(H - L for L, H in ranges[e]), e)) + order = sorted( + ( + e + for e, rg in ranges.items() + if e != r0 and any(L or H for L, H in rg) and math.prod(H - L + 1 for L, H in rg) <= _BOX + ), + key=lambda e: (math.prod(H - L + 1 for L, H in ranges[e]), sum(H - L for L, H in ranges[e]), e), + ) # Ben-Or and Tiwari modulo two primes, a third where the rational coefficients need it bts = {q: _BT(orc, n, q, rng) for q in all_primes()[:2]} found, tried, first, need = {}, 0, [], 8 while len(first) < target: - batch = order[tried:tried + _CANDIDATES * n] + batch = order[tried : tried + _CANDIDATES * n] if not batch: return stop(f"the coefficients found raise the rank to {len(first)} of {target}") tried += len(batch) @@ -433,8 +442,13 @@ def stop(why): out["exist"] = bounds.trial(hi=hi) ** _TRIALS for e in pins: co = found[e] - expr = sum((spy.Rational(c.numerator, c.denominator) * spy.prod([s ** k for s, k in zip(params, m)]) - for m, c in co.items()), spy.Integer(0)) + expr = sum( + ( + spy.Rational(c.numerator, c.denominator) * spy.prod([s**k for s, k in zip(params, m)]) + for m, c in co.items() + ), + spy.Integer(0), + ) # w = N / (L theta^a) with N a polynomial: the degree and height that the check adds to a minor L = math.lcm(*[c.denominator for c in co.values()]) a = [max(0, -min(m[v] for m in co)) for v in range(n)] @@ -443,7 +457,12 @@ def stop(why): text = str(spy.cancel(expr)) out["functions"].append(text) out["checks"][text] = bounds.trial(extra_d, extra_h, hi) ** _TRIALS - out.update(kernels=orc.calls + _TRIALS, reference=str(pr.mons[r0]), degree=bounds.degree, - height=round(bounds.height), trials=_TRIALS) + out.update( + kernels=orc.calls + _TRIALS, + reference=str(pr.mons[r0]), + degree=bounds.degree, + height=round(bounds.height), + trials=_TRIALS, + ) log.append(f"projection of {r} terms: {len(pins)} coefficients verified with {out['kernels']} kernels") return out diff --git a/src/symident/detection/fiber.py b/src/symident/detection/fiber.py index fc6b5d4..8947d62 100644 --- a/src/symident/detection/fiber.py +++ b/src/symident/detection/fiber.py @@ -35,6 +35,7 @@ def _msolve_degree(eqs, names, p): from ..sym.msolve import _msolve_binary from . import work + if work.msolve_too_large(names, eqs): return None with tempfile.TemporaryDirectory() as td: diff --git a/src/symident/detection/fieldproof.py b/src/symident/detection/fieldproof.py index 8c43d7f..a5f0d50 100644 --- a/src/symident/detection/fieldproof.py +++ b/src/symident/detection/fieldproof.py @@ -41,8 +41,8 @@ _GROUP = 8 # the _Var of each target function, and the _Relations of each series, built once -_TARGETS = {} -_REL = {} +_TARGETS: dict = {} +_REL: dict = {} class _Factored: @@ -225,6 +225,7 @@ def split(P): for m, c in P.items(): out.setdefault(tuple(m[:ns]), []).append((m[ns:], c)) return {k: ar.coef(v) for k, v in out.items()} + polys = [split(P) for N, D in seg["F"] for P in (N, D)] + [split(P) for M, E in seg["G"] for P in (M, E)] mons, at, parent = [(0,) * ns], {(0,) * ns: 0}, [None] @@ -232,11 +233,12 @@ def add(m): if m in at: return v = next(i for i, e in enumerate(m) if e) - low = m[:v] + (m[v] - 1,) + m[v + 1:] + low = m[:v] + (m[v] - 1,) + m[v + 1 :] add(low) at[m] = len(mons) mons.append(m) parent.append((at[low], v)) + for P in polys: for m in P: add(m) @@ -397,11 +399,14 @@ def images(a): def distinct(ims): return all(spy.cancel(a - b) != 0 for a, b in itertools.combinations(ims, 2)) + # the simplest alpha: one coordinate, else a combination of two or three with the simplest images order = sorted(moved, key=lambda s: sum(spy.count_ops(v) for v in imgs[s])) - cands = list(order) + \ - [a + t * b for a, b in itertools.combinations(order, 2) for t in (2, 3)] + \ - [a + 2 * b + 5 * c for a, b, c in itertools.combinations(order, 3)] + cands = ( + list(order) + + [a + t * b for a, b in itertools.combinations(order, 2) for t in (2, 3)] + + [a + 2 * b + 5 * c for a, b, c in itertools.combinations(order, 3)] + ) alpha = next((a for a in cands if distinct(imgs[a] if a in imgs else images(a))), None) if alpha is None: return None @@ -415,6 +420,7 @@ def distinct(ims): def over_q(f): e = spy.cancel(spy.expand(f.as_expr())) if gauss else None return f if not gauss else None if e.has(spy.I) else K.from_expr(e) + P = [Kg.one] for a in (Kg.from_expr(a) for a in aims): P = [(P[j - 1] if j else Kg.zero) - (a * P[j] if j < len(P) else Kg.zero) for j in range(len(P) + 1)] @@ -426,8 +432,11 @@ def over_q(f): traces = [t for t in traces if t is not None] F = [K.from_expr(x) for x in fixed] + P[:-1] F = [f for n_, f in enumerate(F) if not (f.numer.is_ground and f.denom.is_ground) and f not in F[:n_]] - traces = [t for n_, t in enumerate(traces) if not (t.numer.is_ground and t.denom.is_ground) and - t not in F and t not in traces[:n_]] + traces = [ + t + for n_, t in enumerate(traces) + if not (t.numer.is_ground and t.denom.is_ground) and t not in F and t not in traces[:n_] + ] return alpha, [f.as_expr() for f in F], [t.as_expr() for t in traces], [s for s in moved if s != alpha] @@ -442,7 +451,7 @@ def _parents(mons): out = [None] for m in mons[1:]: v = next(i for i, e in enumerate(m) if e) - out.append((at[m[:v] + (m[v] - 1,) + m[v + 1:]], v)) + out.append((at[m[:v] + (m[v] - 1,) + m[v + 1 :]], v)) return out @@ -506,8 +515,11 @@ def _large_value(self, x, p): """(numerator, denominator) at x modulo p in C++, both at once.""" if not hasattr(self, "_arr"): terms = self.tn + self.td - self._arr = (np.array([m for m, _, _ in terms], dtype=np.int32).reshape(len(terms), -1), - [(a, b) for _, a, b in terms], np.array([0, len(self.tn), len(terms)], dtype=np.int64)) + self._arr = ( + np.array([m for m, _, _ in terms], dtype=np.int32).reshape(len(terms), -1), + [(a, b) for _, a, b in terms], + np.array([0, len(self.tn), len(terms)], dtype=np.int64), + ) E, co, off = self._arr res = self.__dict__.setdefault("_res", {}) if p not in res: @@ -516,7 +528,6 @@ def _large_value(self, x, p): return int(nv), int(dv) - def _find(f, W, syms, outs, pool, d, stop, mons=None): """(A, B) as text with f = A(W)/B(W) of total degree d, or on the monomials `mons` (lowest degree first), proven by _check; None where none is found.""" @@ -538,8 +549,7 @@ def _find(f, W, syms, outs, pool, d, stop, mons=None): if work.ticks() > stop or not vals: return None # the monomials at every point in C++, then times -f for the columns of B - M = _core.io_mono_matrix(np.array(vals, dtype=np.int64).reshape(len(vals), len(W)), E, p, - ioproj._threads()) + M = _core.io_mono_matrix(np.array(vals, dtype=np.int64).reshape(len(vals), len(W)), E, p, ioproj._threads()) test.setdefault(p, [int(t) for t in M[0]]) rows = np.hstack([M, M * ((-np.array(fvs, dtype=np.int64)) % p)[:, None] % p]) work.tick(rows.shape) @@ -589,6 +599,7 @@ def _check(vec, mons, W, target, syms, outs): def ring(e): return R.from_expr(spy.sympify(e).xreplace(tsym)) + fr = {i: cs[W[i].c] if W[i].c is not None else F.quo(ring(W[i].num), ring(W[i].den)) for i in used} pw = {} @@ -608,6 +619,7 @@ def value(coefs): t = F.mul(t, power(i, m[i])) out.append(t) return F.total(out) + B = value(vec[n:]) if not B[0]: return None @@ -618,8 +630,15 @@ def value(coefs): names = [W[i].name for i in range(len(W))] def text(coefs): - return " + ".join(f"({q})" + "".join(f"*{nm}" + (f"^{e}" if e > 1 else "") for nm, e in zip(names, m) if e) - for m, q in zip(mons, coefs) if q) or "0" + return ( + " + ".join( + f"({q})" + "".join(f"*{nm}" + (f"^{e}" if e > 1 else "") for nm, e in zip(names, m) if e) + for m, q in zip(mons, coefs) + if q + ) + or "0" + ) + return text(vec[:n]), text(vec[n:]) @@ -652,6 +671,7 @@ def __init__(self, series, syms): def reads(j): N, D = seg["F"][j] return {i for P in (N, D) for m in P for i in range(ns) if m[i]} + # the known states (inputs and their jets, the clock) within _CHAIN steps of the others: a relation of # order m reads the jets of an input up to m, and the long chains would make the field too large keep = {j for j in range(ns) if j not in known} @@ -669,14 +689,15 @@ def reads(j): extra = [str(c) for c in syms if str(c) not in names] # rational right-hand sides and observables: the field of the states and coordinates; the polynomial ring # where every denominator is a number, whose arithmetic needs no gcd - polynomial = all(all(not any(m) for m in D) for _, D in seg["F"]) and \ - all(all(not any(m) for m in E) for _, E in seg["G"]) + polynomial = all(all(not any(m) for m in D) for _, D in seg["F"]) and all( + all(not any(m) for m in E) for _, E in seg["G"] + ) self.R, *gens = (spy.ring if polynomial else spy.field)(",".join(names + extra), spy.QQ) self.names = names + extra X = [None] * ns for j, g in zip(kept, gens): X[j] = g - P = gens[len(kept):len(kept) + len(params)] + P = gens[len(kept) : len(kept) + len(params)] def poly(Pd): out = self.R.zero @@ -684,7 +705,7 @@ def poly(Pd): t = self.R(spy.Rational(c.numerator, c.denominator)) for g, e in zip(X + list(P), m): if e: - t = t * g ** e + t = t * g**e out = out + t return out @@ -693,6 +714,7 @@ def quo(N, D): (c,) = D.values() return poly(N) * self.R(spy.Rational(1) / spy.Rational(c.numerator, c.denominator)) return poly(N) / poly(D) + # the last jets kept stay constant: the relations tried read fewer derivatives than the chain holds self.f = [None if j not in keep else self.R.zero if j in cut else quo(*seg["F"][j]) for j in range(ns)] self.cut = cut @@ -726,7 +748,7 @@ def jets(self, ms): d = self._lie[r] while len(d) <= m: d.append(self.lie(d[-1])) - ys.append(d[:m + 1]) + ys.append(d[: m + 1]) return ys def inputs(self, m): @@ -757,8 +779,9 @@ def _relation_matrix(rel, x, p, ms, degree, K): if S is None: return None mons = _monomials(S.shape[0], degree) - ser = _core.io_series_monomials(S, np.array(mons, dtype=np.int32).reshape(len(mons), S.shape[0]), p, - ioproj._threads()) + ser = _core.io_series_monomials( + S, np.array(mons, dtype=np.int32).reshape(len(mons), S.shape[0]), p, ioproj._threads() + ) return ser.T.tolist(), mons @@ -819,13 +842,16 @@ def _polys_at_once(S, entries, scale, primes, stop, degrees=range(0, 12), box=No rows = [] for x, v in pts: sc = scale(x, p) if scale else 1 - mv = _mono_values(x, par, p) if par is not None else \ - [math.prod((pow(xi, k, p) for xi, k in zip(x, m) if k), start=1) % p for m in mons] + mv = ( + _mono_values(x, par, p) + if par is not None + else [math.prod((pow(xi, k, p) for xi, k in zip(x, m) if k), start=1) % p for m in mons] + ) rows.append(mv + [v[e] * sc % p for e in todo]) rows = np.array(rows, dtype=np.int64) work.tick(rows.shape) rr = rref_modp(rows, p) - piv = [int(c) for c in rr["piv"][:rr["rank"]]] + piv = [int(c) for c in rr["piv"][: rr["rank"]]] if piv[:U] != list(range(U)): break for k, e in enumerate(todo): @@ -862,8 +888,10 @@ def _line_degrees(S, width, p, stop, top=24): for tot in range(0, top + 1): for dd in range(0, tot + 1): dn = tot - dd - rows = [[pow(t, i, p) for i in range(dn + 1)] + [(-v[e] * pow(t, i, p)) % p for i in range(dd + 1)] - for t, v in pts] + rows = [ + [pow(t, i, p) for i in range(dn + 1)] + [(-v[e] * pow(t, i, p)) % p for i in range(dd + 1)] + for t, v in pts + ] if _kernel_canonical(rows, p)[2]: got = (dn, dd) break @@ -916,8 +944,9 @@ def _rational_one(S, e, dn, dd, primes, stop): pts = S.get(p, U + 8, stop) if pts is None: return None - rows = [[v[e] * t % p for t in _mono_values(x, pd, p)] + [(-t) % p for t in _mono_values(x, pn, p)] - for x, v in pts] + rows = [ + [v[e] * t % p for t in _mono_values(x, pd, p)] + [(-t) % p for t in _mono_values(x, pn, p)] for x, v in pts + ] piv, free, basis = _kernel_canonical(rows, p) if len(basis) != 1: return None @@ -927,7 +956,7 @@ def _rational_one(S, e, dn, dd, primes, stop): coef = [_crt_rational({p: vecs[p][2][i] for p in primes}) for i in range(U)] if any(c_ is None for c_ in coef): return None - return (mn, coef[len(md):]), (md, coef[:len(md)]) + return (mn, coef[len(md) :]), (md, coef[: len(md)]) def _interpolate(values, n, rng, stop): @@ -944,8 +973,7 @@ def _interpolate(values, n, rng, stop): if degs is None or any(g is None for g in degs): return None zero = [Fraction(0)] - out = {e: ([(0,) * n], zero, [Fraction(1)]) for e, g in enumerate(degs) if g == (0, 0) and - not first[0][1][e]} + out = {e: ([(0,) * n], zero, [Fraction(1)]) for e, g in enumerate(degs) if g == (0, 0) and not first[0][1][e]} polys = [e for e, g in enumerate(degs) if e not in out and g[1] == 0] if polys: top = max(degs[e][0] for e in polys) @@ -969,6 +997,7 @@ def _interpolate(values, n, rng, stop): def scale(x, p): return _eval_terms(dterms, x, p) + top = max(degs[e][0] - degs[e][1] for e in rest) + degs[e0][1] nums = _polys_at_once(S, rest, scale, primes, stop, range(max(0, top), top + 3)) if len(nums) < len(rest): @@ -985,8 +1014,9 @@ def scale(x, p): def _base(rel, ms): """The derivatives of the observables, up to ms[r] for observable r, and the input states, as ioproj.Quo.""" J = ioproj.jets_of(rel) - return [q for r, m in enumerate(ms) if m >= 0 for q in J.observable(r, m)] + \ - [J.state(i) for i in rel.inputs(max(ms))] + return [q for r, m in enumerate(ms) if m >= 0 for q in J.observable(r, m)] + [ + J.state(i) for i in rel.inputs(max(ms)) + ] def _configs(ny, ni, cap, floor=0): @@ -997,8 +1027,9 @@ def _configs(ny, ni, cap, floor=0): if ny <= 3: vectors = itertools.product(range(-1, 6), repeat=ny) else: - vectors = [tuple(m if r == q else -1 for r in range(ny)) for q in range(ny) for m in range(6)] + \ - [(m,) * ny for m in range(6)] + vectors = [tuple(m if r == q else -1 for r in range(ny)) for q in range(ny) for m in range(6)] + [ + (m,) * ny for m in range(6) + ] for ms in vectors: if max(ms) < 0: continue @@ -1038,10 +1069,22 @@ def _rebuild(inter, tsy): """The interpolated entries as expressions in the symbols `tsy`, None where a denominator is zero.""" out = [] for mons_, nn, dd in inter: - N = sum((spy.Rational(q.numerator, q.denominator) * spy.prod([s_ ** e for s_, e in zip(tsy, mm)]) - for mm, q in zip(mons_, nn) if q), spy.Integer(0)) - Dn = sum((spy.Rational(q.numerator, q.denominator) * spy.prod([s_ ** e for s_, e in zip(tsy, mm)]) - for mm, q in zip(mons_, dd) if q), spy.Integer(0)) + N = sum( + ( + spy.Rational(q.numerator, q.denominator) * spy.prod([s_**e for s_, e in zip(tsy, mm)]) + for mm, q in zip(mons_, nn) + if q + ), + spy.Integer(0), + ) + Dn = sum( + ( + spy.Rational(q.numerator, q.denominator) * spy.prod([s_**e for s_, e in zip(tsy, mm)]) + for mm, q in zip(mons_, dd) + if q + ), + spy.Integer(0), + ) if Dn == 0: return None out.append(spy.cancel(N / Dn)) @@ -1072,7 +1115,7 @@ def _phis(rel, ms, degree, extra=()): J = ioproj.jets_of(rel) base = _base(rel, ms) phis = ioproj.products(J, base, _monomials(len(base), degree)) - low = phis[:math.comb(len(base) + degree - 1, degree - 1)] + low = phis[: math.comb(len(base) + degree - 1, degree - 1)] return phis + [ioproj.Quo(q.numer * J.X[e], q.exps) for e in extra for q in low] @@ -1117,8 +1160,9 @@ def state_relation(series, syms, coord, rng, stop, cap=None): nmon = len(jets[1]) nlow = math.comb(len(_base(rel, ms)) + degree - 1, degree - 1) ext = (xi, nlow) - piv, free, basis = _kernel_at(rel, jets, [rng.randrange(1, p0) for _ in idx], p0, pos, rng, - nmon + nlow + 7, ext) + piv, free, basis = _kernel_at( + rel, jets, [rng.randrange(1, p0) for _ in idx], p0, pos, rng, nmon + nlow + 7, ext + ) # a free column x_i psi_k: the basis vector of that column has the state at a nonzero coefficient cols = [c for c in free if c >= nmon] if not cols: @@ -1130,6 +1174,7 @@ def values(xp, p, piv=piv, free=free, jets=jets, col=col, ext=ext, nmon=nmon, nl if (pv, fr) != (piv, free): return None return [b[col][j] for j in piv] + inter = _interpolate(values, len(idx), rng, stop) if inter is None: continue @@ -1142,17 +1187,25 @@ def values(xp, p, piv=piv, free=free, jets=jets, col=col, ext=ext, nmon=nmon, nl phis = _phis(rel, ms, degree, [i]) # the denominator sum_k mu_k psi_k of x_i is not zero, over the common denominators mu = _ring_coeffs(rel, syms, {j: v for j, v in lam.items() if j >= nmon}) - den, T = ioproj.combine(J, list(mu.values()), [ioproj.Quo(phis[j].numer.exquo(J.X[i]), phis[j].exps) - for j in mu]) + den, T = ioproj.combine( + J, list(mu.values()), [ioproj.Quo(phis[j].numer.exquo(J.X[i]), phis[j].exps) for j in mu] + ) if den == 0 or not _identity(rel, syms, lam, phis): continue # and not zero at the start of the trajectory, with the factors of the denominator - start = {spy.Symbol(str(x)): (v[0] if v[0] is not None else spy.Symbol(str(x))) - for x, v in zip(rel.X, seg["x0"]) if x is not None} + start = { + spy.Symbol(str(x)): (v[0] if v[0] is not None else spy.Symbol(str(x))) + for x, v in zip(rel.X, seg["x0"]) + if x is not None + } if any(spy.cancel(P.as_expr().xreplace(start)) == 0 for P in [den] + [J.fac[k] for k in T]): continue - return {"reads": set().union(*[v.free_symbols for v in lam.values()]), "orders": ms, "degree": degree, - "state": i} + return { + "reads": set().union(*[v.free_symbols for v in lam.values()]), + "orders": ms, + "degree": degree, + "state": i, + } return None @@ -1194,6 +1247,7 @@ def values(xp, p, piv=piv, free=free, jets=jets, nmon=nmon): if (pv, fr) != (piv, free): return None return [v[j] for v in b for j in piv] + inter = _interpolate(values, len(idx), rng, stop) if inter is None: log.append(f"relations at orders {ms}, degree {degree}: not interpolated") @@ -1299,6 +1353,7 @@ def projection_functions(series, syms, rng, stop, log, found=None): def _elim_child(): """elim.eliminate_relations() on the pickled input of stdin, the relations pickled to stdout as dictionaries.""" from . import elim + series, syms, seed, terms = pickle.loads(sys.stdin.buffer.read()) rel = _relations(series, syms) try: @@ -1306,10 +1361,19 @@ def _elim_child(): except ValueError as exc: sys.stdout.buffer.write(pickle.dumps({"why": str(exc)})) return - sys.stdout.buffer.write(pickle.dumps({"order": got["ring"].order, "orders": got["orders"], "steps": got["steps"], - "relations": {r: P.to_dict() for r, P in got["relations"].items()}, - "states": {j: None if ab is None else tuple(P.to_dict() for P in ab) - for j, ab in got["states"].items()}})) + sys.stdout.buffer.write( + pickle.dumps( + { + "order": got["ring"].order, + "orders": got["orders"], + "steps": got["steps"], + "relations": {r: P.to_dict() for r, P in got["relations"].items()}, + "states": { + j: None if ab is None else tuple(P.to_dict() for P in ab) for j, ab in got["states"].items() + }, + } + ) + ) def elimination_functions(series, syms, rng, stop, log, found=None): @@ -1333,8 +1397,10 @@ def elimination_functions(series, syms, rng, stop, log, found=None): return payload = pickle.dumps((series, list(syms), rng.getrandbits(64), work.CAPS["elimination_terms"])) try: - r = work.run([sys.executable, "-c", "from symident.detection.fieldproof import _elim_child; _elim_child()"], - input=payload) + r = work.run( + [sys.executable, "-c", "from symident.detection.fieldproof import _elim_child; _elim_child()"], + input=payload, + ) got = pickle.loads(r.stdout) if r.returncode == 0 and r.stdout else None except (pickle.UnpicklingError, EOFError): got = None @@ -1347,8 +1413,8 @@ def elimination_functions(series, syms, rng, stop, log, found=None): gens = [spy.Symbol(n) for n in R.params] def expr(co): - return sum((spy.Integer(c) * spy.prod([g ** k for g, k in zip(gens, m)]) for m, c in co.items()), - spy.Integer(0)) + return sum((spy.Integer(c) * spy.prod([g**k for g, k in zip(gens, m)]) for m, c in co.items()), spy.Integer(0)) + for obs, d in got["relations"].items(): P = R.ctx.from_dict(d) built = elim.relation_projection(rel, R, P) @@ -1366,8 +1432,10 @@ def expr(co): den = expr(coefs[ref]) exprs = [spy.cancel(expr(coefs[j]) / den) for j in pins] rel.__dict__.setdefault("_eliminated", set()).add(obs) - log.append(f"{where}: relation of {len(support)} terms ({len(P)} with the coordinates), rank {rk} along " - f"the trajectory, {len(pins)} coefficients proven") + log.append( + f"{where}: relation of {len(support)} terms ({len(P)} with the coordinates), rank {rk} along " + f"the trajectory, {len(pins)} coefficients proven" + ) yield _new(exprs, found) @@ -1422,8 +1490,7 @@ def state_projection(series, syms, coord, rng, stop): # the projection, where the start is algebraic of higher degree over those below; small supports first, # since a search without a relation runs up to the cap lifts = ((r, d) for r in range(len(h)) for d in [_top_degree(rel, h, r, pos, rng, stop)] if d and d > 1) - tries = itertools.chain([(None, ioproj.CAP // 4)], ((lift, ioproj.CAP) for lift in lifts), - [(None, ioproj.CAP)]) + tries = itertools.chain([(None, ioproj.CAP // 4)], ((lift, ioproj.CAP) for lift in lifts), [(None, ioproj.CAP)]) for lift, cap in tries: if work.ticks() > stop: return None @@ -1538,11 +1605,26 @@ def exact_fiber(series, orders, grp, syms, inputs=(), known=(), pre=()): return out seed = session.current().rng("exact fiber", tuple(series.coords)).getrandbits(64) from ..sym import msolve - payload = pickle.dumps((series, list(orders), grp, list(syms), list(inputs), seed, list(known), - list(pre), msolve._MSOLVE_THREADS, work.MSOLVE_MEMORY, dict(work.CAPS))) + + payload = pickle.dumps( + ( + series, + list(orders), + grp, + list(syms), + list(inputs), + seed, + list(known), + list(pre), + msolve._MSOLVE_THREADS, + work.MSOLVE_MEMORY, + dict(work.CAPS), + ) + ) try: - r = work.run([sys.executable, "-c", "from symident.detection.fieldproof import _child; _child()"], - input=payload) + r = work.run( + [sys.executable, "-c", "from symident.detection.fieldproof import _child; _child()"], input=payload + ) got = pickle.loads(r.stdout) if r.returncode == 0 and r.stdout else None except (pickle.UnpicklingError, EOFError): got = None @@ -1556,8 +1638,7 @@ def exact_fiber(series, orders, grp, syms, inputs=(), known=(), pre=()): def _child(): """The search of exact_fiber() on the pickled input of stdin, the result pickled to stdout.""" - series, orders, grp, syms, inputs, seed, known, pre, threads, memory, caps = \ - pickle.loads(sys.stdin.buffer.read()) + series, orders, grp, syms, inputs, seed, known, pre, threads, memory, caps = pickle.loads(sys.stdin.buffer.read()) ioproj.THREADS[0] = threads work.MSOLVE_MEMORY = memory work.CAPS.update(caps) @@ -1580,8 +1661,11 @@ def large_projections(series, syms): return [] rel = _REL[key][1] done = rel.__dict__.get("_eliminated", set()) - return [{"profile": list(h), "observable": i, "support": [tuple(int(x) for x in m) for m in S]} - for (h, i), S in _supports(rel).items() if S and len(S) > ioproj.TERMS and i not in done] + return [ + {"profile": list(h), "observable": i, "support": [tuple(int(x) for x in m) for m in S]} + for (h, i), S in _supports(rel).items() + if S and len(S) > ioproj.TERMS and i not in done + ] def _search(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): @@ -1602,8 +1686,7 @@ def _search(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): pool = _Pool(outs, len(syms), rng) a, b = pool.get(all_primes()[0], 2) # the coefficients that are numbers add nothing to the field - W = [_Var(f"c{j}", c=j) for j in sorted(range(len(a[1])), key=lambda j: outs.index[j][1]) - if a[1][j] != b[1][j]] + W = [_Var(f"c{j}", c=j) for j in sorted(range(len(a[1])), key=lambda j: outs.index[j][1]) if a[1][j] != b[1][j]] # the known constants of the model: in the base field Q(kappa), with the output coefficients kappa = {spy.Symbol(k) for k in known} W += [_Var(str(k), expr=k, syms=syms) for k in sorted(kappa, key=str)] @@ -1619,11 +1702,13 @@ def _search(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): def relations(end): # the small dense configurations, the projections, the relations by elimination, the large dense # configurations - return itertools.chain(io_functions(series, syms, rng, min(end, work.ticks() + _DENSE * cap), log, - cap=_FIRST, found=found), - projection_functions(series, syms, rng, end, log, found), - elimination_functions(series, syms, rng, end, log, found), - io_functions(series, syms, rng, end, log, floor=_FIRST, found=found)) + return itertools.chain( + io_functions(series, syms, rng, min(end, work.ticks() + _DENSE * cap), log, cap=_FIRST, found=found), + projection_functions(series, syms, rng, end, log, found), + elimination_functions(series, syms, rng, end, log, found), + io_functions(series, syms, rng, end, log, floor=_FIRST, found=found), + ) + io = relations(t0 + _SHARE * cap) tried = set() scaled = {} @@ -1668,8 +1753,9 @@ def subsystems(f): def products(nv, nP, cap): # monomials of degree dv in the functions times degree dp in the proven coordinates, fewest first - pairs = sorted((2 * math.comb(nv + dv, dv) * math.comb(nP + dp, dp), dv, dp) - for dv in range(1, 4) for dp in range(0, 9)) + pairs = sorted( + (2 * math.comb(nv + dv, dv) * math.comb(nP + dp, dp), dv, dp) for dv in range(1, 4) for dp in range(0, 9) + ) for U, dv, dp in pairs: if U > cap: break @@ -1701,8 +1787,9 @@ def prove(f, coefficients, cap=_UNKNOWNS): w, m = scaled[id(v)] W.append(v) out["proven"].append(str(v.expr)) - out["generators"].append({"function": str(v.expr), "numerator": f"(1)*{w.name}", - "denominator": str(m)}) + out["generators"].append( + {"function": str(v.expr), "numerator": f"(1)*{w.name}", "denominator": str(m)} + ) return got sets = [near, [w for w in W if w.c is None]] + low + ([W] if coefficients and cap == _UNKNOWNS else []) for V in sets: @@ -1738,6 +1825,7 @@ def step(coefficients, cap=_UNKNOWNS): pending.remove(done[0]) add(*done) return done is not None + states = {} io_restart = [False] starts = {v[0] for part in series.parts for v in part["segs"][0].get("x0", []) if v[0] is not None} @@ -1772,6 +1860,7 @@ def from_state(size): io_restart[0] = True return True return False + while pending and work.ticks() < stop: # small searches in the output coefficients before the next relations, the large ones after them if step(False) or from_state(_SMALL) or step(True, 300): @@ -1794,8 +1883,10 @@ def from_state(size): # without input-output relations only the search in the output coefficients remains if work.ticks() + _WITHOUT_RELATIONS * cap < stop: stop = work.ticks() + _WITHOUT_RELATIONS * cap - ended[0] = (f"without input-output relations the search ends {int(_WITHOUT_RELATIONS * cap):,} " - "entries of the matrices reduced later") + ended[0] = ( + f"without input-output relations the search ends {int(_WITHOUT_RELATIONS * cap):,} " + "entries of the matrices reduced later" + ) if step(True): continue for h in extra: @@ -1815,8 +1906,9 @@ def from_state(size): add(t, got) if pending: out["entries"] = work.ticks() - t0 - out["why"] = (f"{pending[0]} was not found as a rational function of the output coefficients" + - (f" before the end of the search: {ended[0]}" if work.ticks() >= stop else "")) + out["why"] = f"{pending[0]} was not found as a rational function of the output coefficients" + ( + f" before the end of the search: {ended[0]}" if work.ticks() >= stop else "" + ) return out # the other coordinates in F(alpha): alpha joins the proven functions as a variable of these searches only if others: @@ -1843,21 +1935,22 @@ def in_f_alpha(th): if got is not None: return got return None + proven_syms = set() for th in sorted(others, key=lambda e: sum(spy.count_ops(g.get(e, e)) for g in grp)): got = in_f_alpha(th) if got is None: # the start of a state: x_i(0) from a relation whose coefficients read coordinates in F(alpha) - sr = state_relation(series, syms, th, rng, stop) or \ - state_projection(series, syms, th, rng, stop) + sr = state_relation(series, syms, th, rng, stop) or state_projection(series, syms, th, rng, stop) inF = {w.expr for w in W if w.c is None and w.expr.is_Symbol} | proven_syms if sr is not None and sr["reads"] <= inF: got = ("state relation", f"coefficients in {sorted(map(str, sr['reads']))}") # more of F: the trace of th, then the next relations while got is None and work.ticks() < stop: tr = sum((spy.sympify(g.get(th, th)) for g in grp), spy.Integer(0)) - gt = prove(tr, True) if not any(w.expr is not None and spy.cancel(w.expr - tr) == 0 - for w in W) else None + gt = ( + prove(tr, True) if not any(w.expr is not None and spy.cancel(w.expr - tr) == 0 for w in W) else None + ) if gt is not None: add(tr, gt) else: @@ -1870,8 +1963,9 @@ def in_f_alpha(th): out["entries"] = work.ticks() - t0 out["why"] = f"{th} was not found as a rational function of the proven functions and {alpha}" return out - out["generators"].append({"function": str(th), "numerator": got[0], "denominator": got[1], - "over": f"F({alpha})"}) + out["generators"].append( + {"function": str(th), "numerator": got[0], "denominator": got[1], "over": f"F({alpha})"} + ) Fa.append(_Var(f"a{len(Fa)}", expr=th, syms=syms)) proven_syms.add(th) out["alpha"] = str(alpha) diff --git a/src/symident/detection/fields.py b/src/symident/detection/fields.py index 4b41304..e2a40b5 100644 --- a/src/symident/detection/fields.py +++ b/src/symident/detection/fields.py @@ -41,10 +41,10 @@ def series_embed(S, N, col_map, nz_out, p, scale=None): S = np.asarray(S, dtype=np.int64) out = np.zeros((S.shape[0], nz_out * N), dtype=np.int64) for c, cm in enumerate(col_map): - v = S[:, c * N:(c + 1) * N] + v = S[:, c * N : (c + 1) * N] if scale is not None: v = mulmod(v, scale[c], p) - out[:, cm * N:(cm + 1) * N] = v + out[:, cm * N : (cm + 1) * N] = v return out @@ -85,8 +85,7 @@ def series_const(M, N): def series_stack(res, sblocks, nz, N, p, cores=1): """Series rank of the stacked series blocks attached to a reduced kernel result.""" S = np.vstack(sblocks).astype(np.int64) - sr = _core.sym_series_rank(S, int(nz), int(N), p, [], at_one_below=int(res["rank"]), - cores=int(cores)) + sr = _core.sym_series_rank(S, int(nz), int(N), p, [], at_one_below=int(res["rank"]), cores=int(cores)) res = dict(res) res["rank_s"] = sr["rank"] res["S"] = sr["S"] @@ -111,8 +110,7 @@ def rank_score(r): def lie_reach_max(tapes): """The largest first Lie order at which a coordinate enters some tape; 0 when the tapes do not tell.""" - R = [np.atleast_1d(np.asarray(t.get("lie_reach"), dtype=np.int64)) for t in tapes - if t.get("lie_reach") is not None] + R = [np.atleast_1d(np.asarray(t.get("lie_reach"), dtype=np.int64)) for t in tapes if t.get("lie_reach") is not None] R = [r for r in R if r.size] if not R or len({r.size for r in R}) != 1: return 0 @@ -175,6 +173,7 @@ def ev_lines(t, add): if (e["method"] != "multiply") == add: out.append(f"{e['var']} = {e['value']}" if add else f"_ = {e['value']}") return out + # a recast E = base^e scales with weight e times that of the base, L = log(base) is translated recast = [r for r in multi.get("power_recast") or [] if not r.get("inverted")] try: @@ -182,11 +181,12 @@ def ev_lines(t, add): per_cond_model=[_lines(t.get("model_lines")) for t in ver_tapes], per_cond_obs=[_lines(t.get("obs_lines")) for t in ver_tapes], inputs=inputs or None, - fixed=list(fixed) if fixed else None, recast=recast or None, powers=True, - extra_model=[_lines(t.get("ver_ic")) + ev_lines(t, True) + _lines(t.get("ver_rest")) - for t in ver_tapes], - extra_obs=[ev_lines(t, False) + ([f"_ = {t['ver_time']}"] - if t.get("ver_time") else []) for t in ver_tapes]) + fixed=list(fixed) if fixed else None, + recast=recast or None, + powers=True, + extra_model=[_lines(t.get("ver_ic")) + ev_lines(t, True) + _lines(t.get("ver_rest")) for t in ver_tapes], + extra_obs=[ev_lines(t, False) + ([f"_ = {t['ver_time']}"] if t.get("ver_time") else []) for t in ver_tapes], + ) except Exception as exc: swallow(exc, "exact scalings") full = None @@ -209,8 +209,7 @@ def ev_lines(t, add): def regime_keys(tapes): """Key per tape from the model and observation lines of the tape; equal keys share one regime.""" - return ["\n".join(_lines(t.get("model_lines")) + ["\x1f"] + _lines(t.get("obs_lines"))) - for t in tapes] + return ["\n".join(_lines(t.get("model_lines")) + ["\x1f"] + _lines(t.get("obs_lines"))) for t in tapes] def _as_eqn(lines): @@ -224,6 +223,7 @@ def _as_eqn(lines): def field_setup(multi, chains, cores, fixed=None, fields=None): """Generators of each regime with a closed form, and the joins of every chain.""" from .core import symmetry_detection + tapes = multi["tapes"] key_of = regime_keys(tapes) rkeys = list(dict.fromkeys(key_of)) @@ -232,7 +232,7 @@ def field_setup(multi, chains, cores, fixed=None, fields=None): for k in rkeys: t = tapes[key_of.index(k)] regimes.append({"f": _lines(t.get("model_lines")), "g": _lines(t.get("obs_lines"))}) - par = (fields is None and len(regimes) >= max(2, cores // 2) and cores > 1) + par = fields is None and len(regimes) >= max(2, cores // 2) and cores > 1 cores_r = 1 if par else cores def one(rg): @@ -242,8 +242,15 @@ def one(rg): fx = [s for s in (fixed or []) if s in syms and s not in fe] try: with state.options(inner=True, order_hint=None): - r = symmetry_detection(fe, ge, reconstruct=True, verify=False, cores=cores_r, - fixed=fx if fx else None, control=session.current().control) + r = symmetry_detection( + fe, + ge, + reconstruct=True, + verify=False, + cores=cores_r, + fixed=fx if fx else None, + control=session.current().control, + ) except Exception as e: swallow(e, "regime detection") if state.env("LIEDIAG"): @@ -266,8 +273,7 @@ def one(rg): if a != b or _evs(ev): joins.append({"from": a - 1, "to": b - 1, "ev": _evs(ev), "chain": ci}) states = list(dict.fromkeys(l.split("=", 1)[0].strip() for rg in regimes for l in rg["f"])) - return {"regimes": regimes, "gens": gens, "regime_of": regime_of, "joins": joins, - "states": states, "tapes": tapes} + return {"regimes": regimes, "gens": gens, "regime_of": regime_of, "joins": joins, "states": states, "tapes": tapes} def own_fields(dirs): @@ -330,8 +336,7 @@ def field_check(setup, V, znames, leaf_names, point, chains, joint): lf0 = lift_start(_lines(t1.get("ver_ic")), t0, base, {}, P, joint=joint is not None) times = [t["ver_time"] for t in (setup["tapes"][i] for i in ch) if t.get("ver_time")] lift_of[ci] = len(lifts) - lifts.append({"regime": setup["regime_of"][ch[0]] - 1, "point": lf0["point"], - "vectors": vecs, "times": times}) + lifts.append({"regime": setup["regime_of"][ch[0]] - 1, "point": lf0["point"], "vectors": vecs, "times": times}) joins = [] for e in setup["joins"]: e = dict(e) @@ -363,8 +368,7 @@ def extended_fields(setup, chains): return extend_fields(setup["gens"][reg1 - 1], _lines(t1.get("ver_ic")), groups, setup["states"]) -def field_directions(setup, N, n_res, scal_rows, znames, leaf_names, point, chains, joint, - partial=False): +def field_directions(setup, N, n_res, scal_rows, znames, leaf_names, point, chains, joint, partial=False): """Closed forms of the residual kernel from the first regime's fields; RouteError where they do not close it.""" P = PRIMES[0] stset = set(setup["states"]) @@ -407,6 +411,7 @@ def matrix_rank(M): if M.shape[0] == 0: return 0 return int(_core.sym_rref_mod(M.astype(np.float64), P)["rank"]) + basis = Sp chosen = [] r_np = matrix_rank(Np.T) @@ -419,8 +424,10 @@ def matrix_rank(M): if len(chosen) == n_res: break if state.env("LIEDIAG"): - print(f"[liediag] global symmetries: {len(ext)} field(s), {len(cand)} candidate(s), " - f"{len(chosen)} chosen of {n_res}") + print( + f"[liediag] global symmetries: {len(ext)} field(s), {len(cand)} candidate(s), " + f"{len(chosen)} chosen of {n_res}" + ) if not chosen or (len(chosen) < n_res and not partial): raise RouteError(f"the regime fields give {len(chosen)} of {n_res} directions") Vw = np.zeros((N.shape[0], len(chosen)), dtype=np.int64) @@ -447,10 +454,19 @@ def matrix_rank(M): out = [] for c0 in chosen: ex = exact_direction(setup, c0["field"], chains, joint is not None) - out.append({"support": sym_sort(list(c0["expr"])), "vector": c0["expr"], "type": "general", - "closed_form": True, "route": "global symmetry", "certified": True, - "exact": ex["ok"] is True, "state_components": ex.get("states"), - "lift_form": dict(c0["expr"])}) + out.append( + { + "support": sym_sort(list(c0["expr"])), + "vector": c0["expr"], + "type": "general", + "closed_form": True, + "route": "global symmetry", + "certified": True, + "exact": ex["ok"] is True, + "state_components": ex.get("states"), + "lift_form": dict(c0["expr"]), + } + ) if len(chosen) < n_res: return {"partial": True, "dirs": out, "vectors": Vw} return out @@ -487,22 +503,27 @@ def restricted_setup(setup, chains, joint): regimes, tapes = setup["regimes"], setup["tapes"] states = list(setup["states"]) stset = set(states) - eqs = [{l.split("=", 1)[0].strip(): model_sympify(l.split("=", 1)[1]) for l in rg["f"]} - for rg in regimes] + eqs = [{l.split("=", 1)[0].strip(): model_sympify(l.split("=", 1)[1]) for l in rg["f"]} for rg in regimes] events = [_evs(t.get("ver_t0")) + _evs(t.get("ver_ev")) for t in tapes] targets = {str(e["var"]) for ch in chains for i in ch for e in events[i]} zero = set() if not joint: zero = set(states) - targets for i in dict.fromkeys(ch[0] for ch in chains): - zero &= {l.split("=", 1)[0].strip() for l in _lines(tapes[i].get("ver_ic")) - if l.split("=", 1)[1].strip() in ("0", "0.0")} + zero &= { + l.split("=", 1)[0].strip() + for l in _lines(tapes[i].get("ver_ic")) + if l.split("=", 1)[1].strip() in ("0", "0.0") + } visited = sorted({setup["regime_of"][i] - 1 for ch in chains for i in ch}) while True: sub = {spy.Symbol(x): spy.Integer(0) for x in zero} # the regimes of many conditions repeat an equation: each distinct one is checked once - drop = {x for x in zero if any(spy.cancel(e.xreplace(sub)) != 0 - for e in {eqs[r][x] for r in visited if x in eqs[r]})} + drop = { + x + for x in zero + if any(spy.cancel(e.xreplace(sub)) != 0 for e in {eqs[r][x] for r in visited if x in eqs[r]}) + } if not drop: break zero -= drop @@ -513,10 +534,12 @@ def syms(e): if names & zero: names = {str(y) for y in e.xreplace(sub).free_symbols} return names & stset + # the states each equation, observable and event value holds, once per regime and tape dep = [{x: syms(f) for x, f in eq.items()} for eq in eqs] - obs_dep = [set().union(*[syms(model_sympify(l.split("=", 1)[1] if "=" in l else l)) for l in rg["g"]]) - for rg in regimes] + obs_dep = [ + set().union(*[syms(model_sympify(l.split("=", 1)[1] if "=" in l else l)) for l in rg["g"]]) for rg in regimes + ] ev_dep = [set().union(*[syms(model_sympify(str(e["value"]))) for e in evs]) for evs in events] # regimes that differ in values only have the same dependencies, and the same closure from the same start kinds = {} @@ -553,24 +576,30 @@ def cut(lines, keep): if lhs in keep or lhs not in stset: if rhs not in zeroed: # a value that holds no state at zero stays as written - zeroed[rhs] = str(model_sympify(rhs).xreplace(sub)) \ - if set(_NAMES.findall(rhs)) & zero else rhs + zeroed[rhs] = str(model_sympify(rhs).xreplace(sub)) if set(_NAMES.findall(rhs)) & zero else rhs out.append(f"{lhs} = {zeroed[rhs]}") return out - new_regimes = [{"f": cut(rg["f"], keep_r.get(r, stset)), - "g": [f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" - for l in rg["g"]]} for r, rg in enumerate(regimes)] + + new_regimes = [ + { + "f": cut(rg["f"], keep_r.get(r, stset)), + "g": [f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" for l in rg["g"]], + } + for r, rg in enumerate(regimes) + ] new_tapes = [] for i, t in enumerate(tapes): keep = keep_of.get(i, stset) - t = dict(t, ver_ic=cut(t.get("ver_ic"), keep), - ver_t0=[e for e in _evs(t.get("ver_t0")) if str(e["var"]) in keep], - ver_ev=[e for e in _evs(t.get("ver_ev")) if str(e["var"]) in keep]) + t = dict( + t, + ver_ic=cut(t.get("ver_ic"), keep), + ver_t0=[e for e in _evs(t.get("ver_t0")) if str(e["var"]) in keep], + ver_ev=[e for e in _evs(t.get("ver_ev")) if str(e["var"]) in keep], + ) new_tapes.append(t) union = set().union(*keep_r.values()) if keep_r else set() joins = [dict(e, ev=[v for v in e["ev"] if str(v["var"]) in union]) for e in setup["joins"]] - return dict(setup, regimes=new_regimes, tapes=new_tapes, joins=joins, - states=[x for x in states if x in union]) + return dict(setup, regimes=new_regimes, tapes=new_tapes, joins=joins, states=[x for x in states if x in union]) def exact_direction(setup, field, chains, joint, init=(), known=()): @@ -585,14 +614,17 @@ def exact_direction(setup, field, chains, joint, init=(), known=()): # a jet of an unknown input has no identity: the jet component prolongs the input component; the last # jet has no derivative in the chain jets, tops = setup.get("jets") or (), set(setup.get("jet_tops") or ()) + def names(v): return set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", str(v))) + if tops and any(tops & names(v) for v in dict(field).values()): return {"ok": None, "why": "a component holds the last jet of an unknown input"} # a parameter component is constant in time, which no identity checks once it holds an input; the # lines below allow it, since they show only that the field annihilates every Lie derivative - param_input = bool(jets) and any(set(jets) & names(v) for k, v in theta.items() - if k in set(setup.get("params") or ())) + param_input = bool(jets) and any( + set(jets) & names(v) for k, v in theta.items() if k in set(setup.get("params") or ()) + ) # a field whose lines the flow keeps is a symmetry as well, unless a switch moves the joins lines_ok = not joint and all(e["ev"] for e in setup["joins"]) if param_input and not lines_ok: @@ -613,8 +645,10 @@ def holds(r, f): own = [ch for ch in chains if setup["regime_of"][ch[0]] - 1 == r] ics = None if own and not joint: - ics = [f"{x.strip()} = {_rename_init(e.strip(), init)}" for x, e in - (line.split("=", 1) for line in _lines(setup["tapes"][own[0][0]].get("ver_ic")))] + ics = [ + f"{x.strip()} = {_rename_init(e.strip(), init)}" + for x, e in (line.split("=", 1) for line in _lines(setup["tapes"][own[0][0]].get("ver_ic"))) + ] # the lift of a regime with the same initial values first: the regimes of many conditions share it if tuple(ics) in found and holds(r, found[tuple(ics)]): of[r] = found[tuple(ics)] @@ -624,16 +658,17 @@ def holds(r, f): continue # initial values set by other parameters: the state components from their identities if ics is not None: - lifts = (lambda: initial_lift(field, ics, states, regimes[r]["f"]), - lambda: linear_lift(field, regimes[r], ics, states), - lambda: None if jets else support_lift(field, regimes[r], ics, states)) + lifts = ( + lambda: initial_lift(field, ics, states, regimes[r]["f"]), + lambda: linear_lift(field, regimes[r], ics, states), + lambda: None if jets else support_lift(field, regimes[r], ics, states), + ) lift = next((x for x in (make() for make in lifts) if x is not None and holds(r, x)), None) if lift is not None: of[r] = found[tuple(ics)] = lift continue # in another regime the direction may need other state components - alt = None if jets else \ - combined_field(extended_fields(setup, own) if own else setup["gens"][r], theta, states) + alt = None if jets else combined_field(extended_fields(setup, own) if own else setup["gens"][r], theta, states) res = certify(regime_identities(regimes[r], alt if alt is not None else field, jets)) if res["ok"] is not True: return res @@ -642,8 +677,9 @@ def holds(r, f): for e in setup["joins"]: if e["from"] in of and e["to"] in of: if e["from"] in by_line or e["to"] in by_line: - part = line_event_identities(e["ev"], of[e["from"]], of[e["to"]], states, - [k[e["to"]] for k in known if e["to"] in k], jets) + part = line_event_identities( + e["ev"], of[e["from"]], of[e["to"]], states, [k[e["to"]] for k in known if e["to"] in k], jets + ) if part is None: at = e["ev"][0].get("time") return {"ok": None, "why": f"no factor maps the field through the event at {at}"} @@ -687,6 +723,7 @@ def holds(r, f): def _in_span_at_a_point(A, b): """False when b is outside the column span of A at a random rational point.""" import random + rng = random.Random(len(A)) syms = sorted(A.free_symbols | b.free_symbols, key=str) pt = {x: spy.Rational(rng.randint(2, 997), rng.randint(2, 997)) for x in syms} @@ -709,6 +746,7 @@ def _square_solve(A, b): import random from sympy.polys.matrices import DomainMatrix + if sum(spy.count_ops(x) for x in list(A) + list(b)) > _SOLVE_OPS: session.note("limits", "combined lift: the system is past the size of a symbolic solve") return None @@ -766,18 +804,27 @@ def combined_field(gens, vec, states): return None -def static_fields(multi, models, conds, chains, p_names, leaf_names, point, forcings=None, - zeros=None): +def static_fields(multi, models, conds, chains, p_names, leaf_names, point, forcings=None, zeros=None): """Fields of the static subsystems of the resting conditions with values at point.""" tp = multi["tapes"] cl = [] for i, ci in enumerate(conds): idx = chains[i] - cl.append({"rest": _lines(models[ci]), - "zero": [str(z) for z in zeros[i]] if zeros is not None and len(zeros) > i and zeros[i] else [], - "segs": [{"f": _lines(tp[t].get("model_lines")), "g": _lines(tp[t].get("obs_lines")), - "ev": _evs(tp[t].get("ver_ev"))} for t in idx], - "t0": _evs(tp[idx[0]].get("ver_t0"))}) + cl.append( + { + "rest": _lines(models[ci]), + "zero": [str(z) for z in zeros[i]] if zeros is not None and len(zeros) > i and zeros[i] else [], + "segs": [ + { + "f": _lines(tp[t].get("model_lines")), + "g": _lines(tp[t].get("obs_lines")), + "ev": _evs(tp[t].get("ver_ev")), + } + for t in idx + ], + "t0": _evs(tp[idx[0]].get("ver_t0")), + } + ) try: sf = static_fields_symbolic(cl, list(p_names), list(forcings) if forcings else None) except Exception as exc: @@ -803,11 +850,19 @@ def static_fields(multi, models, conds, chains, p_names, leaf_names, point, forc x = np.zeros(len(p_names), dtype=np.int64) for k, e in zip(f.keys(), ev): x[list(p_names).index(k)] = e - lx = np.array([0 if x[i] == 0 else int(x[i]) * invmod(vals[i], P) % P - for i in range(len(x))], dtype=np.int64) - out.append({"support": sym_sort(list(f)), "vector": dict(f), "val": x, "lval": lx, - "type": "general", "closed_form": True, "route": "static subsystem", - "certified": True}) + lx = np.array([0 if x[i] == 0 else int(x[i]) * invmod(vals[i], P) % P for i in range(len(x))], dtype=np.int64) + out.append( + { + "support": sym_sort(list(f)), + "vector": dict(f), + "val": x, + "lval": lx, + "type": "general", + "closed_form": True, + "route": "static subsystem", + "certified": True, + } + ) return out or None @@ -828,9 +883,29 @@ def _rate_order(r, top): def _segment_key(sg): """What the ranks of a segment from a given start read of the tape of the segment.""" - return tuple(tuple(np.atleast_1d(np.asarray(sg[k])).tolist()) if sg.get(k) is not None else None - for k in ("op", "a", "b", "cnum", "cden", "state_slots", "f_out", "g_out", "tm_op", "tm_a", - "tm_b", "tm_cnum", "tm_cden", "tm_out", "leaf_slot", "leaf_src", "leaf_num", "leaf_den")) + return tuple( + tuple(np.atleast_1d(np.asarray(sg[k])).tolist()) if sg.get(k) is not None else None + for k in ( + "op", + "a", + "b", + "cnum", + "cden", + "state_slots", + "f_out", + "g_out", + "tm_op", + "tm_a", + "tm_b", + "tm_cnum", + "tm_cden", + "tm_out", + "leaf_slot", + "leaf_src", + "leaf_num", + "leaf_den", + ) + ) def _jet_key(key): @@ -879,14 +954,33 @@ def _sz_term(deg, n_cols, K, draws=None, rest=1): out = 0 for md, d0, ns in zip(mds, d0s, stops): n_obs = max(1, len(md[2])) - out += int(d0) * (int(ns) * md[0] + gen * sum(min((k + 1) * n_obs, n_cols) * lie_row_degree(md, k + 1) - for k in range(K + 1))) + out += int(d0) * ( + int(ns) * md[0] + gen * sum(min((k + 1) * n_obs, n_cols) * lie_row_degree(md, k + 1) for k in range(K + 1)) + ) return int(rest) * (int(deg.get("bezout", 1)) * out + int(deg.get("extra", 0))) -def lie_certificate(segs, seeds, n_leaves, n_states, z_slots, p, cap, map_fn=None, threads=1, - start=None, degs=None, terms=None, at_rest=False, start_seeds=None, start_p=None, - rest_draws=1, draws=None, drop_states=(), cores=None): +def lie_certificate( + segs, + seeds, + n_leaves, + n_states, + z_slots, + p, + cap, + map_fn=None, + threads=1, + start=None, + degs=None, + terms=None, + at_rest=False, + start_seeds=None, + start_p=None, + rest_draws=1, + draws=None, + drop_states=(), + cores=None, +): """Certified Lie order per block, None where the start does not reach the generic rank; `terms` receives the error bounds and `draws` per block the most points drawn for one random point, `rest_draws` those of the resting point. @@ -971,16 +1065,22 @@ def values(): sg = sb[j] if j > 0 and sg.get("ev_var_idx") is not None and len(np.atleast_1d(sg["ev_var_idx"])): evi = np.atleast_1d(sg["ev_var_idx"]).astype(np.int64) - V = event_space(V, evi, np.atleast_1d(sg["ev_method"]).astype(np.int64), - sg.get("ev_leaf_only", np.ones(len(evi), dtype=bool)), n_states, p) + V = event_space( + V, + evi, + np.atleast_1d(sg["ev_method"]).astype(np.int64), + sg.get("ev_leaf_only", np.ones(len(evi), dtype=bool)), + n_states, + p, + ) while True: lv, Qt, n_drawn = values() if lv is None: return None y = rand_in(Qt[j], V) - Y = Qt[:j + 1].copy() + Y = Qt[: j + 1].copy() Y[j] = y - fz = _core.sym_segment_ranks(sb[:j + 1], n_leaves, n_states, z_b, lv, p, 0, Y) + fz = _core.sym_segment_ranks(sb[: j + 1], n_leaves, n_states, z_b, lv, p, 0, Y) if not fz.get("ok"): return None field = np.asarray(fz["field"], dtype=np.int64).reshape(j + 1, n_states)[j] @@ -1020,17 +1120,44 @@ def call(kind, s, Nc, threads): seg_keys[id(sb[s])] = _segment_key(sb[s]) if kind == "g": # the jets of a call continue those of the call before at a lower order - jets = _jet_key((seg_keys[id(sb[s])], st_g[s].tobytes(), np.asarray(lv_g).tobytes(), int(p), - z_b.tobytes(), drop.tobytes())) - return _core.sym_segment_ranks([sb[s]], n_leaves, n_states, z_b, lv_g, p, Nc, st_g[s:s + 1], - threads, drop, True, jets) - key = (seg_keys[id(sb[s])], q_start[s].tobytes(), (s_seed % s_p).tobytes(), int(s_p), z_b.tobytes(), - drop.tobytes()) + jets = _jet_key( + ( + seg_keys[id(sb[s])], + st_g[s].tobytes(), + np.asarray(lv_g).tobytes(), + int(p), + z_b.tobytes(), + drop.tobytes(), + ) + ) + return _core.sym_segment_ranks( + [sb[s]], n_leaves, n_states, z_b, lv_g, p, Nc, st_g[s : s + 1], threads, drop, True, jets + ) + key = ( + seg_keys[id(sb[s])], + q_start[s].tobytes(), + (s_seed % s_p).tobytes(), + int(s_p), + z_b.tobytes(), + drop.tobytes(), + ) kept = shared.get(key) if kept is not None and len(kept) > Nc: - return {"ok": True, "ranks": kept[:Nc + 1]} - r = _core.sym_segment_ranks([sb[s]], n_leaves, n_states, z_b, s_seed % s_p, s_p, Nc, - q_start[s:s + 1], threads, drop, True, _jet_key(key)) + return {"ok": True, "ranks": kept[: Nc + 1]} + r = _core.sym_segment_ranks( + [sb[s]], + n_leaves, + n_states, + z_b, + s_seed % s_p, + s_p, + Nc, + q_start[s : s + 1], + threads, + drop, + True, + _jet_key(key), + ) if r.get("ok"): shared[key] = np.asarray(r["ranks"]).ravel() return r @@ -1046,7 +1173,7 @@ def extend(jobs): for (kind, sj, Nc), r in zip(jobs, got): if not r.get("ok"): return False - (G if kind == "g" else Q)[sj] = np.asarray(r["ranks"]).ravel()[:Nc + 1] + (G if kind == "g" else Q)[sj] = np.asarray(r["ranks"]).ravel()[: Nc + 1] return True def known(Nt): @@ -1054,11 +1181,11 @@ def known(Nt): the rank after it, up to Nt; the jobs that the ranks up to Nt need.""" g_n, ordv, jobs = [], [], [] for sj in range(n_seg): - gn = _flat_at(G[sj][:Nt + 1]) + gn = _flat_at(G[sj][: Nt + 1]) if gn is None and len(G[sj]) <= Nt: jobs.append(("g", sj)) g_n.append(gn) - ra = None if gn is None else _reach_at(Q[sj][:Nt + 1], G[sj][gn + 1]) + ra = None if gn is None else _reach_at(Q[sj][: Nt + 1], G[sj][gn + 1]) if gn is not None and ra is None and len(Q[sj]) <= Nt: jobs.append(("q", sj)) ordv.append(ra) @@ -1109,8 +1236,10 @@ def target(kind, sj, Nt): def lanes(b): cols = read_columns(segs[b], n_leaves, z_slots) return len(segs[b]) * ((len(z_slots) if cols is None else len(cols)) + n_states) - order = sorted(idx, key=lambda b: (-lanes(b), -(start[b] or 0) if start is not None and len(start) == len(idx) - else 0)) + + order = sorted( + idx, key=lambda b: (-lanes(b), -(start[b] or 0) if start is not None and len(start) == len(idx) else 0) + ) got = dict(zip(order, map_fn(one, order))) res = [got[b] for b in idx] else: diff --git a/src/symident/detection/finalize.py b/src/symident/detection/finalize.py index 9fc4589..4ba677f 100644 --- a/src/symident/detection/finalize.py +++ b/src/symident/detection/finalize.py @@ -35,15 +35,23 @@ def public_symmetry(d): inp = d.get("input_vector") or None if inp is not None and gen is not None: from .fields import rescaled_lift + inp = rescaled_lift(gen, d.get("input_form") or gen, inp) if inp is not None: inp = {k: str(v).replace("**", "^") for k, v in inp.items()} - return {"type": re.sub(r"^Type: ", "", str(d.get("type"))), "generator": gen, - "weights": weights, "degree": d.get("degree"), - "support": d.get("support") if d.get("support") is not None else list(gen or []), - "explicit": gen is not None, "reason": d.get("reason"), "route": d.get("route"), - "level": level_of(d, gen), - "state_components": _lift(d, gen), "input_change": inp} + return { + "type": re.sub(r"^Type: ", "", str(d.get("type"))), + "generator": gen, + "weights": weights, + "degree": d.get("degree"), + "support": d.get("support") if d.get("support") is not None else list(gen or []), + "explicit": gen is not None, + "reason": d.get("reason"), + "route": d.get("route"), + "level": level_of(d, gen), + "state_components": _lift(d, gen), + "input_change": inp, + } def _lift(d, gen): @@ -52,11 +60,12 @@ def _lift(d, gen): if sc is None or gen is None or d.get("lift_form") is None: return sc from .fields import rescaled_lift + return rescaled_lift(gen, d["lift_form"], sc) def level_of(d, gen): - """"exact" when proven over Q, "verified" when checked modulo a prime on every entry, "checked" when on part + """ "exact" when proven over Q, "verified" when checked modulo a prime on every entry, "checked" when on part of them, "open" without a closed form.""" if gen is None: return "open" @@ -126,8 +135,7 @@ def complete(syms, positive=True, coordinates=None): if isinstance(positive, (list, tuple)) and coordinates: unknown = [p for p in positive if p not in set(coordinates)] if unknown: - warnings.warn("`positive` names no coordinate: " - f"{', '.join(unknown)}; ignored.", stacklevel=2) + warnings.warn(f"`positive` names no coordinate: {', '.join(unknown)}; ignored.", stacklevel=2) out = [] for d in syms: if d["generator"] is None: @@ -171,37 +179,55 @@ def finalize(raw, method, settings, elapsed=None, coordinates=None): rank = int(raw["rank"]) if raw.get("rank") is not None else None dim = int(raw["dim"]) if raw.get("dim") is not None else None identifiable = (rank == dim) if is_obs else None - engine = "integer-kernel" if method == "scaling" else \ - ("symbolic" if raw.get("engine") == "symbolic" else "modular") + engine = "integer-kernel" if method == "scaling" else ("symbolic" if raw.get("engine") == "symbolic" else "modular") keep = bool(state.get("keep_kernel")) - info = {"engine": engine, "lie_order_used": raw.get("lie_order_used"), - "lie_order_driver": raw.get("lie_order_driver"), "lie_plateau": raw.get("lie_plateau"), - "lie_certified": raw.get("lie_certified"), "lie_uncertified": raw.get("lie_uncertified"), - "lie_certificate": raw.get("lie_certificate"), - "lie_block_orders": raw.get("lie_block_orders"), - "kernel": raw.get("kernel") if keep else None, - "sat_score": raw.get("sat_score") if keep else None, - "stacked": raw.get("stacked") if keep else None, - "rank_proven": raw.get("rank_proven"), "rank_proof": raw.get("rank_proof"), - "rank_fields": raw.get("rank_fields"), "rank_fields_bound": raw.get("rank_fields_bound"), - "gap_order_used": raw.get("gap_order_used"), "gap_certified": raw.get("gap_certified"), - "gap_certificate": raw.get("gap_certificate"), "gap_bound": raw.get("gap_bound"), - "order_bound": raw.get("order_bound"), "order_bound_why": raw.get("order_bound_why"), - "order_draws": raw.get("order_draws"), - "projection": raw.get("projection"), - "series_certified": raw.get("series_certified"), "series_certificate": raw.get("series_certificate"), - "conditions": raw.get("conditions"), "selection": raw.get("selection"), - "segments": raw.get("segments"), - "coordinates": list(raw["coordinates"]) if raw.get("coordinates") is not None else coordinates, - "settings": settings, "elapsed": elapsed, "timing": raw.get("timing"), - "verification": raw.get("verification"), - "bound": raw.get("bound"), - "attempts": [{"support": d.get("support"), "attempts": [list(a) for a in d["attempts"]]} - for d in raw_syms if d.get("attempts")], - "proof": [{"support": s["support"], "reason": d.get("proof") or "no exact proof on this path"} - for d, s in zip(raw_syms, syms) if s["level"] == "verified"]} - return {"method": method, "identifiable": identifiable, "rank": rank, "dim": dim, - "symmetries": syms, "info": info} + info = { + "engine": engine, + "lie_order_used": raw.get("lie_order_used"), + "lie_order_driver": raw.get("lie_order_driver"), + "lie_plateau": raw.get("lie_plateau"), + "lie_certified": raw.get("lie_certified"), + "lie_uncertified": raw.get("lie_uncertified"), + "lie_certificate": raw.get("lie_certificate"), + "lie_block_orders": raw.get("lie_block_orders"), + "kernel": raw.get("kernel") if keep else None, + "sat_score": raw.get("sat_score") if keep else None, + "stacked": raw.get("stacked") if keep else None, + "rank_proven": raw.get("rank_proven"), + "rank_proof": raw.get("rank_proof"), + "rank_fields": raw.get("rank_fields"), + "rank_fields_bound": raw.get("rank_fields_bound"), + "gap_order_used": raw.get("gap_order_used"), + "gap_certified": raw.get("gap_certified"), + "gap_certificate": raw.get("gap_certificate"), + "gap_bound": raw.get("gap_bound"), + "order_bound": raw.get("order_bound"), + "order_bound_why": raw.get("order_bound_why"), + "order_draws": raw.get("order_draws"), + "projection": raw.get("projection"), + "series_certified": raw.get("series_certified"), + "series_certificate": raw.get("series_certificate"), + "conditions": raw.get("conditions"), + "selection": raw.get("selection"), + "segments": raw.get("segments"), + "coordinates": list(raw["coordinates"]) if raw.get("coordinates") is not None else coordinates, + "settings": settings, + "elapsed": elapsed, + "timing": raw.get("timing"), + "verification": raw.get("verification"), + "bound": raw.get("bound"), + "attempts": [ + {"support": d.get("support"), "attempts": [list(a) for a in d["attempts"]]} + for d in raw_syms + if d.get("attempts") + ], + "proof": [ + {"support": s["support"], "reason": d.get("proof") or "no exact proof on this path"} + for d, s in zip(raw_syms, syms) + if s["level"] == "verified" + ], + } + return {"method": method, "identifiable": identifiable, "rank": rank, "dim": dim, "symmetries": syms, "info": info} def log_arg_back(raw, la): @@ -217,9 +243,9 @@ def ren(x): def back(vec): if not vec: return vec - out = log_arg_back_vec({k: str(x).replace("^", "**") for k, x in vec.items()}, - la["map"]) + out = log_arg_back_vec({k: str(x).replace("^", "**") for k, x in vec.items()}, la["map"]) return {k: str(x).replace("**", "^") for k, x in out.items()} + ab_syms = set(get_symbols([x for m in la["map"] for x in (m["a"], m["b"])])) Lset = set(la["L"]) pat = re.compile(r"\b(" + "|".join(re.escape(l) for l in la["L"]) + r")\b") if la["L"] else None @@ -227,10 +253,17 @@ def back(vec): def fix_dir(d): if not isinstance(d, dict): return d - names = list((d.get("vector") or {}).keys()) + list((d.get("infinitesimals") or {}).keys()) + \ - list(d.get("support") or []) - vals = [str(v) for v in list((d.get("vector") or {}).values()) + - list((d.get("infinitesimals") or {}).values()) + list((d.get("input_vector") or {}).values())] + names = ( + list((d.get("vector") or {}).keys()) + + list((d.get("infinitesimals") or {}).keys()) + + list(d.get("support") or []) + ) + vals = [ + str(v) + for v in list((d.get("vector") or {}).values()) + + list((d.get("infinitesimals") or {}).values()) + + list((d.get("input_vector") or {}).values()) + ] hit = any(n in Lset | ab_syms for n in names) or (pat is not None and any(pat.search(v) for v in vals)) if not hit: return d @@ -258,8 +291,11 @@ def fix_dir(d): elif d.get("support") is not None: sup = ren(d["support"]) while True: - add = [m["v"] for m in la["map"] if m["v"] not in sup and - any(s in sup for s in get_symbols([m["a"], m["b"]]))] + add = [ + m["v"] + for m in la["map"] + if m["v"] not in sup and any(s in sup for s in get_symbols([m["a"], m["b"]])) + ] if not add: break sup = sup + add @@ -271,6 +307,7 @@ def fix_dir(d): d["input_vector"] = {k: str(model_sympify(str(v)).xreplace(at)) for k, v in d["input_vector"].items()} d["input_form"] = back(d.get("input_form")) return d + raw = dict(raw) if raw.get("coordinates") is not None: raw["coordinates"] = ren(raw["coordinates"]) diff --git a/src/symident/detection/firstint.py b/src/symident/detection/firstint.py index 042e859..d1e577c 100644 --- a/src/symident/detection/firstint.py +++ b/src/symident/detection/firstint.py @@ -37,7 +37,7 @@ def _diff(P, j): out = {} for m, c in P.items(): if m[j]: - mm = m[:j] + (m[j] - 1,) + m[j + 1:] + mm = m[:j] + (m[j] - 1,) + m[j + 1 :] out[mm] = out.get(mm, 0) + c * m[j] return out @@ -134,15 +134,23 @@ def _galois(K, J, blocks, laws): continue # the multiplicity over K is at least the one of the laws and at most the one modulo a prime zeros = mult - need = {b: {"n": len(B) - zeros[b], "full": None, "minus": None if len(B) - zeros[b] > 2 else "n/a", - "transposition": None} for b, B in enumerate(blocks) if len(B) - zeros[b] >= 2} + need = { + b: { + "n": len(B) - zeros[b], + "full": None, + "minus": None if len(B) - zeros[b] > 2 else "n/a", + "transposition": None, + } + for b, B in enumerate(blocks) + if len(B) - zeros[b] >= 2 + } pairs = {(a, b): None for a in need for b in need if a < b} if mult != zeros: continue types = {} where = [p, int(tau)] if K.d > 1 else p for b, rec in need.items(): - ct = cycle_type(chis[b][:len(chis[b]) - zeros[b]], p) + ct = cycle_type(chis[b][: len(chis[b]) - zeros[b]], p) if ct is None: continue types[b] = ct @@ -156,18 +164,26 @@ def _galois(K, J, blocks, laws): for a, b in pairs: if pairs[(a, b)] is None and a in types and b in types and order_of(types[a]) != order_of(types[b]): pairs[(a, b)] = where - if zeros is not None and all(r["full"] is not None and r["minus"] is not None for r in need.values()) and \ - all(v is not None for v in pairs.values()): + if ( + zeros is not None + and all(r["full"] is not None and r["minus"] is not None for r in need.values()) + and all(v is not None for v in pairs.values()) + ): break if zeros is None: - raise _OpenError(f"the Jacobian at the equilibrium has the eigenvalue 0 more often than the {laws} " - "conservation laws give, at every prime read" if laws else - "the Jacobian at the equilibrium has the eigenvalue 0 modulo every prime read, as under a " - "conservation law") + raise _OpenError( + f"the Jacobian at the equilibrium has the eigenvalue 0 more often than the {laws} " + "conservation laws give, at every prime read" + if laws + else "the Jacobian at the equilibrium has the eigenvalue 0 modulo every prime read, as under a " + "conservation law" + ) for r in need.values(): if r["full"] is None or r["minus"] is None: - raise _OpenError(f"no prime of the {seen} read shows the cycles that make the Galois group of a block " - f"of degree {r['n']} 2-transitive") + raise _OpenError( + f"no prime of the {seen} read shows the cycles that make the Galois group of a block " + f"of degree {r['n']} 2-transitive" + ) if any(v is None for v in pairs.values()): raise _OpenError("no prime of those read separates the splitting fields of two blocks of the Jacobian") return zeros, need, pairs @@ -178,8 +194,9 @@ def _text(K, a): if len(a) == 1: return str(a[0]) s = spy.Symbol("s") - return str(sum((spy.Rational(c.numerator, c.denominator) * s ** k for k, c in enumerate(a)), - spy.Integer(0))).replace("**", "^") + return str(sum((spy.Rational(c.numerator, c.denominator) * s**k for k, c in enumerate(a)), spy.Integer(0))).replace( + "**", "^" + ) def _test(K, J, names, laws=0): @@ -196,13 +213,14 @@ def _test(K, J, names, laws=0): if len(keep) == 1 and K.is_zero(traces[keep[0]]): raise _OpenError("the trace of the Jacobian at the equilibrium is 0") if rank_over_q([traces[b] for b in keep]) < len(keep): - raise _OpenError(f"the traces of the {len(keep)} diagonal blocks are linearly dependent over Q in a field " - f"of degree {max(K.d, 1)}") + raise _OpenError( + f"the traces of the {len(keep)} diagonal blocks are linearly dependent over Q in a field " + f"of degree {max(K.d, 1)}" + ) out = [] for b in keep: r = need.get(b) - e = {"states": [names[i] for i in blocks[b]], "degree": len(blocks[b]) - zeros[b], - "trace": _text(K, traces[b])} + e = {"states": [names[i] for i in blocks[b]], "degree": len(blocks[b]) - zeros[b], "trace": _text(K, traces[b])} if zeros[b]: e["zero_eigenvalues"] = zeros[b] if r is not None: @@ -250,14 +268,21 @@ def _attempt(K, F, U, allv, names, laws, d): def _proven(K, point, alpha, sym, fixed, reads, st, equilibrium, laws, got, t0): """The fields of a proven certificate.""" blocks, pairs = got - return {"proven": True, "why": None, "point": point, - "alpha": None if alpha is None else - str(sum(c * sym ** k for k, c in enumerate(alpha))).replace("**", "^") + " = 0", - "inputs": {st[i]: str(v) for i, v in fixed.items() if i in reads}, - "field": repr(K), "equilibrium": equilibrium, - "laws": [" + ".join(f"({c})*{x}" for x, c in law.items()) for law in laws], - "blocks": blocks, "splitting_fields": pairs, - "seconds": round(time.monotonic() - t0, 2)} + return { + "proven": True, + "why": None, + "point": point, + "alpha": None + if alpha is None + else str(sum(c * sym**k for k, c in enumerate(alpha))).replace("**", "^") + " = 0", + "inputs": {st[i]: str(v) for i, v in fixed.items() if i in reads}, + "field": repr(K), + "equilibrium": equilibrium, + "laws": [" + ".join(f"({c})*{x}" for x, c in law.items()) for law in laws], + "blocks": blocks, + "splitting_fields": pairs, + "seconds": round(time.monotonic() - t0, 2), + } def _field_poly(rng, d): @@ -276,6 +301,7 @@ def _equilibria(F, U, fixed, theta, alpha, nonzero, level=()): [(K, {variable: element})], each Galois orbit one field, smallest first; None and the reason where msolve finds none or a family.""" from .discrete import _msolve + names = [f"z{i}" for i in range(len(U))] syms = [spy.Symbol(n) for n in names] a = spy.Symbol("a") @@ -285,8 +311,14 @@ def _equilibria(F, U, fixed, theta, alpha, nonzero, level=()): gvals[i] = s def expr(P): - return sum((spy.Rational(c.numerator, c.denominator) * spy.prod([gvals[j] ** e for j, e in enumerate(m) if e]) - for m, c in P.items()), spy.Integer(0)) + return sum( + ( + spy.Rational(c.numerator, c.denominator) * spy.prod([gvals[j] ** e for j, e in enumerate(m) if e]) + for m, c in P.items() + ), + spy.Integer(0), + ) + eqs, dens = [], spy.Integer(1) for i in U: N, D = F[i] @@ -310,15 +342,17 @@ def ms(e): m = "*".join(f"{g}^{k}" if k > 1 else str(g) for g, k in zip(gens, mono) if k) out.append(f"{c}*{m}" if m else str(c)) return "+".join(out).replace("+-", "-") + # a balance that vanishes identically is a conservation law, whose level set enters below lines = [x for x in (ms(e) for e in eqs) if x is not None] lines += [ms(e) for e in level] if alpha is not None: - lines.append(ms(sum(c * a ** k for k, c in enumerate(alpha)))) + lines.append(ms(sum(c * a**k for k, c in enumerate(alpha)))) lines.append(ms(spy.Symbol("si_w") * sat - 1)) data = _msolve(msnames, 0, lines, ["-P", "1"]) if data is None: from . import work + why = work.msolve_too_large(msnames + ["si_w"], lines) return None, "msolve did not solve the balances" + (f": {why}" if why else "") if data[0] == 1: @@ -364,12 +398,22 @@ def _linear_point(F, U, fixed, nt, ns, rng, alpha): K = NumberField(alpha) if alpha is not None else NumberField([0, 1]) def draw(): - return K._reduce([Fraction(rng.randint(2, 40))] + [Fraction(rng.randint(-9, 9)) for _ in range(K.d - 1)]) \ - if K.d > 1 else (Fraction(rng.randint(2, 40)),) + return ( + K._reduce([Fraction(rng.randint(2, 40))] + [Fraction(rng.randint(-9, 9)) for _ in range(K.d - 1)]) + if K.d > 1 + else (Fraction(rng.randint(2, 40)),) + ) + # the states in K as well: identities of the balances can tie traces with a rational factor of the states - xs = {i: K.add(K.rational(Fraction(rng.randint(1, 30), rng.randint(1, 7))), - K._reduce([Fraction(0)] + [Fraction(rng.randint(-5, 5), rng.randint(1, 7)) for _ in range(K.d - 1)]) - if K.d > 1 else K.zero) for i in U} + xs = { + i: K.add( + K.rational(Fraction(rng.randint(1, 30), rng.randint(1, 7))), + K._reduce([Fraction(0)] + [Fraction(rng.randint(-5, 5), rng.randint(1, 7)) for _ in range(K.d - 1)]) + if K.d > 1 + else K.zero, + ) + for i in U + } vals = dict(xs) vals.update({i: K.rational(int(v)) for i, v in fixed.items()}) held = {} @@ -395,6 +439,7 @@ def at(m): for _ in range(e): out = K.mul(out, vals[j]) return out + # rows: sum_k A_ik theta_k = b_i over K rows = [] for i in U: @@ -477,7 +522,7 @@ def certificate(series, laws=()): for k in range(len(params)): v = spy.Integer(rng.randint(2, 40)) if alpha is not None: - v = v + sum(rng.randint(-9, 9) * a ** j for j in range(1, d)) + v = v + sum(rng.randint(-9, 9) * a**j for j in range(1, d)) theta[ns + k] = v # an equilibrium chosen first, the parameters solved, where the balances are linear in them lin = _linear_point(F, U, fixed, len(params), ns, rng, alpha) if nonzero else None @@ -496,16 +541,35 @@ def certificate(series, laws=()): if retry is not None: plan.insert(0, (retry, nonzero)) continue - out.update(_proven(K, {p: _text(K, tv[k]) for k, p in enumerate(params)}, alpha, spy.Symbol("s"), - fixed, reads, st, {names[j]: _text(K, xv[i]) for j, i in enumerate(U)}, laws, got, - t0)) + out.update( + _proven( + K, + {p: _text(K, tv[k]) for k, p in enumerate(params)}, + alpha, + spy.Symbol("s"), + fixed, + reads, + st, + {names[j]: _text(K, xv[i]) for j, i in enumerate(U)}, + laws, + got, + t0, + ) + ) return out # a level set of the laws, at random values level = [] for law in laws: - g = sum((model_sympify(str(c)).xreplace(series.known).xreplace( - {spy.Symbol(p): theta[ns + k] for k, p in enumerate(params)}) * spy.Symbol(f"z{U.index(st.index(x))}") - for x, c in law.items()), spy.Integer(0)) + g = sum( + ( + model_sympify(str(c)) + .xreplace(series.known) + .xreplace({spy.Symbol(p): theta[ns + k] for k, p in enumerate(params)}) + * spy.Symbol(f"z{U.index(st.index(x))}") + for x, c in law.items() + ), + spy.Integer(0), + ) level.append(spy.fraction(spy.together(g - rng.randint(2, 30)))[0]) found, why = _equilibria(F, U, fixed, theta, alpha, nonzero, level) if not found: @@ -536,8 +600,21 @@ def certificate(series, laws=()): continue al = spy.Symbol("alpha") point = {p: str(theta[ns + k].xreplace({a: al})).replace("**", "^") for k, p in enumerate(params)} - out.update(_proven(K, point, alpha, al, fixed, reads, st, - {names[j]: _text(K, xj) for j, xj in enumerate(x)}, laws, got, t0)) + out.update( + _proven( + K, + point, + alpha, + al, + fixed, + reads, + st, + {names[j]: _text(K, xj) for j, xj in enumerate(x)}, + laws, + got, + t0, + ) + ) return out out["why"] = last or "no equilibrium of the draws settles the test" out["seconds"] = round(time.monotonic() - t0, 2) diff --git a/src/symident/detection/forward.py b/src/symident/detection/forward.py index f8419ef..cbcfdab 100644 --- a/src/symident/detection/forward.py +++ b/src/symident/detection/forward.py @@ -126,9 +126,26 @@ def _fit_entry(primes, bankU_rows, reli_cols, mons, vals_of, vars_): return num_str if den_str == "1" else f"({num_str})/({den_str})" -def perprime_forward(f, sc, kcall, kcall_fwd, znames, z_slots, leaf_names, nz, scaling, - state_col_names, ctrl, phys_cols, models, real_state_names, solve_param_names, - solve_held, ac_in=None, list_anchors=False): +def perprime_forward( + f, + sc, + kcall, + kcall_fwd, + znames, + z_slots, + leaf_names, + nz, + scaling, + state_col_names, + ctrl, + phys_cols, + models, + real_state_names, + solve_param_names, + solve_held, + ac_in=None, + list_anchors=False, +): """Forward-sampling reconstruction of one residual direction over solved resting states.""" rprimes = all_primes() n_prime_fwd = max(2, min(3, len(rprimes) - 1)) @@ -222,9 +239,16 @@ def kx_f(pt, p, ac, sr): tsv = {s: ((i + 1) * 7919 + 11) % (P1 - 1) + 1 for i, s in enumerate(real_state_names)} tpv = {s: ((i + 1) * 104729 + 3) % (P1 - 1) + 1 for i, s in enumerate(solve_param_names)} try: - ts = solve_forward_modular(models[0], list(real_state_names), list(solve_param_names), tsv, - tpv, P1, forcings=list(solve_held) if solve_held else None, - keep_free=keep_free) + ts = solve_forward_modular( + models[0], + list(real_state_names), + list(solve_param_names), + tsv, + tpv, + P1, + forcings=list(solve_held) if solve_held else None, + keep_free=keep_free, + ) except SYMPY_FAILS as exc: sympy_fail(exc) ts = None @@ -262,7 +286,7 @@ def moved(lis, seed): return bool(np.any((v[phys_supp] - v0f[phys_supp]) % P1 != 0)) gsz = 8 - groups = [cand[i:i + gsz] for i in range(0, len(cand), gsz)] + groups = [cand[i : i + gsz] for i in range(0, len(cand), gsz)] single = [] for gi, g in enumerate(groups, start=1): m = (moved(g, 7919 * gi + 1), moved(g, 7919 * gi + 2)) @@ -288,8 +312,10 @@ def moved(lis, seed): return fb(f"forward: couples {len(union_rel)} leaves (entry up to {max_rel})") d_cap = max(1, min(3, int(ctrl["degree_cap"]))) - bank = {"U": np.zeros((0, len(union_rel)), dtype=np.int64), - "V": [np.zeros((0, nz), dtype=np.int64) for _ in primes]} + bank = { + "U": np.zeros((0, len(union_rel)), dtype=np.int64), + "V": [np.zeros((0, nz), dtype=np.int64) for _ in primes], + } def need_of(k, d): return 2 * mono_table(k, d).shape[0] + 20 @@ -315,8 +341,7 @@ def rec_entry(reli, c9): mons = mono_table(len(reli), d) if not fill_bank_to(need_of(len(reli), d)): continue - expr = _fit_entry(primes, bank["U"], reli_cols, mons, - lambda jp, need: bank["V"][jp][:need, c9], vars_) + expr = _fit_entry(primes, bank["U"], reli_cols, mons, lambda jp, need: bank["V"][jp][:need, c9], vars_) if expr is not None: return {"expr": expr, "reli": vars_} return None @@ -362,8 +387,13 @@ def rec_entry(reli, c9): pred = eval_modq(ex, env, qv) if pred is None or (pred - int(vver[col])) % qv != 0: return fb("forward: reconstructed direction failed fresh-point verification") - return {"support": sym_sort(list(entries)), "vector": entries, "type": "general", - "closed_form": True, "solved_rates": list(solve_rates)} + return { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "solved_rates": list(solve_rates), + } class SolveRates(list): @@ -381,10 +411,26 @@ def key(self): return tuple(self), tuple(self.state_solve) -def perprime_forward_shared(sc, kcall, kcall_fwd, znames, z_slots, leaf_names, nz, scaling, - state_col_names, ctrl, phys_cols, models, real_state_names, - solve_param_names, solve_held, kcall_fwd_sh=None, select_fn=None, - map_fn=None): +def perprime_forward_shared( + sc, + kcall, + kcall_fwd, + znames, + z_slots, + leaf_names, + nz, + scaling, + state_col_names, + ctrl, + phys_cols, + models, + real_state_names, + solve_param_names, + solve_held, + kcall_fwd_sh=None, + select_fn=None, + map_fn=None, +): """Every residual direction on the forward route: one transversal, one bank.""" rprimes = all_primes() n_prime_fwd = max(2, min(3, len(rprimes) - 1)) @@ -476,8 +522,7 @@ def kx_all(pt, p, acs, sr): for ac in acs: v0 = rr0["R"][piv0.index(ac)] % P1 nzv = [int(i) for i in np.nonzero(v0)[0]] - supp_of.append(list(dict.fromkeys(_strip_name(znames[i]) - for i in [ac] + [c for c in nzv if c != ac]))) + supp_of.append(list(dict.fromkeys(_strip_name(znames[i]) for i in [ac] + [c for c in nzv if c != ac]))) li = {nm: i for i, nm in enumerate(leaf_names)} def run_group(acs, supp_of, ts, n_p=1): @@ -495,13 +540,17 @@ def run_group(acs, supp_of, ts, n_p=1): base0, vb = cand, vs break if base0 is None: - return [{"support": sym_sort(sp), "type": "general", "closed_form": False, - "reason": "forward: no base"} for sp in supp_of] + return [ + {"support": sym_sort(sp), "type": "general", "closed_form": False, "reason": "forward: no base"} + for sp in supp_of + ] if select_fn is not None and kcall_fwd_sh is not None: select_fn(base0, P1, sc["nt_used"], solve_rates) v0f = vb[0] - phys_supp_of = [[int(c) for c in np.nonzero(v0f[a] % P1)[0] if int(c) in phys_set_s and int(c) != acs[a]] - for a in range(len(acs))] + phys_supp_of = [ + [int(c) for c in np.nonzero(v0f[a] % P1)[0] if int(c) in phys_set_s and int(c) != acs[a]] + for a in range(len(acs)) + ] solved = {li[r] for r in solve_rates if r in li} cand = [i for i in range(len(leaf_names)) if i not in solved] @@ -564,9 +613,11 @@ def changed_at(lis, seed): # draws every leaf of a wide direction rarely solves the resting balances local = len(union_rel) > fwd_cap_dir if rdiag: - print(f"[fwds] leaves per anchor {[len({x for r in rel_by[a] for x in r}) for a in range(len(acs))]}, " - f"entries up to {max((len(r) for rb in rel_by for r in rb), default=0)}, union " - f"{len(union_rel)}{' (banks per entry)' if local else ''}") + print( + f"[fwds] leaves per anchor {[len({x for r in rel_by[a] for x in r}) for a in range(len(acs))]}, " + f"entries up to {max((len(r) for rb in rel_by for r in rb), default=0)}, union " + f"{len(union_rel)}{' (banks per entry)' if local else ''}" + ) # an entry of a leaf solved from a resting balance has the degree of that balance plus one d_cap = max(1, min(4, int(ctrl["degree_cap"]))) @@ -575,8 +626,11 @@ def changed_at(lis, seed): def bank_of(reli): key = tuple(reli) if local else tuple(union_rel) if key not in banks: - banks[key] = {"cols": list(key), "U": np.zeros((0, len(key)), dtype=np.int64), - "V": [[] for _ in primes]} + banks[key] = { + "cols": list(key), + "U": np.zeros((0, len(key)), dtype=np.int64), + "V": [[] for _ in primes], + } return banks[key] def need_of(k, d): @@ -617,11 +671,14 @@ def rec_entry(a, reli, c9): mons = mono_table(len(reli), d) if not fill_bank_to(bank, need_of(len(reli), d)): if rdiag: - print(f"[fwds] entry {znames[c9]}: {len(reli)} leaves, degree {d}: bank of " - f"{len(bank['V'][0])} of {need_of(len(reli), d)} points") + print( + f"[fwds] entry {znames[c9]}: {len(reli)} leaves, degree {d}: bank of " + f"{len(bank['V'][0])} of {need_of(len(reli), d)} points" + ) continue - expr = _fit_entry(primes, bank["U"], reli_cols, mons, - lambda jp, need: val_of(bank, jp, a, c9, need), vars_) + expr = _fit_entry( + primes, bank["U"], reli_cols, mons, lambda jp, need: val_of(bank, jp, a, c9, need), vars_ + ) if expr is not None: return {"expr": expr, "reli": vars_} if rdiag: @@ -637,9 +694,10 @@ def rec_entry(a, reli, c9): break out = [] for a, ac in enumerate(acs): + def opn(reason, a=a): - return {"support": sym_sort(supp_of[a]), "type": "general", "closed_form": False, - "reason": reason} + return {"support": sym_sort(supp_of[a]), "type": "general", "closed_form": False, "reason": reason} + if not ok_a[a]: out.append(opn("forward: couples too many leaves")) continue @@ -689,8 +747,15 @@ def opn(reason, a=a): if bad: out.append(opn("forward: failed fresh-point verification")) continue - out.append({"support": sym_sort(list(entries)), "vector": entries, "type": "general", - "closed_form": True, "solved_rates": list(solve_rates)}) + out.append( + { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "solved_rates": list(solve_rates), + } + ) return out tsv = {s: ((i + 1) * 7919 + 11) % (P1 - 1) + 1 for i, s in enumerate(real_state_names)} @@ -700,10 +765,16 @@ def opn(reason, a=a): def trans_for(sp): kf = list(dict.fromkeys([x for s in sp for x in s] + recast_leaves)) try: - ts = solve_forward_modular(models[0], list(real_state_names), list(solve_param_names), - tsv, tpv, P1, - forcings=list(solve_held) if solve_held else None, - keep_free=kf) + ts = solve_forward_modular( + models[0], + list(real_state_names), + list(solve_param_names), + tsv, + tpv, + P1, + forcings=list(solve_held) if solve_held else None, + keep_free=kf, + ) except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -743,17 +814,30 @@ def groups_for(idx): for g in groups: gidx = g["idx"] if g["ts"] is None: - res = [{"support": sym_sort(supp_of[i]), "type": "general", "closed_form": False, - "reason": "forward: no transversal"} for i in gidx] + res = [ + { + "support": sym_sort(supp_of[i]), + "type": "general", + "closed_form": False, + "reason": "forward: no transversal", + } + for i in gidx + ] else: res = run_group([acs[i] for i in gidx], [supp_of[i] for i in gidx], g["ts"]) if res is None: - res = [{"support": sym_sort(supp_of[i]), "type": "general", "closed_form": False, - "reason": "forward: no closed form"} for i in gidx] + res = [ + { + "support": sym_sort(supp_of[i]), + "type": "general", + "closed_form": False, + "reason": "forward: no closed form", + } + for i in gidx + ] again = [k for k, e in enumerate(res) if not e.get("closed_form")] if again and g["ts"] is not None: - res2 = run_group([acs[gidx[k]] for k in again], [supp_of[gidx[k]] for k in again], - g["ts"], n_p=n_prime_fwd) + res2 = run_group([acs[gidx[k]] for k in again], [supp_of[gidx[k]] for k in again], g["ts"], n_p=n_prime_fwd) if res2 is not None: for j, k in enumerate(again): res[k] = res2[j] @@ -765,8 +849,7 @@ def groups_for(idx): for g in groups_for(again): if g["ts"] is None: continue - res = run_group([acs[i] for i in g["idx"]], [supp_of[i] for i in g["idx"]], g["ts"], - n_p=n_prime_fwd) + res = run_group([acs[i] for i in g["idx"]], [supp_of[i] for i in g["idx"]], g["ts"], n_p=n_prime_fwd) if res is not None: for k, i in enumerate(g["idx"]): if res[k].get("closed_form"): @@ -776,8 +859,10 @@ def groups_for(idx): if not e.get("closed_form"): print(f"[fwds] open: {e.get('reason')}") n_k = track["n_k"] - print(f"[fwds] closed {sum(1 for e in out if e.get('closed_form'))} of {len(out)} ({el()}; " - f"{n_k} kernel calls, {track['t_k'] / n_k if n_k else 0:.1f} s each)") + print( + f"[fwds] closed {sum(1 for e in out if e.get('closed_form'))} of {len(out)} ({el()}; " + f"{n_k} kernel calls, {track['t_k'] / n_k if n_k else 0:.1f} s each)" + ) return out @@ -789,18 +874,50 @@ def fwd_adopt(fwd, n_res): return cl if len(cl) == n_res and n_res > 0 else None -def perprime_forward_multi(residual_free, sc, kcall, kcall_fwd, znames, z_slots, leaf_names, nz, - scaling, state_col_names, ctrl, phys_cols, models, real_state_names, - solve_param_names, solve_held): +def perprime_forward_multi( + residual_free, + sc, + kcall, + kcall_fwd, + znames, + z_slots, + leaf_names, + nz, + scaling, + state_col_names, + ctrl, + phys_cols, + models, + real_state_names, + solve_param_names, + solve_held, +): """Forward results of the first residual direction per anchor; [] without directions, None without anchors.""" if not residual_free: return [] def fwd1(ac_in, list_anchors): - return perprime_forward(residual_free[0], sc, kcall, kcall_fwd, znames, z_slots, leaf_names, - nz, scaling, state_col_names, ctrl, phys_cols, models, - real_state_names, solve_param_names, solve_held, - ac_in=ac_in, list_anchors=list_anchors) + return perprime_forward( + residual_free[0], + sc, + kcall, + kcall_fwd, + znames, + z_slots, + leaf_names, + nz, + scaling, + state_col_names, + ctrl, + phys_cols, + models, + real_state_names, + solve_param_names, + solve_held, + ac_in=ac_in, + list_anchors=list_anchors, + ) + anchors = fwd1(None, True) if not anchors: return None diff --git a/src/symident/detection/gapcert.py b/src/symident/detection/gapcert.py index 86a7b46..02c3676 100644 --- a/src/symident/detection/gapcert.py +++ b/src/symident/detection/gapcert.py @@ -156,7 +156,7 @@ def rows(self, k): raise OverflowError("a Lie derivative grows past the size cap") self.orders.append([[spy.diff(g, w) for w in self.W] for g in self.jets]) self.jets = [_lie(g, self.F) for g in self.jets] - return [r for o in self.orders[:k + 1] for r in o] + return [r for o in self.orders[: k + 1] for r in o] def gap_bound(tapes, chains, znames, n_lie, p, rng, cap=None): @@ -170,16 +170,20 @@ def gap_bound(tapes, chains, znames, n_lie, p, rng, cap=None): def _gap_bound(tapes, chains, znames, n_lie, p, rng, cap): # a moving boundary shifts the series and the state at the event, which the family leaves out for c in chains: - if any(str(tapes[i].get("ver_time") or "").strip() and model_sympify(str(tapes[i]["ver_time"])).free_symbols - for i in c): + if any( + str(tapes[i].get("ver_time") or "").strip() and model_sympify(str(tapes[i]["ver_time"])).free_symbols + for i in c + ): return {"bound": None, "why": "an event time with a free symbol"} try: cs = [_Chain(tapes, c, n_lie, p, rng) for c in chains] except (OverflowError, LookupError, *SYMPY_FAILS) as exc: if not isinstance(exc, (OverflowError, LookupError)): sympy_fail(exc) - return {"bound": None, "why": str(exc) if isinstance(exc, LookupError) else - f"no symbolic family ({type(exc).__name__})"} + return { + "bound": None, + "why": str(exc) if isinstance(exc, LookupError) else f"no symbolic family ({type(exc).__name__})", + } zs = [spy.Symbol(z) for z in znames] zval = {z: spy.Integer(rng.randrange(2, p)) for z in zs} total, term, tdeg = [], 0, 0 @@ -226,8 +230,10 @@ def _gap_bound(tapes, chains, znames, n_lie, p, rng, cap): return {"bound": None, "why": "initial values that are not rational"} A = np.asarray(reach[1], dtype=object) B = np.asarray(Jv, dtype=object) - total += [[int(sum(int(a) * int(b) for a, b in zip(A[i], B[:, j])) % p) for j in range(len(zs))] - for i in range(A.shape[0])] + total += [ + [int(sum(int(a) * int(b) for a, b in zip(A[i], B[:, j])) % p) for j in range(len(zs))] + for i in range(A.shape[0]) + ] dr, dj = rows_degree(reach[0]), rows_degree([[e for r in J for e in r]]) tdeg = None if tdeg is None or dr is None or dj is None else max(tdeg, dr + dj) U = _rank(total, p) diff --git a/src/symident/detection/gauge.py b/src/symident/detection/gauge.py index c7b9dc0..edc66e9 100644 --- a/src/symident/detection/gauge.py +++ b/src/symident/detection/gauge.py @@ -24,9 +24,12 @@ def gauge_state(kernel, coords): N = np.asarray(kernel["N"], dtype=np.int64) p = kernel["p"] rr = _core.sym_rref_mod((N.T % p).astype(np.float64), p) - return {"R": np.asarray(rr["R"], dtype=np.float64).reshape(-1, N.shape[0]), - "piv": np.atleast_1d(rr["piv"]).astype(np.int64), "p": p, - "coords": list(kernel["coords"])} + return { + "R": np.asarray(rr["R"], dtype=np.float64).reshape(-1, N.shape[0]), + "piv": np.atleast_1d(rr["piv"]).astype(np.int64), + "p": p, + "coords": list(kernel["coords"]), + } def outside_span(W, chosen_idx): @@ -36,7 +39,7 @@ def outside_span(W, chosen_idx): A = W[:, chosen_idx] coef, *_ = np.linalg.lstsq(A, W, rcond=None) r = W - A @ coef - return np.sqrt((r ** 2).sum(axis=0)) > 1e-7 * np.maximum(1, np.sqrt((W ** 2).sum(axis=0))) + return np.sqrt((r**2).sum(axis=0)) > 1e-7 * np.maximum(1, np.sqrt((W**2).sum(axis=0))) def gauge_shape(kernel, coords, count=None): @@ -62,6 +65,7 @@ def shape(cs): free = np.atleast_1d(rr["piv"]) >= len(cs) cols = [i for i, c in enumerate(order) if count is None or c in set(count)] return [int(x) for x in (R[free][:, cols] != 0).sum(axis=1)] + return shape @@ -81,10 +85,8 @@ def gauge_suggest(syms, kernel, coordinates, fixed=()): with warnings.catch_warnings(): warnings.simplefilter("ignore") best = choose_gauge(scal, None, fixed=fixed, kernel=kernel) - plain = choose_gauge(scal, None, fixed=fixed, - avoid=list(dict.fromkeys(c for d in gen for c in _coords_of(d)))) - return {"gauge": best, "sizes": sorted(shape(best)), "plain": plain, - "plain_sizes": sorted(shape(plain))} + plain = choose_gauge(scal, None, fixed=fixed, avoid=list(dict.fromkeys(c for d in gen for c in _coords_of(d)))) + return {"gauge": best, "sizes": sorted(shape(best)), "plain": plain, "plain_sizes": sorted(shape(plain))} def choose_gauge(scal, pref, avoid=(), fixed=(), kernel=None): @@ -117,8 +119,7 @@ def choose_gauge(scal, pref, avoid=(), fixed=(), kernel=None): break top = min(pref_rank[j] for j in ok) cand = [coords[j] for j in ok if pref_rank[j] == top] - score = _core.sym_gauge_scores(st["R"], st["piv"], st["p"], - [st["coords"].index(c) for c in cand]) + score = _core.sym_gauge_scores(st["R"], st["piv"], st["p"], [st["coords"].index(c) for c in cand]) k = cand[int(np.argmin(np.asarray(score)))] fx = _core.sym_gauge_fix(st["R"], st["piv"], st["p"], st["coords"].index(k)) st["R"] = np.asarray(fx["R"], dtype=np.float64) @@ -132,14 +133,17 @@ def choose_gauge(scal, pref, avoid=(), fixed=(), kernel=None): if len(chosen) == W.shape[0]: break if len(chosen) < W.shape[0]: - warnings.warn(f"the scaling weights have rank {len(chosen)} for " - f"{W.shape[0]} scalings; the gauge fixes {len(chosen)}.", stacklevel=2) + warnings.warn( + f"the scaling weights have rank {len(chosen)} for {W.shape[0]} scalings; the gauge fixes {len(chosen)}.", + stacklevel=2, + ) return chosen def gauged_detection(args, pref, fixed, reconstruct): """Scalings first, then the general directions in a gauge of the scalings.""" from .core import symmetry_detection + args = dict(args, gauge_preference=False) t0 = time.monotonic() a1 = dict(args, reconstruct=False) @@ -147,25 +151,39 @@ def gauged_detection(args, pref, fixed, reconstruct): s1 = symmetry_detection(**a1) def split(s): - return ([d for d in s["symmetries"] if d["type"] == "scaling"], - [d for d in s["symmetries"] if d["type"] != "scaling"]) + return ( + [d for d in s["symmetries"] if d["type"] == "scaling"], + [d for d in s["symmetries"] if d["type"] != "scaling"], + ) + scal, gen = split(s1) - if not _settled(s1["info"]) and not s1["info"].get("lie_certified") and \ - (not (gen and reconstruct) or s1["info"].get("stacked")): + if ( + not _settled(s1["info"]) + and not s1["info"].get("lie_certified") + and (not (gen and reconstruct) or s1["info"].get("stacked")) + ): with state.options(keep_kernel=True, stacked_first=False): s1 = symmetry_detection(**a1) scal, gen = split(s1) - gauge = choose_gauge(scal, pref, avoid=list(dict.fromkeys(s for d in gen for s in d["support"])), - fixed=list(fixed or []), kernel=s1["info"]["kernel"] if gen else None) + gauge = choose_gauge( + scal, + pref, + avoid=list(dict.fromkeys(s for d in gen for s in d["support"])), + fixed=list(fixed or []), + kernel=s1["info"]["kernel"] if gen else None, + ) if pref and gen: coords_i = list(s1["info"]["coordinates"]) shape = gauge_shape(s1["info"]["kernel"], coords_i, count=coords_i) sug = gauge_suggest(s1["symmetries"], s1["info"]["kernel"], coords_i, fixed=list(fixed or [])) if shape is not None and sug is not None and max(shape(gauge) or [0]) > max(sug["sizes"] or [0]): - warnings.warn(f"the preferred gauge ({', '.join(gauge)}) leaves " - f"general directions on up to {max(shape(gauge))} coordinates; fixing " - f"{', '.join(sug['gauge'])} leaves at most {max(sug['sizes'])}, which " - "reduce() handles faster.", stacklevel=2) + warnings.warn( + f"the preferred gauge ({', '.join(gauge)}) leaves " + f"general directions on up to {max(shape(gauge))} coordinates; fixing " + f"{', '.join(sug['gauge'])} leaves at most {max(sug['sizes'])}, which " + "reduce() handles faster.", + stacklevel=2, + ) res = s1 s1info = dict(s1["info"]) res["info"] = dict(s1info, kernel=None, sat_score=None, stacked=None) @@ -174,13 +192,17 @@ def split(s): s1ok = bool(s1info.get("lie_certified")) or _settled(s1info) hint = None if s1info.get("lie_block_orders"): - hint = {"block_orders": [int(x) for x in s1info["lie_block_orders"]], - "nt_used": int(s1info["lie_order_used"]), "sat_score": s1info.get("sat_score"), - "Mtot": int(s1info.get("gap_order_used") or 0), "certified": s1ok, - "order_bound": s1info.get("order_bound"), - "order_bound_why": s1info.get("order_bound_why"), - "order_draws": s1info.get("order_draws"), - "gap_stop": "full" if s1info.get("gap_certified") else "plateau"} + hint = { + "block_orders": [int(x) for x in s1info["lie_block_orders"]], + "nt_used": int(s1info["lie_order_used"]), + "sat_score": s1info.get("sat_score"), + "Mtot": int(s1info.get("gap_order_used") or 0), + "certified": s1ok, + "order_bound": s1info.get("order_bound"), + "order_bound_why": s1info.get("order_bound_why"), + "order_draws": s1info.get("order_draws"), + "gap_stop": "full" if s1info.get("gap_certified") else "plateau", + } with state.options(order_hint=hint): s2 = symmetry_detection(**a2) res["symmetries"] = scal + s2["symmetries"] @@ -216,6 +238,9 @@ def _joint_bound(b1, b2): for b in (b1, b2): if b.get("probability") is None: return b - return dict(b2, probability=float(min(1.0, b1["probability"] + b2["probability"])), - degree=max(int(b1.get("degree") or 0), int(b2.get("degree") or 0)), - draws=max(int(b1.get("draws") or 0), int(b2.get("draws") or 0))) + return dict( + b2, + probability=float(min(1.0, b1["probability"] + b2["probability"])), + degree=max(int(b1.get("degree") or 0), int(b2.get("degree") or 0)), + draws=max(int(b1.get("draws") or 0), int(b2.get("draws") or 0)), + ) diff --git a/src/symident/detection/groups.py b/src/symident/detection/groups.py index 6995e7e..173cb3a 100644 --- a/src/symident/detection/groups.py +++ b/src/symident/detection/groups.py @@ -44,6 +44,7 @@ def mul(z, r, v): z[r] = z[r] % P * aval % P z[v] = z[v] % P * ainv % P return z + moves = {"add": add, "mul": mul} nt = sc["nt_used"] @@ -53,6 +54,7 @@ def outcome(o): def same(a, b): return a is not None and b is not None and a[0] == b[0] and np.array_equal(a[1], b[1]) + def shift(z, v): z = z.copy() z[v] += tval @@ -62,6 +64,7 @@ def scale(z, v): z = z.copy() z[v] = z[v] % P * aval % P return z + single = {"add": shift, "mul": scale} at_z1 = outcome(kb_s([z1], [P], nt)[0]) groups = [] @@ -71,13 +74,12 @@ def scale(z, v): todo = [x for x in relevant if x not in grouped] # leaves that enter only through their sum (product) give the same kernel when either alone # is shifted (scaled): only pairs with the same such signature are tested - sig = [outcome(o) for o in kb_s([single[type_](z1, v) for v in todo], [P] * len(todo), nt)] \ - if todo else [] + sig = [outcome(o) for o in kb_s([single[type_](z1, v) for v in todo], [P] * len(todo), nt)] if todo else [] sig = dict(zip(todo, sig)) # one kernel call per block against every possible representative; the greedy # assignment replays in order for start in range(0, len(todo), _BLOCK): - block = todo[start:start + _BLOCK] + block = todo[start : start + _BLOCK] keys = [(r, v) for i, v in enumerate(block) for r in reps + block[:i] if same(sig[r], sig[v])] outs = kb_s([mv(z1, r, v) for r, v in keys], [P] * len(keys), nt) if keys else [] got = {k: outcome(o) for k, o in zip(keys, outs)} @@ -97,6 +99,7 @@ def scale(z, v): def shift_groups(vec, groups, leaf_names, point0): """Entries fitted with group members held at the base point, mapped back to the groups.""" import sympy as spy + taken = set(vec) | set(leaf_names) U = [] for k in range(len(groups)): diff --git a/src/symident/detection/hybrid.py b/src/symident/detection/hybrid.py index 46c9b10..8415c36 100644 --- a/src/symident/detection/hybrid.py +++ b/src/symident/detection/hybrid.py @@ -27,6 +27,7 @@ def _sym(x): def _parse(text): """A model string (R syntax) as a sympy expression.""" from ..sym.switching import _plain + return _plain(str(text)).xreplace(CONSTS) @@ -136,8 +137,9 @@ def __init__(self, hy, kw, regimes=None): if self.unknown: self._check_unknown() # the clock where a condition's model reads time - self.clock = any(TIME in cd.apply(e).free_symbols for cd in self.conds for e in self.f.values()) or \ - any(TIME in e.free_symbols for cd in self.conds for e in cd.obs.values()) + self.clock = any(TIME in cd.apply(e).free_symbols for cd in self.conds for e in self.f.values()) or any( + TIME in e.free_symbols for cd in self.conds for e in cd.obs.values() + ) exprs = list(self.f.values()) + [e for x in hy.g for e in x.values()] + list(self.sw.funcs) for cd in self.conds: exprs += [e for e in cd.ic.values() if e is not None] + list(cd.obs.values()) @@ -160,8 +162,7 @@ def _check_unknown(self): if hit: raise HybridError(f"a switch on the unknown input {hit[0]} ({self.hy.surface(j)}) is not supported") if self.root_events or any(not e["t0"] for cd in self.conds for e in cd.events): - raise HybridError("unknown inputs together with switches and events after the start are not " - "supported yet") + raise HybridError("unknown inputs together with switches and events after the start are not supported yet") seen = {} for cd in self.conds: vals = [v for v in cd.ic.values() if v is not None] + [e["value"] for e in cd.events] @@ -173,16 +174,17 @@ def _check_unknown(self): seen.setdefault(str(u), []).append(cd.name) shared = sorted(u for u, c in seen.items() if len(c) > 1) if shared: - raise HybridError(f"the unknown input {shared[0]} enters several conditions; with switches each " - "condition needs an input of its own, renamed in `conditions`") + raise HybridError( + f"the unknown input {shared[0]} enters several conditions; with switches each " + "condition needs an input of its own, renamed in `conditions`" + ) def _conditions(self): kw, hy = self.kw, self.hy grid = Grid.from_any(kw.get("conditions")) trafo = kw.get("trafo") tlist = isinstance(trafo, (list, tuple)) - K = max(1, grid.nrow if grid is not None else 0, len(trafo) if tlist else 0, - len(hy.g) if hy.g_list else 0) + K = max(1, grid.nrow if grid is not None else 0, len(trafo) if tlist else 0, len(hy.g) if hy.g_list else 0) names = list(grid.rows) if grid is not None else [str(i + 1) for i in range(K)] self.grid = grid states = set(self.f) @@ -203,6 +205,7 @@ def _conditions(self): def app(e, t_sub=t_sub, gp=gp): return spy.sympify(e).xreplace(t_sub).xreplace(gp) + cd.apply = app ic = {} for x in self.dyn: @@ -227,15 +230,23 @@ def app(e, t_sub=t_sub, gp=gp): vv = grid.cell(c, vv) T = app(_parse(tv)) # an event value reads the clock at the event time - cd.events.append({"var": e["var"], "time": T, "value": app(_parse(vv)).xreplace({TIME: T}), - "method": e["method"], "index": i}) + cd.events.append( + { + "var": e["var"], + "time": T, + "value": app(_parse(vv)).xreplace({TIME: T}), + "method": e["method"], + "index": i, + } + ) cd.equil = self.equilibrate cd.roots = [r for r in hy.roots if _applies(r["event"], c)] cd.root_events = [r["event"] for r in cd.roots] conds.append(cd) # the start: 0, or the earliest event time that is a number in a condition - self.t0e = min([_rational(e["time"]) for cd in conds for e in cd.events if e["time"].is_number] + - [spy.Integer(0)]) + self.t0e = min( + [_rational(e["time"]) for cd in conds for e in cd.events if e["time"].is_number] + [spy.Integer(0)] + ) self.t0 = float(self.t0e) for cd in conds: for e in cd.events: @@ -259,8 +270,8 @@ def gfun(self, cd, j): def _regimes(self): """(kept, dropped) sign patterns of the switches; dropped ones contradict a declared sign in every condition.""" m = len(self.sw.funcs) - if 2 ** m > _MAX_REGIMES: - raise HybridError(f"the switches give {2 ** m} sign patterns, more than {_MAX_REGIMES}") + if 2**m > _MAX_REGIMES: + raise HybridError(f"the switches give {2**m} sign patterns, more than {_MAX_REGIMES}") per = [] for cd in self.conds: rules = set() @@ -299,7 +310,7 @@ def _declarations(self, regimes): def _sides_of(self, entry): """{surface: side} of one entry of `regimes`.""" out = {} - for txt in ([entry] if isinstance(entry, str) else list(entry)): + for txt in [entry] if isinstance(entry, str) else list(entry): d, side = comparison(txt) hit = self.sw.match(d) if hit is None: @@ -326,19 +337,26 @@ def _select(self, cd, decl): for pick in picks: hit = [r for r in self.regimes if all(r[j] == v for j, v in pick.items())] if not hit: - raise HybridError(f"condition {cd.name}: `regimes` names no feasible regime " - f"with {', '.join(self.hy.text(j, v) for j, v in pick.items())}") + raise HybridError( + f"condition {cd.name}: `regimes` names no feasible regime " + f"with {', '.join(self.hy.text(j, v) for j, v in pick.items())}" + ) cd.regimes += [r for r in hit if r not in cd.regimes] self._check_start(cd, picks[0]) - cd.surfaces = [j for j in range(len(self.sw.funcs)) - if {r[j] for r in cd.regimes} == {1, -1} or j in {r["surface"] for r in cd.roots}] + cd.surfaces = [ + j + for j in range(len(self.sw.funcs)) + if {r[j] for r in cd.regimes} == {1, -1} or j in {r["surface"] for r in cd.roots} + ] # no trajectory crosses a surface in the parameters alone moving = {_sym(x) for x in self.f} | {TIME} for j in cd.surfaces: if not self.gfun(cd, j).free_symbols & moving: - raise HybridError(f"condition {cd.name}: the switch on {self.hy.surface(j)} depends on " - f"parameters only, so no trajectory crosses it; name the side with " - f"`regimes`, for instance regimes=[{self.hy.text(j, 1)!r}]") + raise HybridError( + f"condition {cd.name}: the switch on {self.hy.surface(j)} depends on " + f"parameters only, so no trajectory crosses it; name the side with " + f"`regimes`, for instance regimes=[{self.hy.text(j, 1)!r}]" + ) def _check_start(self, cd, pick): """Check the declared start against the initial values and record the sides they leave undecided.""" @@ -356,9 +374,11 @@ def _check_start(self, cd, pick): g = self.gfun(cd, j).xreplace(x0) d = None if g.free_symbols & dyn else self.sw.sign_of(g) if d is not None and d != side: - raise HybridError(f"condition {cd.name}: `regimes` starts in " - f"{self.hy.text(j, side)}, but the initial values give " - f"{self.hy.text(j, d) if d else self.hy.surface(j)}") + raise HybridError( + f"condition {cd.name}: `regimes` starts in " + f"{self.hy.text(j, side)}, but the initial values give " + f"{self.hy.text(j, d) if d else self.hy.surface(j)}" + ) if d is None: cd.declared.append(f"{self.hy.text(j, side)} at the start") @@ -394,8 +414,7 @@ def visibility(self, cd, j): fa, ha = self.model(cd, a) fb, hb = self.model(cd, b) reach = self._reach(cd, (a, b)) - if all(is_zero(ha[y] - hb[y]) for y in ha) and \ - all(is_zero(fa[x] - fb[x]) for x in reach): + if all(is_zero(ha[y] - hb[y]) for y in ha) and all(is_zero(fa[x] - fb[x]) for x in reach): verdicts.append(_INVISIBLE) continue seen = sol is not None and self._jets_differ(fa, fb, ha, hb, sol) @@ -408,8 +427,9 @@ def _jets_differ(self, fa, fb, ha, hb, sol): """Whether the observable jets differ between the regimes at a seeded point of the surface, modulo a prime.""" syms = set().union(*[e.free_symbols for m in (fa, fb, ha, hb) for e in m.values()]) # a surface symbol that no expression contains does not enter the key - key = tuple(tuple(sorted((str(k), str(v)) for k, v in m.items())) for m in (fa, fb, ha, hb)) + \ - ((str(sol[0]), str(sol[1])) if sol[0] in syms else ()) + key = tuple(tuple(sorted((str(k), str(v)) for k, v in m.items())) for m in (fa, fb, ha, hb)) + ( + (str(sol[0]), str(sol[1])) if sol[0] in syms else () + ) memo = self.__dict__.setdefault("_jet_memo", {}) if key in memo: return memo[key] @@ -431,8 +451,11 @@ def _jets_differ(self, fa, fb, ha, hb, sol): while True: va = output_series({_sym(k): v for k, v in fa.items()}, [ha[y] for y in ys], pt, n, p) vb = output_series({_sym(k): v for k, v in fb.items()}, [hb[y] for y in ys], pt, n, p) - seen = any(x != y for A, B, c in zip(va, vb, caps) - for x, y in list(zip(A, B))[:None if c is None else c + 1]) + seen = any( + x != y + for A, B, c in zip(va, vb, caps) + for x, y in list(zip(A, B))[: None if c is None else c + 1] + ) if seen or n >= order: break n = min(order, 2 * n) @@ -461,8 +484,11 @@ def text(self, sides): def on_surface(self, cd, j): """Surface j solved for a symbol in which it is linear, states first: (symbol, value).""" g = self.gfun(cd, j) - prefer = [_sym(x) for x in self.dyn] + ([TIME] if TIME in g.free_symbols else []) + \ - sorted(g.free_symbols - {_sym(x) for x in self.f} - {TIME}, key=str) + prefer = ( + [_sym(x) for x in self.dyn] + + ([TIME] if TIME in g.free_symbols else []) + + sorted(g.free_symbols - {_sym(x) for x in self.f} - {TIME}, key=str) + ) return solve_linear(g, prefer) @@ -516,11 +542,13 @@ def _copies(st, names=None): first = len(copies) for sides in cd.regimes: # a resting start is each closed-form resting state of the regime - starts = [dict(cd.ic)] if not cd.equil else \ - [{x: s[_sym(x)] for x in st.dyn} for s in _steady_states(st, cd, sides)] + starts = ( + [dict(cd.ic)] + if not cd.equil + else [{x: s[_sym(x)] for x in st.dyn} for s in _steady_states(st, cd, sides)] + ) for ic in starts: - copies += _switched({"cd": cd, "sides": sides, "ic": ic, "events": True, - "obs": {}, "time": st.t0e}, st) + copies += _switched({"cd": cd, "sides": sides, "ic": ic, "events": True, "obs": {}, "time": st.t0e}, st) points = [] for j in cd.surfaces: g = st.gfun(cd, j) @@ -565,18 +593,27 @@ def _copies(st, names=None): pt[v] = _compose(pt[v], ev.get("method", "replace"), cd.apply(_parse(ev["value"])).xreplace(pt)) ic = {x: pt[_sym(x)] for x in st.dyn} for sides in cd.regimes: - copies += _switched({"cd": cd, "sides": sides, "ic": ic, "events": False, "obs": {}, - "time": tsym if tsym is not None else st.t0e, - "inputs": {u: pt[_sym(u)] for u in st.inputs}, "surface": on, - "block": tuple(mine)}, st) + copies += _switched( + { + "cd": cd, + "sides": sides, + "ic": ic, + "events": False, + "obs": {}, + "time": tsym if tsym is not None else st.t0e, + "inputs": {u: pt[_sym(u)] for u in st.inputs}, + "surface": on, + "block": tuple(mine), + }, + st, + ) return copies, fresh def _jet_chains(st, order, names): """{input: [input, jets of the input]} of the unknown inputs the model reads, `order` names each.""" # in a condition that renames an input the chain stands for the new name - read = set().union(*[e.free_symbols for e in st.f.values()], - *[e.free_symbols for g in st.hy.g for e in g.values()]) + read = set().union(*[e.free_symbols for e in st.f.values()], *[e.free_symbols for g in st.hy.g for e in g.values()]) return {w: [w] + [names(f"{w}_d{k}") for k in range(1, order)] for w in st.unknown if _sym(w) in read} @@ -588,6 +625,7 @@ def new(x): nm = names(f"{x}_si") fresh[nm] = x return _sym(nm) + for cp in copies: own = (id(cp["ic"]), tuple(cp["sides"])) if own not in starts: @@ -619,8 +657,9 @@ def _uncovered(st, copies): for cd in st.conds: own = [c for c in copies if c["cd"] is cd] starts = [c["sides"] for c in own if c.get("switch") is None and c.get("events", True)] - into = [c["switch"][1] for c in own if c.get("switch") is not None] + \ - [c["sides"] for c in own if st.unknown and not c.get("events", True)] + into = [c["switch"][1] for c in own if c.get("switch") is not None] + [ + c["sides"] for c in own if st.unknown and not c.get("events", True) + ] for r in cd.regimes: if r not in starts: out.append((cd.name, list(r), "start")) @@ -697,8 +736,9 @@ def _rows_model(st, copies, fresh, jets=None, jet_fresh=None, order=0): tr.update({x: _core_text(v) for x, v in (cp.get("jets") or {}).items()}) for u, v in (cp.get("inputs") or {}).items(): # an input starts at zero; an event at the start sets it - events.append({"var": u, "time": _core_text(st.t0e), "value": _core_text(v), "method": "replace", - "cond": [i]}) + events.append( + {"var": u, "time": _core_text(st.t0e), "value": _core_text(v), "method": "replace", "cond": [i]} + ) if st.clock: tr["time"] = _core_text(cp["time"]) trafos.append(tr) @@ -706,29 +746,67 @@ def _rows_model(st, copies, fresh, jets=None, jet_fresh=None, order=0): o.update({k: _core_text(v) for k, v in cp["obs"].items()}) obs.append(o) for e in evs: - events.append({"var": e["var"], "time": _core_text(e["time"]), "value": _core_text(e["value"]), - "method": e["method"], "cond": [i]}) + events.append( + { + "var": e["var"], + "time": _core_text(e["time"]), + "value": _core_text(e["value"]), + "method": e["method"], + "cond": [i], + } + ) if cp.get("switch") is not None: ts, other = cp["switch"] # an event at the start keeps the clock origin at t0 for the switch time - events.append({"var": st.hy.names[0], "time": _core_text(st.t0e), - "value": "1" if cp["sides"][0] > 0 else "0", "method": "replace", - "cond": [i]}) + events.append( + { + "var": st.hy.names[0], + "time": _core_text(st.t0e), + "value": "1" if cp["sides"][0] > 0 else "0", + "method": "replace", + "cond": [i], + } + ) for j, h in enumerate(st.hy.names): if other[j] != cp["sides"][j]: - events.append({"var": h, "time": _core_text(ts), - "value": "1" if other[j] > 0 else "0", "method": "replace", - "cond": [i]}) - kw.update(f=f, g=obs, trafo=trafos, conditions={"rows": rows, "cols": cols}, - events=events or None, reconstruct=True, reactions=None, totals=None, - equilibrate=False, unknown_inputs=None) + events.append( + { + "var": h, + "time": _core_text(ts), + "value": "1" if other[j] > 0 else "0", + "method": "replace", + "cond": [i], + } + ) + kw.update( + f=f, + g=obs, + trafo=trafos, + conditions={"rows": rows, "cols": cols}, + events=events or None, + reconstruct=True, + reactions=None, + totals=None, + equilibrate=False, + unknown_inputs=None, + ) if jets: - kw["nuisance"] = {"states": list(jet_fresh), "kept": [], "tops": [], "exact_order": int(order) - 1, - "prolonged": False, "jet_states": [], "starts": dict(jet_fresh)} + kw["nuisance"] = { + "states": list(jet_fresh), + "kept": [], + "tops": [], + "exact_order": int(order) - 1, + "prolonged": False, + "jet_states": [], + "starts": dict(jet_fresh), + } pos = st.positive if pos not in (True, False): - pos = list(pos or []) + [n for n in fresh if n.startswith("si_time") or - any(n.startswith(f"{x}_si") and x in set(pos or []) for x in st.f)] + pos = list(pos or []) + [ + n + for n in fresh + if n.startswith("si_time") or any(n.startswith(f"{x}_si") and x in set(pos or []) for x in st.f) + ] kw["positive"] = pos return kw @@ -748,8 +826,10 @@ def _steady_states(st, cd, sides): sol = [] sol = [s for s in sol if set(s) == {_sym(x) for x in st.dyn}] if not sol: - raise HybridError(f"condition {cd.name}: a resting state of a regime has no closed form, " - "so a symmetry cannot be certified on it") + raise HybridError( + f"condition {cd.name}: a resting state of a regime has no closed form, " + "so a symmetry cannot be certified on it" + ) return sol @@ -797,20 +877,37 @@ def regular(e, sub): if r is None: r = memo[key] = _regular_zero(e, sub) return r + zs = {x for x, v in _start_values(st, cd).items() if v is not None and is_zero(v)} fields = [st.model(cd, r)[0] for r in cd.regimes] - later = [(e["var"], e["method"], e["value"]) for e in cd.events if not e["t0"]] + \ - [(str(e["var"]), e.get("method", "replace"), cd.apply(_parse(e["value"]))) for e in cd.root_events] + later = [(e["var"], e["method"], e["value"]) for e in cd.events if not e["t0"]] + [ + (str(e["var"]), e.get("method", "replace"), cd.apply(_parse(e["value"]))) for e in cd.root_events + ] # a state is checked again only when a state named in the right-hand sides or later events # of the checked state has left the set - uses = {x: {str(s) for e in [f[x] for f in fields] + [v for var, _, v in later if var == x] - for s in spy.sympify(e).free_symbols} for x in zs} + uses = { + x: { + str(s) + for e in [f[x] for f in fields] + [v for var, _, v in later if var == x] + for s in spy.sympify(e).free_symbols + } + for x in zs + } check = set(zs) while check: sub = {_sym(x): spy.Integer(0) for x in zs} - drop = {x for x in check if not (all(regular(f[x], sub) for f in fields) and - all(is_zero(_compose(spy.Integer(0), m, spy.sympify(v).xreplace(sub))) for var, m, v in later - if var == x))} + drop = { + x + for x in check + if not ( + all(regular(f[x], sub) for f in fields) + and all( + is_zero(_compose(spy.Integer(0), m, spy.sympify(v).xreplace(sub))) + for var, m, v in later + if var == x + ) + ) + } zs -= drop check = {x for x in zs if uses[x] & drop} return zs @@ -828,11 +925,15 @@ def zero_restriction(hy, kw, regimes=None): def why(z): if regimes is not None: return "`regimes` is declared" - return "the reactions, totals or conditions keep them in the model" if z & shared else \ - "not in every condition" - notes = [f"condition {n}: {', '.join(sorted(z - common))} start at zero and stay at zero there, but " - + why(z) + "; the switched copies of that condition start at any point of the surface" - for n, z in per.items() if z - common] + return "the reactions, totals or conditions keep them in the model" if z & shared else "not in every condition" + + notes = [ + f"condition {n}: {', '.join(sorted(z - common))} start at zero and stay at zero there, but " + + why(z) + + "; the switched copies of that condition start at any point of the surface" + for n, z in per.items() + if z - common + ] return kw2, sorted(common), notes, st @@ -859,14 +960,23 @@ def z(t): def m(d): return None if d is None else {str(k): z(v) for k, v in dict(d).items() if str(k) not in drop} + g, tr = kw.get("g"), kw.get("trafo") - events = [{k: z(v) if k in ("time", "value", "root") else v for k, v in e.items()} - for e in as_events(kw.get("events")) or [] if str(e["var"]) not in drop] + events = [ + {k: z(v) if k in ("time", "value", "root") else v for k, v in e.items()} + for e in as_events(kw.get("events")) or [] + if str(e["var"]) not in drop + ] pos = kw.get("positive", True) - return dict(kw, f=m(kw["f"]), g=[m(x) for x in g] if isinstance(g, (list, tuple)) else m(g), - trafo=[m(x) for x in tr] if isinstance(tr, (list, tuple)) else m(tr), conditions=cond, - events=events or None, - positive=pos if pos in (True, False) else [x for x in pos or [] if str(x) not in drop]) + return dict( + kw, + f=m(kw["f"]), + g=[m(x) for x in g] if isinstance(g, (list, tuple)) else m(g), + trafo=[m(x) for x in tr] if isinstance(tr, (list, tuple)) else m(tr), + conditions=cond, + events=events or None, + positive=pos if pos in (True, False) else [x for x in pos or [] if str(x) not in drop], + ) def _coords(st): @@ -946,15 +1056,15 @@ def _bracket(st, X, f): out[k] = -sum((spy.diff(comp, s) * f[str(s)] for s in sx), spy.Integer(0)) for x in st.f: comp = X.get(_sym(x), spy.Integer(0)) - out[_sym(x)] = _apply(X, f[x]) - sum((spy.diff(comp, s) * f[str(s)] for s in sx), - spy.Integer(0)) + out[_sym(x)] = _apply(X, f[x]) - sum((spy.diff(comp, s) * f[str(s)] for s in sx), spy.Integer(0)) return out def _events_of(st, cd): - return [e for e in cd.events if not e["t0"]] + \ - [{"var": e["var"], "time": None, "value": cd.apply(_parse(e["value"])), - "method": e.get("method", "replace")} for e in cd.root_events] + return [e for e in cd.events if not e["t0"]] + [ + {"var": e["var"], "time": None, "value": cd.apply(_parse(e["value"])), "method": e.get("method", "replace")} + for e in cd.root_events + ] def _starts(st, cd): @@ -998,8 +1108,7 @@ def certify_fields(st, cands, why=None): def _family(st, cd, cands, alive, why): - keys = sorted({_sym(z) for i in alive for z in cands[i].theta} | - {_sym(x) for x in st.f}, key=str) + keys = sorted({_sym(z) for i in alive for z in cands[i].theta} | {_sym(x) for x in st.f}, key=str) fam = [] for i in alive: # an input change follows from the brackets below @@ -1029,6 +1138,7 @@ def local(X): if e["time"] is not None and not is_zero(_apply(X, e["time"])): return "it moves an event time" return None + while True: kept = [] for i, X in fam: @@ -1048,7 +1158,7 @@ def local(X): if sol is None: drop = (k, "the regimes do not leave the span invariant") break - changes[k, r] = dict(zip(drives[r], sol[len(vecs):])) + changes[k, r] = dict(zip(drives[r], sol[len(vecs) :])) if drop is None: for e in evs: post = _post(e) @@ -1079,8 +1189,9 @@ def local(X): at = [{k: spy.sympify(v).xreplace(x0) for k, v in Y.items()} for Y in vecs] v0 = {k: spy.sympify(v).xreplace(x0) for k, v in X.items() if str(k) not in st.f} for x in st.dyn: - v0[_sym(x)] = _apply(X, x0[_sym(x)]) if x0[_sym(x)] != _sym(x) else \ - spy.sympify(X.get(_sym(x), 0)).xreplace(x0) + v0[_sym(x)] = ( + _apply(X, x0[_sym(x)]) if x0[_sym(x)] != _sym(x) else spy.sympify(X.get(_sym(x), 0)).xreplace(x0) + ) if _span(at, v0, keys) is None: ok = False break @@ -1160,8 +1271,9 @@ def _hidden_jumps(st, cd, fam, keys, surf): if cd.vis[j] == _VISIBLE: continue g, sol = surf[j] - moving = [k for k, (_, X) in enumerate(fam) - if sol is None or not is_zero(_apply(X, g).xreplace({sol[0]: sol[1]}))] + moving = [ + k for k, (_, X) in enumerate(fam) if sol is None or not is_zero(_apply(X, g).xreplace({sol[0]: sol[1]})) + ] if not moving: continue rep = {} if sol is None else {sol[0]: sol[1]} @@ -1174,8 +1286,7 @@ def _hidden_jumps(st, cd, fam, keys, surf): fb, hb = st.model(cd, b) jump = {_sym(x): (fa[x] - fb[x]).xreplace(rep) for x in st.f} at = [{k: spy.sympify(v).xreplace(rep) for k, v in Y.items()} for Y in vecs] - if any(not is_zero((ha[y] - hb[y]).xreplace(rep)) for y in ha) or \ - _span(at, jump, keys) is None: + if any(not is_zero((ha[y] - hb[y]).xreplace(rep)) for y in ha) or _span(at, jump, keys) is None: cand = [k for k in moving if fam[k][0] is not None] k = cand[0] if cand else moving[0] return k, f"it moves the surface {st.hy.surface(j)}, whose switch it would see" @@ -1213,8 +1324,6 @@ def _rank_at_point(rows): return None - - def _scaling_candidates(st): """Scalings the integer kernel proposes over every regime, constrained by surfaces, initial values, events.""" models, obs, xm, xo = [], [], [], [] @@ -1224,8 +1333,10 @@ def _scaling_candidates(st): v = cd.ic.get(x) if v is not None and not cd.equil: cons_m.append(f"{x} = {to_str(v)}") - resets = [{"var": r["var"], "time": None, "method": r.get("method", "replace"), - "value": cd.apply(_parse(r["value"]))} for r in cd.root_events] + resets = [ + {"var": r["var"], "time": None, "method": r.get("method", "replace"), "value": cd.apply(_parse(r["value"]))} + for r in cd.root_events + ] for e in list(cd.events) + resets: if e["var"] in st.inputs or e["method"] == "multiply": cons_o.append(f"_ = {to_str(e['value'])}") @@ -1233,17 +1344,22 @@ def _scaling_candidates(st): cons_m.append(f"{e['var']} = {to_str(e['value'])}") if e["time"] is not None and e["time"].free_symbols: cons_o.append(f"_ = {to_str(e['time'])}") - cons_o += [f"_ = {r}" for r in surface_ratios([st.gfun(cd, j) for j in cd.surfaces - if cd.vis[j] == _VISIBLE])] + cons_o += [f"_ = {r}" for r in surface_ratios([st.gfun(cd, j) for j in cd.surfaces if cd.vis[j] == _VISIBLE])] for sides in cd.regimes: f, h = st.model(cd, sides) models.append([f"{x} = {to_str(v)}" for x, v in f.items()]) obs.append([f"{y} = {to_str(v)}" for y, v in h.items()]) xm.append(cons_m) xo.append(cons_o) - r = scaling_symmetries_multi(per_cond_model=models, per_cond_obs=obs, inputs=st.inputs or None, - fixed=list(st.fixed) + ["time"], logs=True, extra_model=xm, - extra_obs=xo) + r = scaling_symmetries_multi( + per_cond_model=models, + per_cond_obs=obs, + inputs=st.inputs or None, + fixed=list(st.fixed) + ["time"], + logs=True, + extra_model=xm, + extra_obs=xo, + ) out = [] for d in r["non_identifiable"]: # the weight of an unknown input is the input change @@ -1262,9 +1378,10 @@ def _kernel_candidates(st, res, fresh): if not gen: continue try: - comp = {k: spy.sympify(str(v).replace("^", "**"), - locals={n: spy.Symbol(n) for n in _names_in(v)}) - for k, v in gen.items()} + comp = { + k: spy.sympify(str(v).replace("^", "**"), locals={n: spy.Symbol(n) for n in _names_in(v)}) + for k, v in gen.items() + } except (spy.SympifyError, TypeError): continue syms = set(comp) | {str(s) for v in comp.values() for s in v.free_symbols} @@ -1291,8 +1408,10 @@ def _kernel_candidates(st, res, fresh): def _parsed(comp): """String components as SymPy expressions; empty where one does not parse.""" try: - return {k: spy.sympify(str(v).replace("^", "**"), locals={n: spy.Symbol(n) for n in _names_in(v)}) - for k, v in comp.items()} + return { + k: spy.sympify(str(v).replace("^", "**"), locals={n: spy.Symbol(n) for n in _names_in(v)}) + for k, v in comp.items() + } except (spy.SympifyError, TypeError): return {} @@ -1341,38 +1460,72 @@ def _entry(F, comps, coords, reconstruct): support = sym_sort([z for z, c in zip(coords, comps) if not is_zero(c)]) if F.kind == "scaling" and F.weights is not None: w = {z: str(F.weights.get(z, 0)) for z in support} - return {"support": support, "vector": w, "type": "scaling", "closed_form": True, - "certified": True, "exact": True, "route": "hybrid symmetry"} + return { + "support": support, + "vector": w, + "type": "scaling", + "closed_form": True, + "certified": True, + "exact": True, + "route": "hybrid symmetry", + } w = {z: spy.cancel(c / _sym(z)) for z, c in zip(coords, comps) if z in support} if w and all(r.is_Integer for r in w.values()): - return {"support": support, "vector": {z: str(r) for z, r in w.items()}, "type": "scaling", - "closed_form": True, "certified": True, "exact": True, "route": "hybrid symmetry"} + return { + "support": support, + "vector": {z: str(r) for z, r in w.items()}, + "type": "scaling", + "closed_form": True, + "certified": True, + "exact": True, + "route": "hybrid symmetry", + } vec = {z: to_str(spy.factor(c).xreplace(BACK)) for z, c in zip(coords, comps) if z in support} if not reconstruct: return {"support": support, "type": "general", "closed_form": False, "certified": True} - return {"support": support, "vector": vec, "type": "general", "closed_form": True, - "certified": True, "exact": True, "route": "hybrid symmetry"} - - + return { + "support": support, + "vector": vec, + "type": "general", + "closed_form": True, + "certified": True, + "exact": True, + "route": "hybrid symmetry", + } def _info(st, extra=None): - out = {"surfaces": [st.hy.surface(j) for j in range(len(st.sw.funcs))], - "kinds": list(st.hy.kind), - "regimes": [st.text(r) for r in st.regimes], - "excluded": [st.text(r) for r in st.excluded], - "conditions": [{"name": cd.name, "regimes": [st.text(r) for r in cd.regimes], - "visibility": {st.hy.surface(j): cd.vis[j] for j in cd.surfaces}, - "declared": list(cd.declared)} for cd in st.conds]} + out = { + "surfaces": [st.hy.surface(j) for j in range(len(st.sw.funcs))], + "kinds": list(st.hy.kind), + "regimes": [st.text(r) for r in st.regimes], + "excluded": [st.text(r) for r in st.excluded], + "conditions": [ + { + "name": cd.name, + "regimes": [st.text(r) for r in cd.regimes], + "visibility": {st.hy.surface(j): cd.vis[j] for j in cd.surfaces}, + "declared": list(cd.declared), + } + for cd in st.conds + ], + } out.update(extra or {}) return out def _settings(st): kw = st.kw - return {"positive": st.positive, "reduce_cq": False, "equilibrate": st.equilibrate, - "reconstruct": bool(kw.get("reconstruct")), "verify": bool(kw.get("verify", True)), - "sym_engine": "modular", "degree_cap": None, "scalings_only": bool(kw.get("scalings_only"))} + return { + "positive": st.positive, + "reduce_cq": False, + "equilibrate": st.equilibrate, + "reconstruct": bool(kw.get("reconstruct")), + "verify": bool(kw.get("verify", True)), + "sym_engine": "modular", + "degree_cap": None, + "scalings_only": bool(kw.get("scalings_only")), + } def _entering(st, copies, fresh): @@ -1397,8 +1550,9 @@ def _reach_held(st, cp, pair, fr): start value.""" cd, ic = cp["cd"], cp["ic"] # a copy with the events of the condition, or without fresh start values, takes the plain reach - if cp.get("events", True) or \ - not any({str(a) for a in spy.sympify(v).free_symbols} & fr for v in ic.values() if v is not None): + if cp.get("events", True) or not any( + {str(a) for a in spy.sympify(v).free_symbols} & fr for v in ic.values() if v is not None + ): return st._reach(cd, pair) models = [st.model(cd, r) for r in pair] # a set of states whose right-hand sides vanish identically at their start values keeps them in every regime @@ -1468,6 +1622,7 @@ def _dropping_blocks(res, coords, copies, entering): def _on_copies(st, kept, fresh, coords): """(dimension of the projection or None where not proven, result, rows) of the stacked rows of `kept` alone.""" from .core import detection_with_primes + held = {z for cp in kept for z in cp.get("block") or ()} fresh = [z for z in fresh if z in held] # the kernel at the sample point bounds the rank; closed forms and the saturation guard are not needed @@ -1496,14 +1651,17 @@ def _at_random(rows, res, coords, fresh, entering, need): rk = ker.get("random") if rk is None: return {"status": "unchecked", "of": _OF_FRESH}, need - at = {"info": {"kernel": {"coords": ker["coords"], "N": rk["N"], "p": rk["p"]}, - "coordinates": res["info"]["coordinates"]}} + at = { + "info": { + "kernel": {"coords": ker["coords"], "N": rk["N"], "p": rk["p"]}, + "coordinates": res["info"]["coordinates"], + } + } need_r, proven = _relaxed_dim(at, coords, fresh, entering) if proven: return {"status": "proven"}, need_r if need_r != need: - return {"status": "differs", "of": _OF_FRESH, "base": len(coords) - need, - "random": len(coords) - need_r}, need + return {"status": "differs", "of": _OF_FRESH, "base": len(coords) - need, "random": len(coords) - need_r}, need cols = len(ker["coords"]) + len([z for z in ker["coords"] if z in set(fresh)]) return {"status": "verified", "of": _OF_FRESH, "probability": _minor_bound(rows, res, cols)}, need @@ -1511,6 +1669,7 @@ def _at_random(rows, res, coords, fresh, entering, need): def _minor_bound(rows, res, cols): """Schwartz-Zippel bound on a maximal minor of the stacked rows or their fresh columns vanishing, or None.""" from .core import _model_bound + order = int(res["info"].get("lie_order_used") or 0) evs = list(rows.get("events") or []) deg, q = 0, None @@ -1531,14 +1690,19 @@ def _projected(res, coords): if ker is None: raise HybridError("internal: the stacked analysis returned no kernel") kc = list(ker["coords"]) - N = np.asarray(ker["N"], dtype=np.int64).reshape(len(kc), -1) if np.size(ker["N"]) else \ - np.zeros((len(kc), 0), dtype=np.int64) + N = ( + np.asarray(ker["N"], dtype=np.int64).reshape(len(kc), -1) + if np.size(ker["N"]) + else np.zeros((len(kc), 0), dtype=np.int64) + ) missing = [z for z in coords if z not in kc] pub = [z for z in res["info"]["coordinates"] if not re.search(r"\|c[0-9]+$", z)] unknown = [z for z in missing if z in pub] if unknown: - raise HybridError("internal: the kernel of the stacked analysis is in other coordinates " - f"({', '.join(kc)}) than the model ({', '.join(coords)})") + raise HybridError( + "internal: the kernel of the stacked analysis is in other coordinates " + f"({', '.join(kc)}) than the model ({', '.join(coords)})" + ) rows = [kc.index(z) for z in coords if z in kc] if not rows or N.shape[1] == 0: return len(missing), None @@ -1555,6 +1719,7 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): if kw.get("scalings_only"): return _scalings_only(st, coords, t_start) from .core import _jet_order, detection_with_primes + given = int(dict(kw.get("control") or {}).get("input_jet_order") or 0) order = given or (_jet_order(kw) if st.unknown else 0) start = None @@ -1564,8 +1729,10 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): copies, fresh = _copies(st, names) miss = _uncovered(st, copies) if miss: - raise HybridError("internal: a regime enters no copy of the condition: " + - "; ".join(f"{c}: {', '.join(st.text(r))} ({k})" for c, r, k in miss)) + raise HybridError( + "internal: a regime enters no copy of the condition: " + + "; ".join(f"{c}: {', '.join(st.text(r))} ({k})" for c, r, k in miss) + ) jet_fresh = _jet_values(copies, jets, names) if fresh and not jets and start is None: # full rank on the copies without fresh coordinates is full rank of the rule, with nothing to project @@ -1597,44 +1764,59 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): chosen, why = [], [] off = fresh + list(jet_fresh) + [x for chain in jets.values() for x in chain] if need > 0: - cands = _scaling_candidates(st) + _kernel_candidates(st, res, off) + \ - _unit_candidates(st, coords) + cands = _scaling_candidates(st) + _kernel_candidates(st, res, off) + _unit_candidates(st, coords) chosen, why = _certify(st, cands, coords, need) uncertified, candidates = None, None syms = [_entry(F, c, coords, bool(kw.get("reconstruct"))) for F, c in chosen] if len(chosen) < need: - uncertified = (f"the stacked regimes leave {need} direction(s) open, and {len(chosen)} were proven " - "directions of the rule" + ("; rejected candidates: " + "; ".join(dict.fromkeys(why)) - if why else "")) + uncertified = ( + f"the stacked regimes leave {need} direction(s) open, and {len(chosen)} were proven " + "directions of the rule" + ("; rejected candidates: " + "; ".join(dict.fromkeys(why)) if why else "") + ) candidates = [_candidate(e) for e in _stacked_entries(res, off, syms, need - len(chosen))] dim = len(coords) info = res["info"] proven = need if need and uncertified is None else None - raw = {"rank": dim - need, "dim": dim, "coordinates": coords, "non_identifiable": syms, - "rank_proven": proven, - "rank_proof": "stacked regimes and exact symmetries of every regime" if proven else None, - "lie_order_used": info.get("lie_order_used"), "lie_certified": info.get("lie_certified"), - "lie_block_orders": info.get("lie_block_orders"), - "gap_order_used": info.get("gap_order_used"), "gap_certified": info.get("gap_certified"), - "gap_certificate": info.get("gap_certificate"), "gap_bound": info.get("gap_bound"), - "order_bound": info.get("order_bound"), "order_bound_why": info.get("order_bound_why"), - "order_draws": info.get("order_draws"), - "conditions": len(st.conds), - "segments": info.get("segments"), - "projection": projection} - out = finalize(raw, "observability", _settings(st), elapsed=time.monotonic() - t_start, - coordinates=coords) + raw = { + "rank": dim - need, + "dim": dim, + "coordinates": coords, + "non_identifiable": syms, + "rank_proven": proven, + "rank_proof": "stacked regimes and exact symmetries of every regime" if proven else None, + "lie_order_used": info.get("lie_order_used"), + "lie_certified": info.get("lie_certified"), + "lie_block_orders": info.get("lie_block_orders"), + "gap_order_used": info.get("gap_order_used"), + "gap_certified": info.get("gap_certified"), + "gap_certificate": info.get("gap_certificate"), + "gap_bound": info.get("gap_bound"), + "order_bound": info.get("order_bound"), + "order_bound_why": info.get("order_bound_why"), + "order_draws": info.get("order_draws"), + "conditions": len(st.conds), + "segments": info.get("segments"), + "projection": projection, + } + out = finalize(raw, "observability", _settings(st), elapsed=time.monotonic() - t_start, coordinates=coords) out["info"]["model_exprs"] = info.get("model_exprs") out["info"]["model_rhs"] = info.get("model_rhs") out["info"]["model_inputs"] = info.get("model_inputs") - out["info"]["switching"] = _info(st, {"copies": len(copies), "uncertified": uncertified, - "candidates": candidates}) + out["info"]["switching"] = _info(st, {"copies": len(copies), "uncertified": uncertified, "candidates": candidates}) if jets: - out["info"]["unknown_inputs"] = {"names": list(jets), "jets": jets, "jet_order": int(order), - "exact_order": int(order) - 1, "short": short} + out["info"]["unknown_inputs"] = { + "names": list(jets), + "jets": jets, + "jet_order": int(order), + "exact_order": int(order) - 1, + "short": short, + } if short: - session.note("limits", f"unknown inputs: the {order} jets of each input are exact up to Lie order " - f"{order - 1}, below the orders the analysis took") + session.note( + "limits", + f"unknown inputs: the {order} jets of each input are exact up to Lie order " + f"{order - 1}, below the orders the analysis took", + ) return out @@ -1653,8 +1835,11 @@ def _with_inputs_projection(rows, res, projection): return projection if nu["status"] != "verified": return nu - both = None if None in (projection.get("probability"), nu.get("probability")) else \ - float(min(1.0, projection["probability"] + nu["probability"])) + both = ( + None + if None in (projection.get("probability"), nu.get("probability")) + else float(min(1.0, projection["probability"] + nu["probability"])) + ) return {"status": "verified", "of": f"{projection['of']} and the unknown inputs", "probability": both} @@ -1690,14 +1875,21 @@ def _scalings_only(st, coords, t_start): why = [] alive = certify_fields(st, cands, why) if len(alive) < len(cands): - raise HybridError("the scaling kernel proposes a scaling that is not proven a direction " - f"of the rule ({why[0] if why else ''})") + raise HybridError( + "the scaling kernel proposes a scaling that is not proven a direction " + f"of the rule ({why[0] if why else ''})" + ) for F in cands: - out_syms.append({"support": sym_sort([k for k, v in F.weights.items() if v]), - "vector": {k: str(v) for k, v in F.weights.items() if v}, - "type": "scaling", "certified": True, "exact": True}) + out_syms.append( + { + "support": sym_sort([k for k, v in F.weights.items() if v]), + "vector": {k: str(v) for k, v in F.weights.items() if v}, + "type": "scaling", + "certified": True, + "exact": True, + } + ) raw = {"non_identifiable": out_syms, "coordinates": coords} - out = finalize(raw, "scaling", _settings(st), elapsed=time.monotonic() - t_start, - coordinates=coords) + out = finalize(raw, "scaling", _settings(st), elapsed=time.monotonic() - t_start, coordinates=coords) out["info"]["switching"] = _info(st) return out diff --git a/src/symident/detection/inputs.py b/src/symident/detection/inputs.py index 8b47ce5..7d6236c 100644 --- a/src/symident/detection/inputs.py +++ b/src/symident/detection/inputs.py @@ -20,7 +20,7 @@ def _dicts(x): # texts that passed _expression during one check_arguments call: conditions repeat the same entries -_PASSED = set() +_PASSED: set = set() # a plain name or decimal number always parses _PLAIN = re.compile(r"[A-Za-z_][A-Za-z_0-9]*|[0-9]+(\.[0-9]*)?([eE][-+]?[0-9]+)?") @@ -42,8 +42,10 @@ def _expression(text, where): except (SyntaxError, TokenError) as exc: kws = [w for w in re.findall(r"[A-Za-z_][A-Za-z_0-9]*", text) if keyword.iskeyword(w)] if kws: - raise InputError(f"{where} cannot be parsed: {text!r}; {kws[0]} is a Python keyword and cannot " - f"name a state, parameter or input, rename it") from exc + raise InputError( + f"{where} cannot be parsed: {text!r}; {kws[0]} is a Python keyword and cannot " + f"name a state, parameter or input, rename it" + ) from exc raise InputError(f"{where} cannot be parsed: {text!r}") from exc except Exception: # an expression the engine handles or refuses by name later return diff --git a/src/symident/detection/interp.py b/src/symident/detection/interp.py index f679f0e..a164840 100644 --- a/src/symident/detection/interp.py +++ b/src/symident/detection/interp.py @@ -64,11 +64,31 @@ def entry_degrees(f, pivots, point0, nv, zvals_of, rel, kbatch, nt_used, ctrl, l return out -def interpolate_direction(f, ref, pivots, znames, z_slots, leaf_names, n_leaves, point0, pool, - pool_next, nt_used, kcall, rel_probe=None, residue_fn=None, ctrl=None, - kbatch=None, shared_bank=None, fast_only=False, aux_leaves=(), degrees=None): +def interpolate_direction( + f, + ref, + pivots, + znames, + z_slots, + leaf_names, + n_leaves, + point0, + pool, + pool_next, + nt_used, + kcall, + rel_probe=None, + residue_fn=None, + ctrl=None, + kbatch=None, + shared_bank=None, + fast_only=False, + aux_leaves=(), + degrees=None, +): """One residual direction as rational entries over the leaves that move each entry.""" from .closedform import reconstruct_entry + if kbatch is None: kbatch = _default_kbatch(kcall) zvals0 = None if z_slots is None else np.asarray(point0)[z_slots] @@ -78,6 +98,7 @@ def zvals_of(pt): def nv(rp, p, zvals=zvals0): return null_residues(rp, f, p) if residue_fn is None else residue_fn(rp, p, zvals) + rel = direction_relevance(f, ref, pivots, z_slots, n_leaves, point0, rel_probe, residue_fn) base_nv, support_cols = rel["base_nv"], rel["support_cols"] relevant, rel_by_entry = rel["relevant"], rel["rel_by_entry"] @@ -89,11 +110,13 @@ def fallback(reason=None): def const_entry(col): if box["const_base"] is None: kr = kbatch([point0] * len(PRIMES), list(PRIMES), nt_used) - box["const_base"] = [nv(kr[k], PRIMES[k]) if _pivots_eq(kr[k], pivots) else None - for k in range(len(PRIMES))] + box["const_base"] = [ + nv(kr[k], PRIMES[k]) if _pivots_eq(kr[k], pivots) else None for k in range(len(PRIMES)) + ] # a prime without the kernel at the base point (a resting state without a root modulo it) is left out got = [(int(nvp[col]), p) for nvp, p in zip(box["const_base"], PRIMES) if nvp is not None] return _lift_const([v for v, _ in got], [p for _, p in got]) if got else None + if not relevant: entries = {} for c in support_cols: @@ -102,12 +125,20 @@ def const_entry(col): return fallback("a constant entry could not be lifted from the residues") entries[znames[c]] = e entries[znames[f]] = "1" - return {"pool_next": box["pool_next"], "entry": {"support": sym_sort(list(entries)), - "vector": entries, "type": "general", - "closed_form": True, "fit_how": "constant"}} + return { + "pool_next": box["pool_next"], + "entry": { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "fit_how": "constant", + }, + } if getattr(residue_fn, "pinned_support", False) and rel_probe is not None: - mono = pinned_monomials(f, pivots, znames, leaf_names, point0, nt_used, kcall, nv, base_nv, - support_cols, rel_by_entry, rel_probe) + mono = pinned_monomials( + f, pivots, znames, leaf_names, point0, nt_used, kcall, nv, base_nv, support_cols, rel_by_entry, rel_probe + ) if mono is not None: return {"pool_next": box["pool_next"], "entry": mono} if fast_only: @@ -116,12 +147,15 @@ def const_entry(col): def ex(v): return [x for x in v if x not in aux] + rel_phys = ex(relevant) max_rel_phys = max([0] + [len(ex(e)) for e in rel_by_entry]) if len(rel_phys) > ctrl["relevance_cap_dir"] or max_rel_phys > ctrl["relevance_cap_sparse"]: - return fallback(f"direction couples {len(rel_phys)} parameters (an entry up to {max_rel_phys}), " - f"above relevance_cap_dir={ctrl['relevance_cap_dir']} / relevance_cap_sparse=" - f"{ctrl['relevance_cap_sparse']}; raise the relevant cap") + return fallback( + f"direction couples {len(rel_phys)} parameters (an entry up to {max_rel_phys}), " + f"above relevance_cap_dir={ctrl['relevance_cap_dir']} / relevance_cap_sparse=" + f"{ctrl['relevance_cap_sparse']}; raise the relevant cap" + ) nrel = len(relevant) n_p = len(PRIMES) degs = list(degrees) if degrees is not None else [None] * len(support_cols) @@ -160,8 +194,10 @@ def ex(v): return fallback("no valid steady state under perturbation of the relevant leaves") # the hit rate so far cannot fill the need within the budget: stop early if tries >= 2 * max_need and len(rows_u) + len(rows_u) / tries * (30 * max_need - tries) < max_need: - return fallback("dense sampling could not collect enough pivot-consistent points; " - "raise sample_slack or probe_retries") + return fallback( + "dense sampling could not collect enough pivot-consistent points; " + "raise sample_slack or probe_retries" + ) chunk = max(1, min(max_need - len(rows_u) + ctrl["sample_slack"], 30 * max_need - tries)) tries += chunk uv = [] @@ -196,8 +232,10 @@ def ex(v): for i in range(len(support_cols)): rows_r[i].append(rrow[i]) if len(rows_u) < max_need: - return fallback("dense sampling could not collect enough pivot-consistent points; " - "raise sample_slack or probe_retries") + return fallback( + "dense sampling could not collect enough pivot-consistent points; " + "raise sample_slack or probe_retries" + ) sample_u = np.vstack(rows_u) rstore = [np.vstack(r) for r in rows_r] entries = {} @@ -212,19 +250,21 @@ def ex(v): how.append("constant") continue if len(reli) > ctrl["relevance_cap"]: - e = sparse_entry(reli, c, f, point0, leaf_names, nt_used, kcall, pivots, residue_fn, - ctrl, z_slots, kbatch) + e = sparse_entry(reli, c, f, point0, leaf_names, nt_used, kcall, pivots, residue_fn, ctrl, z_slots, kbatch) how.append("sparse Laurent") if e is None: - e = general_rational_entry(reli, c, f, point0, leaf_names, nt_used, kcall, pivots, - residue_fn, ctrl, z_slots, kbatch) + e = general_rational_entry( + reli, c, f, point0, leaf_names, nt_used, kcall, pivots, residue_fn, ctrl, z_slots, kbatch + ) how[-1] = "sparse rational" if e is None: - return fallback(f"an entry couples {len(reli)} variables and the sparse fit hit the caps " - f"(laurent_deg_num={ctrl['laurent_deg_num']}, general_deg_num=" - f"{ctrl['general_deg_num']}, general_deg_den={ctrl['general_deg_den']}, " - f"term_cap={ctrl['term_cap']}); raise these, or raise relevance_cap=" - f"{ctrl['relevance_cap']} to use the dense fit") + return fallback( + f"an entry couples {len(reli)} variables and the sparse fit hit the caps " + f"(laurent_deg_num={ctrl['laurent_deg_num']}, general_deg_num=" + f"{ctrl['general_deg_num']}, general_deg_den={ctrl['general_deg_den']}, " + f"term_cap={ctrl['term_cap']}); raise these, or raise relevance_cap=" + f"{ctrl['relevance_cap']} to use the dense fit" + ) entries[znames[c]] = simplify(e) continue cols_i = [relevant.index(r) for r in reli] @@ -246,9 +286,16 @@ def ex(v): entries[znames[c]] = simplify(expr) how.append("dense") entries[znames[f]] = "1" - return {"pool_next": box["pool_next"], - "entry": {"support": sym_sort(list(entries)), "vector": entries, "type": "general", - "closed_form": True, "fit_how": ", ".join(dict.fromkeys(how))}} + return { + "pool_next": box["pool_next"], + "entry": { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "fit_how": ", ".join(dict.fromkeys(how)), + }, + } def exp_backsub(vector, back, atoms=None): diff --git a/src/symident/detection/ioproj.py b/src/symident/detection/ioproj.py index d56d045..e4490eb 100644 --- a/src/symident/detection/ioproj.py +++ b/src/symident/detection/ioproj.py @@ -59,8 +59,9 @@ def __init__(self, polys, nv): def __call__(self, pts, p): if p not in self._res: self._res[p] = np.array([a % p * pow(b, -1, p) % p for a, b in self.coefs], dtype=np.int64) - return _core.io_poly_eval(self.exps, self._res[p], self.off, np.ascontiguousarray(pts, dtype=np.int64), p, - _threads()) + return _core.io_poly_eval( + self.exps, self._res[p], self.off, np.ascontiguousarray(pts, dtype=np.int64), p, _threads() + ) def _pow(a, e, p): @@ -78,6 +79,7 @@ def _pow(a, e, p): class Quo: """A quotient N / prod_k F_k^{e_k} of polynomials over a list F of factors shared by the functions of one model, kept without gcds.""" + __slots__ = ("numer", "exps") def __init__(self, numer, exps): @@ -165,7 +167,7 @@ def observable(self, r, m): lst.append((Nt * self.Q - N * self.Qt * a, a + 2, 0)) else: lst.append((Nt * self.Q * E - N * (self.Qt * E * a + Et * self.Q * b), a + 2, b + 1)) - return [self.quo(N, a, ie, b) for N, a, b in lst[:m + 1]] + return [self.quo(N, a, ie, b) for N, a, b in lst[: m + 1]] def within(self, ms): """Whether each derivative of observable r up to order ms[r] is the derivative of one with at most _JET @@ -249,14 +251,21 @@ def _count(nb, degree, cap_top, cap2=None): exponent of a second variable at most cap2.""" if cap2 is None: return sum(math.comb(nb - 1 + degree - e, nb - 1) for e in range(min(degree, cap_top) + 1)) - return sum(math.comb(nb - 2 + degree - e - f, nb - 2) for e in range(min(degree, cap_top) + 1) - for f in range(min(degree - e, cap2) + 1)) + return sum( + math.comb(nb - 2 + degree - e - f, nb - 2) + for e in range(min(degree, cap_top) + 1) + for f in range(min(degree - e, cap2) + 1) + ) def _mono_matrix(B, mons, p): """The values of the monomials at the rows of B.""" - return _core.io_mono_matrix(np.ascontiguousarray(B, dtype=np.int64), np.array(mons, dtype=np.int32).reshape( - len(mons), B.shape[1]), p, _threads()) + return _core.io_mono_matrix( + np.ascontiguousarray(B, dtype=np.int64), + np.array(mons, dtype=np.int32).reshape(len(mons), B.shape[1]), + p, + _threads(), + ) class Projection: @@ -268,8 +277,9 @@ class Projection: def __init__(self, rel, ms, pos, rng, top=None, extra=None): self.rel, self.ms, self.pos, self.rng = rel, list(ms), list(pos), rng J = jets_of(rel) - funcs = [q for r, m in enumerate(self.ms) if m >= 0 for q in J.observable(r, m)] + \ - [J.state(k) for k in rel.inputs(max(self.ms))] + funcs = [q for r, m in enumerate(self.ms) if m >= 0 for q in J.observable(r, m)] + [ + J.state(k) for k in rel.inputs(max(self.ms)) + ] if extra is not None: top, funcs = len(funcs), funcs + [J.state(extra)] self.base = Base(rel, funcs) @@ -298,7 +308,7 @@ def state(cls, rel, h, k, pos, rng, lift=None): return None pr = cls(rel, ms, pos, rng, extra=k) if lift is not None: - pr.capped = (sum(m + 1 for m in ms[:lift[0]]) + h[lift[0]], lift[1] - 1) + pr.capped = (sum(m + 1 for m in ms[: lift[0]]) + h[lift[0]], lift[1] - 1) return pr def points(self, theta, p, m): @@ -328,7 +338,7 @@ def kernel(box): mons = [m for m in mons if m[self.capped[0]] <= self.capped[1]] if len(pool[0]) < len(mons) + 8: pool[0] = np.vstack([pool[0], self.points(theta, p, len(mons) + 8 - len(pool[0]))]) - A = _mono_matrix(pool[0][:len(mons) + 8], mons, p) + A = _mono_matrix(pool[0][: len(mons) + 8], mons, p) work.tick(A.shape) return mons, _core.io_kernel(A, p, _threads()) @@ -357,8 +367,12 @@ def found(mons, v): if len(ker["free"]) == 1: return found(mons, ker["basis"][0]) continue - boxes = [(D, dt) for D in range(1, _DEGREE + 1) for dt in range(1, min(D, top_degree or D) + 1) - if _count(self.nb, D, dt, None if self.capped is None else self.capped[1]) <= c] + boxes = [ + (D, dt) + for D in range(1, _DEGREE + 1) + for dt in range(1, min(D, top_degree or D) + 1) + if _count(self.nb, D, dt, None if self.capped is None else self.capped[1]) <= c + ] largest = [b for b in boxes if not any(o != b and o[0] >= b[0] and o[1] >= b[1] for o in boxes)] for b in largest: if b in done or work.ticks() > stop: @@ -396,8 +410,11 @@ def polytope(self, theta, p, stop): return None rng, nb = self.rng, self.nb order = self.weights() - fixed = [tuple([1] * nb)] + [_unit(nb, v) for v in range(nb)] + \ - [tuple(order), tuple(max(order) + 1 - w for w in order)] + fixed = ( + [tuple([1] * nb)] + + [_unit(nb, v) for v in range(nb)] + + [tuple(order), tuple(max(order) + 1 - w for w in order)] + ) bounds = newton_bounds(sl, fixed, stop) if bounds is None: return None @@ -564,7 +581,7 @@ def count(self, values, direc=None, weights=None, torus=False): d[key] = (d.get(key, 0) + 1) % p eqs.append({m: c for m, c in d.items() if c}) eqs.append({tuple([(0, 1)] + [(self.u[k], 1) for k in self.used]): 1, (): p - 1}) - names = self.names[:self.t] + names = self.names[: self.t] if direc is not None: names = names + ["t"] if torus: @@ -582,11 +599,11 @@ def _gradients(J, funcs, gens, pt, p): for f, _ in q.exps: polys += [J.fac[f]] + [J.fac[f].diff(x) for x in gens] v = [int(x) for x in _Polys(polys, len(pt))(np.array([pt], dtype=np.int64), p)[0]] - n, g = v[0], v[1:len(gens) + 1] + n, g = v[0], v[1 : len(gens) + 1] den, at = 1, len(gens) + 1 lg = [0] * len(gens) for _f, e in q.exps: - F, dF = v[at], v[at + 1:at + 1 + len(gens)] + F, dF = v[at], v[at + 1 : at + 1 + len(gens)] at += 1 + len(gens) if not F: return None @@ -690,7 +707,7 @@ def _pdivmod(a, b, p): if c: for j, bj in enumerate(b): a[k + j] = (a[k + j] - c * bj) % p - return _poly_trim(q), _poly_trim(a[:len(b) - 1]) + return _poly_trim(q), _poly_trim(a[: len(b) - 1]) def _psub(a, b, p): @@ -798,6 +815,7 @@ def rec(v, left, cur): cur.append(e) rec(v + 1, left - e, cur) cur.pop() + rec(0, total, []) out.sort(key=lambda m: (sum(m), m)) return out @@ -1107,7 +1125,7 @@ def _denominator(self, comb, beta, width, boxD, q): if ker["free"] != [len(boxD)]: self.why = "the denominator is not determined by the box of degrees" return None - return np.asarray(ker["basis"][0][:len(boxD)], dtype=np.int64) % q + return np.asarray(ker["basis"][0][: len(boxD)], dtype=np.int64) % q def _numerators(self, vec, dco, boxD, allm, width, q): """The coefficients of every numerator on allm modulo q, one solve with the values times D.""" @@ -1138,9 +1156,15 @@ def _numerators(self, vec, dco, boxD, allm, width, q): def expressions(self, params): """The coefficients as sympy expressions in `params`, in the order of the monomials of the projection.""" + def poly(co): - return sum((spy.Rational(c.numerator, c.denominator) * spy.prod([s ** e for s, e in zip(params, m)]) - for m, c in co.items()), spy.Integer(0)) + return sum( + ( + spy.Rational(c.numerator, c.denominator) * spy.prod([s**e for s, e in zip(params, m)]) + for m, c in co.items() + ), + spy.Integer(0), + ) D = poly(self.den) out = [None] * len(self.order) @@ -1242,7 +1266,7 @@ def _add(self, m): if m in self.at: return v = next(i for i, e in enumerate(m) if e) - lower = m[:v] + (m[v] - 1,) + m[v + 1:] + lower = m[:v] + (m[v] - 1,) + m[v + 1 :] self._add(lower) self.at[m] = len(self.mons) self.mons.append(m) @@ -1252,8 +1276,8 @@ def order(self, X, k): p = self.p for j, m in enumerate(self.mons[1:], 1): v = next(i for i, e in enumerate(m) if e) - par = self.at[m[:v] + (m[v] - 1,) + m[v + 1:]] - self.ser[j, k] = _dot(self.ser[par, :k + 1], X[v][k::-1], p) + par = self.at[m[:v] + (m[v] - 1,) + m[v + 1 :]] + self.ser[j, k] = _dot(self.ser[par, : k + 1], X[v][k::-1], p) def value(self, i, k): return sum(c * int(self.ser[j, k]) for j, c in self.polys[i]) % self.p @@ -1485,6 +1509,7 @@ def ring_poly(co): def coefficient_values(coef, theta, p): """The coefficients of the projection at the parameter point theta modulo p, in the order of the monomials; None where the denominator vanishes there.""" + def ev(co): s = 0 for m, c in co.items(): diff --git a/src/symident/detection/monodromy.py b/src/symident/detection/monodromy.py index 9b1a4d8..be680c7 100644 --- a/src/symident/detection/monodromy.py +++ b/src/symident/detection/monodromy.py @@ -29,6 +29,7 @@ class _Batch: """Values at a batch of points with the gradients over the coordinates, in complex floating point: the arithmetic of Series._outputs for many points at once.""" + __slots__ = ("v", "d") def __init__(self, v, d=None): @@ -85,13 +86,13 @@ def __rtruediv__(self, x): def __pow__(self, e): if e == 0: return self._of(1) - v = self.v ** e + v = self.v**e return _Batch(v, None if self.d is None else self.d * (e * self.v ** (e - 1))[:, None]) def __eq__(self, x): return bool(np.any(self.v == self._of(x).v)) - __hash__ = None + __hash__ = None # type: ignore[assignment] def _flat(ys, orders, gap, free): @@ -102,7 +103,7 @@ def _flat(ys, orders, gap, free): if j in free: continue for k in range(min(orders[j], len(y) - 1) + 1): - for m, c in enumerate(y[k][:gap + 1]): + for m, c in enumerate(y[k][: gap + 1]): out.append(c) index.append((j, k, m)) return out, index @@ -126,8 +127,10 @@ def coefficients(series, X, orders, gap=0, jac=True): vals = np.stack([r.v if isinstance(r, _Batch) else np.full(P, complex(r)) for r in rows], axis=1) J = None if jac: - J = np.stack([r.d if isinstance(r, _Batch) and r.d is not None else np.zeros((P, n), dtype=complex) - for r in rows], axis=1) + J = np.stack( + [r.d if isinstance(r, _Batch) and r.d is not None else np.zeros((P, n), dtype=complex) for r in rows], + axis=1, + ) return vals, J, index @@ -197,7 +200,7 @@ def _eval_safe(F, X): J = np.full((len(X), n, n), np.nan, dtype=complex) ok = np.zeros(len(X), dtype=bool) for i in range(len(X)): - g = F(X[i:i + 1]) + g = F(X[i : i + 1]) if g is not None: v[i], J[i], ok[i] = g[0][0], g[1][0], True return v, J, ok @@ -315,6 +318,7 @@ def rur_points(fib, point, digits=40): from .discrete import FiberTooLargeError from .discrete import _solve as solve_block + try: sysd = fib.system(point) except (FiberTooLargeError, ZeroDivisionError): @@ -331,6 +335,7 @@ def rur_points(fib, point, digits=40): return None elim, den, params = par[1][0][1], par[1][1][1], par[1][2] with mpmath.workdps(digits): + def mp(c): c = Fraction(c) return mpmath.mpf(c.numerator) / c.denominator @@ -338,8 +343,11 @@ def mp(c): def ev(cs, t): return mpmath.polyval([mp(c) for c in reversed(cs)], t) - roots = mpmath.polyroots([mp(c) for c in reversed(elim)], maxsteps=400, extraprec=4 * digits) \ - if len(elim) > 2 else [-mp(elim[0]) / mp(elim[1])] + roots = ( + mpmath.polyroots([mp(c) for c in reversed(elim)], maxsteps=400, extraprec=4 * digits) + if len(elim) > 2 + else [-mp(elim[0]) / mp(elim[1])] + ) sols = [] last = len(vn) - 1 for t in roots: @@ -347,8 +355,9 @@ def ev(cs, t): if dv == 0: continue vals = {vn[j]: -ev(q[0][1], t) / (mp(q[1]) * dv) for j, q in enumerate(params)} - vals[vn[last]] = (t - sum((mp(lin[j]) * vals[vn[j]] for j in range(last)), mpmath.mpf(0))) / \ - mp(lin[last]) + vals[vn[last]] = (t - sum((mp(lin[j]) * vals[vn[j]] for j in range(last)), mpmath.mpf(0))) / mp( + lin[last] + ) sols.append({k: complex(v) for k, v in vals.items()}) per.append(sols) out = [] @@ -363,6 +372,7 @@ def ev(cs, t): # ---- the Krawczyk operator in interval arithmetic -------------------------------------------- + def _dn(x): return np.nextafter(x, -np.inf) @@ -374,6 +384,7 @@ def _up(x): class _Rect: """Complex rectangles [rl, rh] + i [il, ih], arrays of one shape, with outward rounding: each floating-point operation is correctly rounded, so one step to the next float outward encloses the exact result.""" + __slots__ = ("rl", "rh", "il", "ih") def __init__(self, rl, rh, il, ih): @@ -455,6 +466,7 @@ def _sum(rects, shape): class _IDual: """An enclosure of a value with enclosures of the gradient over the coordinates: the arithmetic of Series._outputs over a box.""" + __slots__ = ("v", "d") n = 0 @@ -514,7 +526,7 @@ def __eq__(self, x): # a value whose enclosure holds zero cannot be divided by return bool((self - self._of(x)).v.has_zero()) - __hash__ = None + __hash__ = None # type: ignore[assignment] def _bcast(r): @@ -539,6 +551,7 @@ def square_rows(series, orders, gap, x): """n rows of the coefficients up to `orders` with independent gradients at x, chosen by a pivoted QR decomposition of the Jacobian with rows of unit norm: the best conditioned square subsystem it finds.""" import scipy.linalg as sl + got = coefficients(series, np.asarray(x)[None, :], orders, gap) if got is None: return None @@ -548,7 +561,7 @@ def square_rows(series, orders, gap, x): if len(keep) < A.shape[1]: return None _, _, piv = sl.qr((A[keep] / nrm[keep, None]).T, pivoting=True) - return sorted(int(keep[i]) for i in piv[:A.shape[1]]) + return sorted(int(keep[i]) for i in piv[: A.shape[1]]) def krawczyk(series, orders, gap, rows, base, x, radius): @@ -579,20 +592,28 @@ def krawczyk(series, orders, gap, rows, base, x, radius): return None if not np.all(np.isfinite(Y)): return None - J = _Rect(np.array([c.d.rl for c in JX]), np.array([c.d.rh for c in JX]), - np.array([c.d.il for c in JX]), np.array([c.d.ih for c in JX])) - G = _Rect(np.array([v.rl for v in g]), np.array([v.rh for v in g]), np.array([v.il for v in g]), - np.array([v.ih for v in g])) + J = _Rect( + np.array([c.d.rl for c in JX]), + np.array([c.d.rh for c in JX]), + np.array([c.d.il for c in JX]), + np.array([c.d.ih for c in JX]), + ) + G = _Rect( + np.array([v.rl for v in g]), + np.array([v.rh for v in g]), + np.array([v.il for v in g]), + np.array([v.ih for v in g]), + ) dX = box - _Rect.point(xm) for i in range(n): Yi = _Rect.point(Y[i]) - yg = _sum([(Yi[l:l + 1] * G[l:l + 1]) for l in range(n)], (1,)) + yg = _sum([(Yi[l : l + 1] * G[l : l + 1]) for l in range(n)], (1,)) # row i of I - Y J(X) - E = _Rect.const(0, (n,)) - _sum([Yi[l:l + 1] * J[l] for l in range(n)], (n,)) + E = _Rect.const(0, (n,)) - _sum([Yi[l : l + 1] * J[l] for l in range(n)], (n,)) E.rl[i], E.rh[i] = _dn(E.rl[i] + 1), _up(E.rh[i] + 1) # the row sum of |I - Y J(X)| weighted by the radii, below the radius: a contraction in the weighted norm q = float(_up(np.sum(E.mag() * r) * (1 + 4 * n * np.finfo(float).eps))) - k = _Rect.point(xm[i:i + 1]) - yg + _sum([E[j:j + 1] * dX[j:j + 1] for j in range(n)], (1,)) + k = _Rect.point(xm[i : i + 1]) - yg + _sum([E[j : j + 1] * dX[j : j + 1] for j in range(n)], (1,)) inside = k.rl[0] > box.rl[i] and k.rh[0] < box.rh[i] and k.il[0] > box.il[i] and k.ih[0] < box.ih[i] if not inside or not q < r[i]: return None @@ -623,6 +644,7 @@ def disjoint(a, b): # ---- maps read from the points ---------------------------------------------------------------- + def _nice(z, den=12, tol=1e-7): """z as a Gaussian rational with denominators up to `den`, or None.""" out = [] @@ -631,8 +653,9 @@ def _nice(z, den=12, tol=1e-7): if abs(float(f) - part) > tol * (1 + abs(part)): return None out.append(f) - return spy.Rational(out[0].numerator, out[0].denominator) + \ - spy.I * spy.Rational(out[1].numerator, out[1].denominator) + return spy.Rational(out[0].numerator, out[0].denominator) + spy.I * spy.Rational( + out[1].numerator, out[1].denominator + ) def _coordinate_forms(base, img, moved, syms): @@ -644,9 +667,9 @@ def _coordinate_forms(base, img, moved, syms): for j, s in enumerate(syms): b = base[j] for e in (1, -1): - c = _nice(z / b ** e) + c = _nice(z / b**e) if c is not None and c != 0: - forms.append(c * s ** e) + forms.append(c * s**e) if j == i: d = _nice(z - b) if d is not None and d != 0: @@ -707,6 +730,7 @@ def propose(series, fib, meter=None, target=None): parametrization of msolve over Q; those enclosed in disjoint Krawczyk boxes. The paths stop at the cap monodromy_products of work.CAPS on the work of their steps (_step_work()), or of `meter`.""" from .discrete import Fiber, complex_count + meter = meter or work.Meter("the monodromy", work.CAPS["monodromy_products"], "term products") out = {"points": 0, "square": None, "source": None, "certified": 0, "boxes": [], "why": None} if series.free_rows: @@ -719,7 +743,7 @@ def propose(series, fib, meter=None, target=None): out["why"] = "no square subsystem of independent coefficients" return out, [] srng = session.current().rng("discrete monodromy", tuple(series.coords)) - rng = np.random.default_rng(srng.randint(0, 2 ** 32 - 1)) + rng = np.random.default_rng(srng.randint(0, 2**32 - 1)) base = {s: spy.Rational(srng.randint(5, 40), srng.randint(4, 12)) for s in series.cs} out["base"] = {str(s): str(v) for s, v in base.items()} try: @@ -729,7 +753,7 @@ def propose(series, fib, meter=None, target=None): out["why"] = "the random point is a pole" return out, [] # the size of the square fiber decides whether monodromy can reach it - pt = {s: spy.Integer(srng.randint(2, 10 ** 6)) for s in series.cs} + pt = {s: spy.Integer(srng.randint(2, 10**6)) for s in series.cs} with work.quick_msolve(): est = complex_count(Fiber(series, system.sub_orders, fib.positive), pt, PRIMES[0]) out["square"] = est @@ -769,6 +793,7 @@ def proposals(series, fib, k, known, meter=None): `known`, where the group of the known maps has fewer points than the count `k` or no count exists; (None, []) otherwise.""" from .discrete import _same_map, group + if getattr(fib, "too_large", None) or not series.cs: return None, [] grp = group(known, series.cs) if known else [dict(zip(series.cs, series.cs))] diff --git a/src/symident/detection/multiexp.py b/src/symident/detection/multiexp.py index 0913a90..5a22c5e 100644 --- a/src/symident/detection/multiexp.py +++ b/src/symident/detection/multiexp.py @@ -48,8 +48,14 @@ def eligible(series): if v in used: return None, f"the start coordinate {v} is also a parameter of the model" clocks = {i for i in known if all(not any(m) for P in seg["F"][i] for m in P) and any(seg["F"][i][0].values())} - reads = {j for N, D in [seg["F"][i] for i in range(ns) if i not in known] + list(seg["G"]) - for P in (N, D) for m in P for j, e in enumerate(m[:ns]) if e} + reads = { + j + for N, D in [seg["F"][i] for i in range(ns) if i not in known] + list(seg["G"]) + for P in (N, D) + for m in P + for j, e in enumerate(m[:ns]) + if e + } if reads & clocks: return None, "the model reads the clock" return starts, None @@ -62,6 +68,7 @@ def conservation_laws(seg, states): from sympy.polys.matrices import DomainMatrix from ..sym.parse import model_sympify + xs = [spy.Symbol(x) for x in states] rhs = [model_sympify(str(seg["f"][x])) for x in states] variables = [spy.Symbol(x) for x in seg["f"]] @@ -102,10 +109,14 @@ def stacked(parts, coords, series, starts, K, laws=()): each law starts where the law takes the value of the first experiment. The coordinates of the model come first.""" from ..sym.parse import model_sympify + seg = parts[0]["segments"][0] st = [str(x) for x in series.parts[0]["st"]] - taken = set(coords) | set(seg["f"]) | {w for e in list(seg["f"].values()) + list(seg["g"].values()) - for w in re.findall(r"[A-Za-z_]\w*", str(e))} + taken = ( + set(coords) + | set(seg["f"]) + | {w for e in list(seg["f"].values()) + list(seg["g"].values()) for w in re.findall(r"[A-Za-z_]\w*", str(e))} + ) first = {st[i]: spy.Symbol(str(v)) for i, v in starts.items()} pivots = [next(iter(law)) for law in laws] out, extra = [], [] @@ -131,6 +142,7 @@ def plan(parts, coords, series, starts, ks=None, laws=()): observables plus one, at most 8) whose stacked model has full rank: the orders of the rank criterion per observable of each experiment, the lowest highest order first and among equal ones the fewest experiments.""" from .discrete import Series + if ks is None: n_y = len(series.parts[0]["segs"][0]["G"]) n_t = len(coords) - len(starts) @@ -153,6 +165,7 @@ def count(parts, coords, series, positive, floor, experiments=None): criterion of the stacked model up, until it is stable or reaches `floor`, the orbit of the proven maps.""" from . import discrete, firstint from .discrete import choose_order + t0 = time.monotonic() starts, why = eligible(series) if why is not None: @@ -162,8 +175,10 @@ def count(parts, coords, series, positive, floor, experiments=None): laws = conservation_laws(parts[0]["segments"][0], [st[i] for i in starts]) fi = firstint.certificate(series, laws) if not fi["proven"]: - return {"why": "the absence of rational first integrals is not proven: " + str(fi["why"]), - "first_integrals": fi} + return { + "why": "the absence of rational first integrals is not proven: " + str(fi["why"]), + "first_integrals": fi, + } given = isinstance(experiments, int) and not isinstance(experiments, bool) and experiments > 1 plans = plan(parts, coords, series, starts, [experiments] if given else None, laws) if not plans: @@ -174,9 +189,18 @@ def count(parts, coords, series, positive, floor, experiments=None): sk.pins = [tuple({mm + pad: c for mm, c in P.items()} for P in pin) for pin in series.pins] discrete._FAILURES.clear() fib, stable, cc = choose_order(sk, positive, 1, 2 * len(sk.coords), floor=floor, proj=len(coords)) - out = {"why": None, "experiments": K, "orders": list(fib.orders), "count": cc, "stable": stable, - "first_integrals": fi, "fiber": fib, "crit": crit, "series": sk, - "seconds": round(time.monotonic() - t0, 2)} + out = { + "why": None, + "experiments": K, + "orders": list(fib.orders), + "count": cc, + "stable": stable, + "first_integrals": fi, + "fiber": fib, + "crit": crit, + "series": sk, + "seconds": round(time.monotonic() - t0, 2), + } if cc is None: out["failed"] = discrete.no_count_reason(fib.order) return out diff --git a/src/symident/detection/numbase.py b/src/symident/detection/numbase.py index 3ba0bc0..73ae287 100644 --- a/src/symident/detection/numbase.py +++ b/src/symident/detection/numbase.py @@ -15,8 +15,13 @@ def _bases(e, states): """Positive rational bases b != 1 of the powers b^x of `e` whose exponent x holds no state.""" out = set() for pw in e.atoms(spy.Pow): - if pw.base.is_Rational and pw.base > 0 and pw.base != 1 and not pw.exp.is_number \ - and not (pw.exp.free_symbols & states): + if ( + pw.base.is_Rational + and pw.base > 0 + and pw.base != 1 + and not pw.exp.is_number + and not (pw.exp.free_symbols & states) + ): out.add(pw.base) return out @@ -27,9 +32,10 @@ def _parsed(x): try: e = model_sympify(x) # (2*K)^n as 2^n*K^n - return e.replace(lambda p: p.is_Pow and p.base.is_Mul and not p.exp.is_number - and p.base.as_coeff_Mul()[0] not in (1, -1), - lambda p: spy.expand_power_base(p, force=True)) + return e.replace( + lambda p: p.is_Pow and p.base.is_Mul and not p.exp.is_number and p.base.as_coeff_Mul()[0] not in (1, -1), + lambda p: spy.expand_power_base(p, force=True), + ) except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -59,8 +65,7 @@ def _symbol_bases(e, states): """{exponent: symbols K} of the powers K^x of `e` whose base is a symbol and whose exponent holds no state.""" out = {} for pw in e.atoms(spy.Pow): - if pw.base.is_Symbol and pw.base not in states and not pw.exp.is_number \ - and not (pw.exp.free_symbols & states): + if pw.base.is_Symbol and pw.base not in states and not pw.exp.is_number and not (pw.exp.free_symbols & states): out.setdefault(pw.exp, set()).add(pw.base) return out @@ -68,8 +73,13 @@ def _symbol_bases(e, states): def _numeric_exps(e, states): out = {} for pw in e.atoms(spy.Pow): - if pw.base.is_Rational and pw.base > 0 and pw.base != 1 and not pw.exp.is_number \ - and not (pw.exp.free_symbols & states): + if ( + pw.base.is_Rational + and pw.base > 0 + and pw.base != 1 + and not pw.exp.is_number + and not (pw.exp.free_symbols & states) + ): out.setdefault(pw.exp, set()).add(pw.base) return out @@ -81,16 +91,25 @@ def _copy(kw): kw2[key] = dict(kw[key]) for key in ("g", "trafo"): v = kw.get(key) - kw2[key] = dict(v) if isinstance(v, dict) else [dict(d) if isinstance(d, dict) else d for d in v] \ - if isinstance(v, (list, tuple)) else v + kw2[key] = ( + dict(v) + if isinstance(v, dict) + else [dict(d) if isinstance(d, dict) else d for d in v] + if isinstance(v, (list, tuple)) + else v + ) kw2["events"] = [dict(ev) if isinstance(ev, dict) else ev for ev in kw.get("events") or []] or kw.get("events") return kw2 def _pinned(kw, name): """True if `name` is set outside the model expressions: a `trafo` key or a condition column.""" - keys = {str(k) for d in ([kw["trafo"]] if isinstance(kw.get("trafo"), dict) else kw.get("trafo") or []) - if isinstance(d, dict) for k in d} + keys = { + str(k) + for d in ([kw["trafo"]] if isinstance(kw.get("trafo"), dict) else kw.get("trafo") or []) + if isinstance(d, dict) + for k in d + } cond = kw.get("conditions") cols = set(getattr(cond, "columns", None) or (cond if isinstance(cond, dict) else {}) or []) return name in keys or name in {str(c) for c in cols} @@ -106,8 +125,9 @@ def _absorb(kw, states): if e is None: continue for x, bs in sorted(_numeric_exps(e, states).items(), key=lambda t: str(t[0])): - ks = sorted((k for _, _, e2 in places if e2 is not None - for k in _symbol_bases(e2, states).get(x, ())), key=str) + ks = sorted( + (k for _, _, e2 in places if e2 is not None for k in _symbol_bases(e2, states).get(x, ())), key=str + ) ks = [k for k in ks if not _pinned(kw2, str(k))] if ks: pair = (min(bs), ks[0]) @@ -154,8 +174,10 @@ def numeric_bases(kw): e = _parsed(d[k]) if e is None or not _bases(e, states): continue - e2 = e.replace(lambda x: x.is_Pow and x.base in sym and not x.exp.is_number - and not (x.exp.free_symbols & states), lambda x: sym[x.base] ** x.exp) + e2 = e.replace( + lambda x: x.is_Pow and x.base in sym and not x.exp.is_number and not (x.exp.free_symbols & states), + lambda x: sym[x.base] ** x.exp, + ) d[k] = str(e2).replace("**", "^") kw2["fixed"] = list(kw.get("fixed") or []) + list(names.values()) return kw2, {n: b for b, n in names.items()}, scaled @@ -210,4 +232,5 @@ def walk(o, key=None): if isinstance(o, tuple): return tuple(walk(v) for v in o if not (isinstance(v, str) and v in fixed)) return o + return walk(obj) diff --git a/src/symident/detection/observability/analysis.py b/src/symident/detection/observability/analysis.py index 30499c1..ac53640 100644 --- a/src/symident/detection/observability/analysis.py +++ b/src/symident/detection/observability/analysis.py @@ -54,6 +54,7 @@ def _margin(): def _rational_forms(exprs): """Whether every expression is rational in the symbols it reads, model names read as symbols.""" from ...sym.parse import _is_rational_expr, _make_local_parse + try: _, parse = _make_local_parse([str(x) for x in exprs]) return all(_is_rational_expr(parse(str(x).replace("^", "**"))) for x in exprs) @@ -81,6 +82,7 @@ def _in_rational_span(w, ws): return False try: import sympy as spy + E = spy.Matrix([[spy.Rational(str(v.get(k, 0))) for k in names] for v in ws]) return E.rank() == E.col_join(spy.Matrix([[spy.Rational(str(w.get(k, 0))) for k in names]])).rank() except SYMPY_FAILS as exc: @@ -91,17 +93,30 @@ def _in_rational_span(w, ws): class Analysis: """Observability analysis of all conditions; joint mode has shared columns, then state columns per resting one.""" - def __init__(self, multi, closed_form=False, cores=1, equil_zero_states=(), - cond_zero_states=(), t0events=(), n_conditions=None, chain_of=None, n_gaps=0, - implicit_steady_state=False, control=None, verify=False, codim_spec=None): + def __init__( + self, + multi, + closed_form=False, + cores=1, + equil_zero_states=(), + cond_zero_states=(), + t0events=(), + n_conditions=None, + chain_of=None, + n_gaps=0, + implicit_steady_state=False, + control=None, + verify=False, + codim_spec=None, + ): from ...options import reconst_control + self.ctrl = {**reconst_control(), **dict(control or {})} self.closed_form = bool(closed_form) self.verify = bool(verify) self.codim_spec = codim_spec self.n_conditions = n_conditions - self.run = run = Run(multi, cores, self.ctrl, chain_of, n_gaps, t0events, cond_zero_states, - equil_zero_states) + self.run = run = Run(multi, cores, self.ctrl, chain_of, n_gaps, t0events, cond_zero_states, equil_zero_states) self.joint = bool(multi.get("joint_steady_state")) and bool(implicit_steady_state) self.n_aug = run.n_leaves self.leaf_names_aug = list(run.leaf_names) @@ -118,8 +133,7 @@ def __init__(self, multi, closed_form=False, cores=1, equil_zero_states=(), run.nuis_cols = [int(sys.wide_cols[0][i]) for i in run.nuis_cols] run.nuis_drop = [int(sys.wide_cols[0][i]) for i in run.nuis_drop] pn = set(sys.param_names) - self.aux_leaves = [i for i, nm in enumerate(self.leaf_names_aug) - if nm in set(run.leaf_names) - pn] + self.aux_leaves = [i for i, nm in enumerate(self.leaf_names_aug) if nm in set(run.leaf_names) - pn] self.ctrl["relevance_cap"] = self.ctrl["relevance_cap"] + sys.n_st # exponential leaves outside the resting model leave the report like a transient recast if multi.get("exp_atoms"): @@ -138,8 +152,7 @@ def __init__(self, multi, closed_form=False, cores=1, equil_zero_states=(), self.aux_leaves = [i for i, nm in enumerate(self.leaf_names_aug) if nm in set(self.atom_names)] self.recast = sys.recast self.zsn = set(strs(self.multi.get("z_state_names"))) - self.can_batch = not run.ss_constraint and not run.has_gaps and not self.transient and \ - not run.nuis_cols + self.can_batch = not run.ss_constraint and not run.has_gaps and not self.transient and not run.nuis_cols self.scal_memo = {} self.rank_cap = self.nz self.scal_ws = None @@ -172,28 +185,59 @@ def kbatch(self, point_list, prime_vec, Nt): run, n = self.run, len(point_list) def leaves(): - return np.vstack([np.asarray(pp[:run.n_leaves], dtype=np.int64) for pp in point_list]) + return np.vstack([np.asarray(pp[: run.n_leaves], dtype=np.int64) for pp in point_list]) + if self.can_batch and n > 0: - return _core.sym_obs_null_batch(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, leaves(), - list(prime_vec), int(Nt), run.cores) - if run.has_gaps and not run.ss_constraint and not self.joint and not self.transient and \ - not run.nuis_cols and n > 0: + return _core.sym_obs_null_batch( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + leaves(), + list(prime_vec), + int(Nt), + run.cores, + ) + if ( + run.has_gaps + and not run.ss_constraint + and not self.joint + and not self.transient + and not run.nuis_cols + and n > 0 + ): emulated = run.stacked_chain_batch(point_list, prime_vec, int(Nt), int(run.mtot), list(run.nt_cap)) if emulated is not None: return emulated - return _core.sym_obs_null_chain_point_batch([run.chain_tapes(idx) for idx in run.chain_groups], - run.n_leaves, run.n_states, run.z_slots, leaves(), - list(prime_vec), int(Nt), int(run.mtot), run.cores, - list(run.nt_cap)) + return _core.sym_obs_null_chain_point_batch( + [run.chain_tapes(idx) for idx in run.chain_groups], + run.n_leaves, + run.n_states, + run.z_slots, + leaves(), + list(prime_vec), + int(Nt), + int(run.mtot), + run.cores, + list(run.nt_cap), + ) if self.transient and not self.joint and not run.has_gaps and not run.nuis_cols and n > 0: - os_ = _core.sym_obs_null_batch(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, leaves(), - list(prime_vec), int(Nt), run.cores) + os_ = _core.sym_obs_null_batch( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + leaves(), + list(prime_vec), + int(Nt), + run.cores, + ) return [self.sys.with_relations(os_[i], point_list[i], prime_vec[i]) for i in range(n)] if self.chunked and n > 0: per = 2 * max(1, run.cores) out = [] for s in range(0, n, per): - out.extend(self.sys.chunk(point_list[s:s + per], prime_vec[s:s + per], Nt)) + out.extend(self.sys.chunk(point_list[s : s + per], prime_vec[s : s + per], Nt)) return [run.modulo_nuisance(o, q) for o, q in zip(out, prime_vec)] if self.joint: self.sys.warm_solves(point_list, prime_vec) @@ -204,8 +248,9 @@ def leaves(): if self.joint: self.sys.warm_off = True try: - return run.par_map(range(n), lambda i: self.kcall(point_list[i], prime_vec[i], Nt), - self.sys if self.joint else None) + return run.par_map( + range(n), lambda i: self.kcall(point_list[i], prime_vec[i], Nt), self.sys if self.joint else None + ) finally: run.cores_call = cc_saved if self.joint: @@ -221,14 +266,25 @@ def cover_tapes(self): self._cover = None if not self.can_batch or len(run.tapes) < 16: return None - r = _core.sym_obs_cover(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, - np.asarray(sc["point0"][:run.n_leaves], dtype=np.int64), PRIMES[0], - int(sc["nt_used"]), int(sc["rank"]), run.cores) + r = _core.sym_obs_cover( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + np.asarray(sc["point0"][: run.n_leaves], dtype=np.int64), + PRIMES[0], + int(sc["nt_used"]), + int(sc["rank"]), + run.cores, + ) if ok(r) and int(r["rank"]) == int(sc["rank"]) and len(ints(r["conditions"])) < len(run.tapes): self._cover = kernel_tapes([run.tapes[i] for i in ints(r["conditions"])]) if run.timing: - print(f"[sym] cover: {len(ints(r['conditions']))} of {len(run.tapes)} conditions reach rank " - f"{int(sc['rank'])}", flush=True) + print( + f"[sym] cover: {len(ints(r['conditions']))} of {len(run.tapes)} conditions reach rank " + f"{int(sc['rank'])}", + flush=True, + ) return self._cover def kbatch_cover(self, point_list, prime_vec, Nt): @@ -237,9 +293,10 @@ def kbatch_cover(self, point_list, prime_vec, Nt): if tapes is None or not point_list: return self.kbatch(point_list, prime_vec, Nt) run = self.run - M = np.vstack([np.asarray(pp[:run.n_leaves], dtype=np.int64) for pp in point_list]) - return _core.sym_obs_null_batch(tapes, run.n_leaves, run.n_states, run.z_slots, M, list(prime_vec), - int(Nt), run.cores) + M = np.vstack([np.asarray(pp[: run.n_leaves], dtype=np.int64) for pp in point_list]) + return _core.sym_obs_null_batch( + tapes, run.n_leaves, run.n_states, run.z_slots, M, list(prime_vec), int(Nt), run.cores + ) def lanes(self): """Whether each column of V annihilates the rows of the cover at each of many points, from jets seeded @@ -252,12 +309,22 @@ def lanes(self): def f(points, primes, Nt, V, tapes=None): if tapes is None: tapes = self.cover_tapes() or run.kernel_tapes() - M = np.vstack([np.asarray(pp[:run.n_leaves], dtype=np.int64) for pp in points]) - o = _core.sym_obs_annihilates_batch(tapes, run.n_leaves, run.n_states, run.z_slots, M, list(primes), - int(Nt), np.asarray(V, dtype=np.int64) % int(primes[0]), run.cores) + M = np.vstack([np.asarray(pp[: run.n_leaves], dtype=np.int64) for pp in points]) + o = _core.sym_obs_annihilates_batch( + tapes, + run.n_leaves, + run.n_states, + run.z_slots, + M, + list(primes), + int(Nt), + np.asarray(V, dtype=np.int64) % int(primes[0]), + run.cores, + ) if o is None: return None return [np.asarray(x["zero"], dtype=bool) if ok(x) else None for x in o] + return f def dir_batch(self): @@ -267,10 +334,19 @@ def dir_batch(self): return None def f(pt, q, Nt, V): - o = _core.sym_obs_annihilates(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, - np.asarray(pt[:run.n_leaves], dtype=np.int64), q, run.exact_nt(Nt), - np.asarray(V, dtype=np.int64) % q, run.cores) + o = _core.sym_obs_annihilates( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + np.asarray(pt[: run.n_leaves], dtype=np.int64), + q, + run.exact_nt(Nt), + np.asarray(V, dtype=np.int64) % q, + run.cores, + ) return [bool(x) for x in np.atleast_1d(o["zero"])] if ok(o) else None + return f def dir_call(self): @@ -280,9 +356,17 @@ def dir_call(self): return None def f(pt, q, Nt, v): - o = _core.sym_obs_directional(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, - np.asarray(pt[:run.n_leaves], dtype=np.int64), q, run.exact_nt(Nt), - np.asarray(v, dtype=np.float64), run.cores) + o = _core.sym_obs_directional( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + np.asarray(pt[: run.n_leaves], dtype=np.int64), + q, + run.exact_nt(Nt), + np.asarray(v, dtype=np.float64), + run.cores, + ) if not ok(o): return None if not o.get("zero"): @@ -292,8 +376,8 @@ def f(pt, q, Nt, v): rel_m = self.sys.relation_rows(pt, q) if rel_m is None: return None - return bool(np.all(np.asarray(rel_m % q, dtype=object) @ - (np.asarray(v, dtype=object) % q) % q == 0)) + return bool(np.all(np.asarray(rel_m % q, dtype=object) @ (np.asarray(v, dtype=object) % q) % q == 0)) + return f def exact_scalings(self, fixed): @@ -327,8 +411,7 @@ def _sat_caps(self, orders, point, Mtot, first): """Each chain at the order of the chain plus the plateau during the saturation.""" run = self.run nb = self.sys.kc if self.joint else (len(run.chain_groups) if run.chain_groups else 0) - if not (run.has_gaps and len(orders) == nb - and (self.joint or not run.ss_constraint)): + if not (run.has_gaps and len(orders) == nb and (self.joint or not run.ss_constraint)): return cap0 = [int(o) + _plateau() for o in orders] run.nt_cap = cap0 @@ -343,9 +426,9 @@ def cap_rank(): swallow(exc, "joint cap") r = None return rank_score(r) if ok(r) else None + if self._lower_caps(cap0, cap_rank) and state.env("LIEDIAG"): - print(f"[liediag] joint caps in the saturation at gap order {Mtot}: " - f"{','.join(map(str, run.nt_cap))}") + print(f"[liediag] joint caps in the saturation at gap order {Mtot}: {','.join(map(str, run.nt_cap))}") def _block_map(self, block_call, block_profile): run = self.run @@ -374,7 +457,7 @@ def _scaling_cap(self): return not_fixed = {z for z in self.znames if z not in self.zsn} | set(sys.state_base) self.scal_ws = self.exact_scalings([l for l in run.leaf_names if l not in not_fixed]) - shared = self.znames[:sys.n_shared] + shared = self.znames[: sys.n_shared] rows = [] for v in self.scal_ws: x = np.zeros(sys.n_shared, dtype=np.int64) @@ -383,16 +466,18 @@ def _scaling_cap(self): x[shared.index(k)] = _int_weight(w, PRIMES[0]) rows.append(x) if rows: - self.rank_cap = self.nz - int(_core.sym_rref_mod(np.vstack(rows).astype(np.float64), - PRIMES[0])["rank"]) + self.rank_cap = self.nz - int(_core.sym_rref_mod(np.vstack(rows).astype(np.float64), PRIMES[0])["rank"]) def saturate(self): """The saturated kernel at a generic base point, or None.""" run, sys, multi = self.run, self.sys, self.multi block_call = sys.block_calls() block_profile = sys.block_profiles() - budget = None if run.has_gaps or self.codim_spec is None or run.nuis_cols else \ - int(self.codim_spec) + 2 * len(self.recast) + int(multi.get("exp_codim") or 0) + budget = ( + None + if run.has_gaps or self.codim_spec is None or run.nuis_cols + else int(self.codim_spec) + 2 * len(self.recast) + int(multi.get("exp_codim") or 0) + ) block_map = self._block_map(block_call, block_profile) if self.joint: reach = [run.chain_groups[run.chain_idx[ci]] if run.has_gaps else [ci] for ci in sys.equil_conds] @@ -405,28 +490,45 @@ def saturate(self): if len(nt_min_block) != len(block_call): nt_min_block = None self._scaling_cap() - self.stacked_first = (((not run.ss_constraint and not run.has_gaps) - or (self.joint and run.has_gaps and self.rank_cap < self.nz)) - and not self.recast and self.nz > state.get("stacked_min", 150) - and state.get("stacked_first") is not False and not state.get("inner") - and state.get("order_hint") is None) + self.stacked_first = ( + ((not run.ss_constraint and not run.has_gaps) or (self.joint and run.has_gaps and self.rank_cap < self.nz)) + and not self.recast + and self.nz > state.get("stacked_min", 150) + and state.get("stacked_first") is not False + and not state.get("inner") + and state.get("order_hint") is None + ) self.stacked_quick = self.stacked_first and bool(state.get("stacked_quick")) if self.stacked_first: block_call, block_profile, block_map = None, None, None - sc = saturate_certify(self.kcall_sat, self.n_aug, self.nz, run.max_gap, - warm=self._warm_probe if self.joint else (lambda pts, primes: None), - probe_block=max(1, min(8, run.cores)), block_call=block_call, - budget=budget, block_map=block_map, nt_min=max(floor, lie_reach_max(multi["tapes"])), - nt_min_block=nt_min_block, prep=sys.sat_prep if self.joint else None, - rank_cap=self.rank_cap, block_profile=block_profile, set_caps=self._sat_caps, - checks=not (self.stacked_first and (not self.stacked_quick or run.ss_constraint)), - longest_first=run.has_gaps and not self.joint, - stacked_profile=sys.stacked_profile() if self.stacked_first else None) + sc = saturate_certify( + self.kcall_sat, + self.n_aug, + self.nz, + run.max_gap, + warm=self._warm_probe if self.joint else (lambda pts, primes: None), + probe_block=max(1, min(8, run.cores)), + block_call=block_call, + budget=budget, + block_map=block_map, + nt_min=max(floor, lie_reach_max(multi["tapes"])), + nt_min_block=nt_min_block, + prep=sys.sat_prep if self.joint else None, + rank_cap=self.rank_cap, + block_profile=block_profile, + set_caps=self._sat_caps, + checks=not (self.stacked_first and (not self.stacked_quick or run.ss_constraint)), + longest_first=run.has_gaps and not self.joint, + stacked_profile=sys.stacked_profile() if self.stacked_first else None, + ) if sc is None: if run.ss_constraint and run.ss_why is not None: - warnings.warn("no steady-state point over the finite field after " - f"the generic-point retries ({run.ss_why}). The equilibrate constraint " - "could not be evaluated.", stacklevel=2) + warnings.warn( + "no steady-state point over the finite field after " + f"the generic-point retries ({run.ss_why}). The equilibrate constraint " + "could not be evaluated.", + stacklevel=2, + ) return None if sc["ref"].get("block_rank"): rc = self.kcall4(sc["point0"], PRIMES[0], sc["nt_used"], sc.get("mtot_used") or 0) @@ -439,11 +541,18 @@ def saturate(self): def _gap_proof(self, sc): """Gap order raised until the truncated rank reaches the gapcert bound; False without a bound or at the cap.""" from ..gapcert import gap_bound + run = self.run if self.joint or not run.chain_groups or self.recast: return False - b = gap_bound(self.multi["tapes"], run.chain_groups, list(self.znames), int(sc["nt_used"]), verify_prime(), - session.current().rng("gap.bound", ",".join(self.znames))) + b = gap_bound( + self.multi["tapes"], + run.chain_groups, + list(self.znames), + int(sc["nt_used"]), + verify_prime(), + session.current().rng("gap.bound", ",".join(self.znames)), + ) self.gap_bound = b if b["bound"] is None: return False @@ -468,8 +577,10 @@ def _gap_proof(self, sc): def _gap_reached(self, rank, b): """Whether the truncated `rank` reaches the bound of `b`; a rank above it marks the bound inconsistent.""" if rank > b["bound"]: - session.note("limits", f"gap bound: the truncated rank {rank} exceeds the bound {b['bound']}, " - "so the bound is not taken") + session.note( + "limits", + f"gap bound: the truncated rank {rank} exceeds the bound {b['bound']}, so the bound is not taken", + ) b["inconsistent"] = True return False return rank == b["bound"] @@ -493,9 +604,11 @@ def _gap_why(self, sc): stop = sc.get("gap_stop") or "cap" if rank_of(sc["ref"]) >= self.rank_cap or stop == "full": return None - return {"plateau": f"the rank did not grow from gap order {run.mtot - 1} to {run.mtot}", - "cap": f"reconst_control(gap_order_cap={run.max_gap}) reached", - "failed": f"no kernel past gap order {run.mtot}"}[stop] + return { + "plateau": f"the rank did not grow from gap order {run.mtot - 1} to {run.mtot}", + "cap": f"reconst_control(gap_order_cap={run.max_gap}) reached", + "failed": f"no kernel past gap order {run.mtot}", + }[stop] def _cert_segments(self, sc, p=None, tries=24): """The certificate inputs: chains of tapes, a seed per chain, at rest a start per chain, and the points drawn @@ -516,21 +629,24 @@ def _cert_segments(self, sc, p=None, tries=24): if all(s0 is not None for s0 in sols): return segs, [np.asarray(s0["ptc"], dtype=np.int64) % p for s0 in sols], base, k return segs, [None] * len(sys.equil_conds), base, tries - segs = [run.chain_tapes(idx) for idx in run.chain_groups] if run.has_gaps else \ - [[t] for t in run.tapes] - return segs, [np.asarray(sc["point0"][:run.n_leaves], dtype=np.int64)] * len(segs), None, 1 + segs = [run.chain_tapes(idx) for idx in run.chain_groups] if run.has_gaps else [[t] for t in run.tapes] + return segs, [np.asarray(sc["point0"][: run.n_leaves], dtype=np.int64)] * len(segs), None, 1 def certify(self, sc): """The proven Lie order per block, then the per-chain caps lowered.""" run = self.run run.nt_cap = [] # a full rank, or a rank at the cap set by the exact scalings, cannot rise with the order - sc["certified"] = rank_of(sc["ref"]) >= self.nz or \ - (self.rank_cap < self.nz and rank_of(sc["ref"]) >= self.rank_cap) + sc["certified"] = rank_of(sc["ref"]) >= self.nz or ( + self.rank_cap < self.nz and rank_of(sc["ref"]) >= self.rank_cap + ) sc["order_bound"] = 0.0 if sc["certified"] else None hint = state.get("order_hint") - if hint is not None and hint.get("certified") is not False and \ - list(sc.get("block_orders") or []) == list(hint.get("block_orders") or []): + if ( + hint is not None + and hint.get("certified") is not False + and list(sc.get("block_orders") or []) == list(hint.get("block_orders") or []) + ): sc["certified"] = True sc["cert_orders"] = True sc["order_bound"] = hint.get("order_bound") @@ -541,8 +657,12 @@ def certify(self, sc): if not sc["certified"] and not self.stacked_first and not run.nuis_cols and not start_pow: self._certificate(sc) nb = self.sys.kc if self.joint else (len(run.chain_groups) if run.chain_groups else -1) - if run.has_gaps and (self.joint or not run.ss_constraint) and \ - sc.get("block_orders") is not None and len(sc["block_orders"]) == nb: + if ( + run.has_gaps + and (self.joint or not run.ss_constraint) + and sc.get("block_orders") is not None + and len(sc["block_orders"]) == nb + ): add = 0 if sc.get("cert_orders") else _plateau() run.nt_cap = [int(o) + add for o in sc["block_orders"]] run.stage("Lie order certified") @@ -556,6 +676,7 @@ def cap_rank(): swallow(exc, "joint block caps") r = None return rank_score(r) if ok(r) else None + self._lower_caps(list(run.nt_cap), cap_rank) if state.env("LIEDIAG"): print(f"[liediag] joint block Lie orders: {','.join(map(str, run.nt_cap))}") @@ -564,6 +685,7 @@ def _cert_degrees(self, sc): """(degrees, why): per certificate block the total degrees of each segment and of the initial values, at rest the Bezout number of the resting balances; None where a block has none.""" from ..bound import _vector_degree, no_degree, total_degrees + run, tapes = self.run, self.multi["tapes"] groups = run.chain_groups if run.has_gaps else [[i] for i in range(len(tapes))] if self.joint: @@ -576,8 +698,11 @@ def _cert_degrees(self, sc): for i in idx: t = tapes[i] ml = strs(t.get("jet_f") or t.get("model_lines")) - ol = [f"_y{j} = {e}" for j, e in enumerate(strs(t["jet_g"]))] if t.get("jet_f") else \ - strs(t.get("obs_lines")) + ol = ( + [f"_y{j} = {e}" for j, e in enumerate(strs(t["jet_g"]))] + if t.get("jet_f") + else strs(t.get("obs_lines")) + ) key = (tuple(ml), tuple(ol)) if key not in memo: memo[key] = total_degrees(ml, ol) @@ -617,6 +742,7 @@ def _cert_degrees(self, sc): def _event_degree(evs): """The degree of the event values `evs` in all their symbols, 0 without events.""" from ..bound import _vector_degree + vals = [model_sympify(str(e["value"])) for e in (evs or []) if isinstance(e, dict)] return _vector_degree(vals) if vals else 0 @@ -652,24 +778,38 @@ def _certificate(self, sc): orders, terms, draws = None, [], [] if all(s is not None and len(s) > 0 for s in seeds) and cap >= 1: try: - orders = lie_certificate(segs, seeds, run.n_leaves, run.n_states, - self.sys.z_slots_local if self.joint else run.z_slots, - P1 if degs is None else q, cap=cap, - map_fn=mapf, threads=threads, - start=self._cert_start(sc, len(segs)), degs=degs, terms=terms, - at_rest=self.joint, start_seeds=starts if degs is not None else None, - start_p=P1 if self.joint and degs is not None else None, - rest_draws=rest_draws, draws=draws, - drop_states=run.known_states if not (self.joint or run.has_gaps) else (), - cores=run.cores) + orders = lie_certificate( + segs, + seeds, + run.n_leaves, + run.n_states, + self.sys.z_slots_local if self.joint else run.z_slots, + P1 if degs is None else q, + cap=cap, + map_fn=mapf, + threads=threads, + start=self._cert_start(sc, len(segs)), + degs=degs, + terms=terms, + at_rest=self.joint, + start_seeds=starts if degs is not None else None, + start_p=P1 if self.joint and degs is not None else None, + rest_draws=rest_draws, + draws=draws, + drop_states=run.known_states if not (self.joint or run.has_gaps) else (), + cores=run.cores, + ) except Exception as e: swallow(e, "Lie order certificate") if state.env("LIEDIAG"): print(f"[liediag] certificate failed: {e}") orders = None if orders is not None and len(orders) == len(segs) and not all(o is None for o in orders): - bo = list(sc["block_orders"]) if sc.get("block_orders") is not None and \ - len(sc["block_orders"]) == len(orders) else [int(sc["nt_used"])] * len(orders) + bo = ( + list(sc["block_orders"]) + if sc.get("block_orders") is not None and len(sc["block_orders"]) == len(orders) + else [int(sc["nt_used"])] * len(orders) + ) ordv = [bo[i] + _plateau() if o is None else int(o) for i, o in enumerate(orders)] need = max([1, *ordv]) try: @@ -679,26 +819,47 @@ def _certificate(self, sc): rc = None if ok(rc) and rank_of(rc) < rank_of(sc["ref"]): # an order below the one the scan needed cannot be sufficient - session.note("limits", f"Lie order certificate: the rank at the certified order {need} is below " - f"the rank of the scan at order {int(sc['nt_used'])}; the scanned order " - "is kept") + session.note( + "limits", + f"Lie order certificate: the rank at the certified order {need} is below " + f"the rank of the scan at order {int(sc['nt_used'])}; the scanned order " + "is kept", + ) sc.update(certified=False, uncertified=list(range(len(orders)))) elif ok(rc): cert = all(o is not None for o in orders) - sc.update(ref=rc, nt_used=need, rank=rc["rank"], rank_s=rank_of(rc), pivots=rc["pivots"], - block_orders=ordv, block_driver=int(np.argmax(ordv)), certified=cert, - uncertified=[i for i, o in enumerate(orders) if o is None], cert_orders=True, - order_bound=(float(sum(terms)) if cert and len(terms) == len(orders) and - all(t is not None for t in terms) else None)) + sc.update( + ref=rc, + nt_used=need, + rank=rc["rank"], + rank_s=rank_of(rc), + pivots=rc["pivots"], + block_orders=ordv, + block_driver=int(np.argmax(ordv)), + certified=cert, + uncertified=[i for i, o in enumerate(orders) if o is None], + cert_orders=True, + order_bound=( + float(sum(terms)) + if cert and len(terms) == len(orders) and all(t is not None for t in terms) + else None + ), + ) if sc["order_bound"] is not None and sc["order_bound"] >= 1: # a chance of one or more bounds nothing: the degrees reach the verification prime sc["order_bound"] = None sc["order_bound_why"] = f"the Schwartz-Zippel bound reaches 1 at the verification prime {q}" - sc["order_draws"] = max(draws) if sc["order_bound"] is not None and draws and \ - all(d is not None for d in draws) else None + sc["order_draws"] = ( + max(draws) + if sc["order_bound"] is not None and draws and all(d is not None for d in draws) + else None + ) if cap == chain_end and (orders is None or any(o is None for o in orders)): - session.note("limits", f"Lie order certificate: no start reached the generic rank up to order {cap}, " - "the end of the jet chains of the inputs; the order is not proven sufficient") + session.note( + "limits", + f"Lie order certificate: no start reached the generic rank up to order {cap}, " + "the end of the jet chains of the inputs; the order is not proven sufficient", + ) if state.env("LIEDIAG"): print(f"[liediag] certified block orders: {orders}") @@ -729,27 +890,41 @@ def execute(self): gap_why, gap_used = None, self.gap_bound elif gap_why is not None and getattr(self, "gap_bound", None) is not None: b = self.gap_bound - gap_why += (f" (no rank bound: {b['why']})" if b["bound"] is None else - f" (the rank exceeds the bound {b['bound']})" if b.get("inconsistent") else - f" (the rank stays below the bound {b['bound']} up to the cap)") + gap_why += ( + f" (no rank bound: {b['why']})" + if b["bound"] is None + else f" (the rank exceeds the bound {b['bound']})" + if b.get("inconsistent") + else f" (the rank stays below the bound {b['bound']} up to the cap)" + ) nz, n_seg = self.nz, len(self.multi["tapes"]) - result = {"method": "observability", "engine": "analytic", - "conditions": n_seg if self.n_conditions is None else int(self.n_conditions), - "coordinates": list(self.znames), "segments": n_seg, - "gap_order_used": 0 if run.series_gaps else run.mtot, - "identifiable": sc["rank_s"] == nz, "rank": int(sc["rank_s"]), "dim": int(nz), - "lie_order_used": int(sc["nt_used"]), "lie_order_driver": sc.get("block_driver"), - "lie_uncertified": sc.get("uncertified"), "lie_plateau": sc.get("plateau"), - "lie_certified": bool(sc.get("certified")), "lie_block_orders": sc.get("block_orders"), - "gap_certified": None if not run.has_gaps or run.series_gaps else gap_why is None, - "gap_certificate": None if run.series_gaps else gap_why, - "series_certified": gap_why is None if run.series_gaps else None, - "series_certificate": gap_why if run.series_gaps else None, - "gap_bound": None if gap_used is None else int(gap_used["bound"]), - "order_bound": self._order_bound(sc, gap_used)[0], - "order_bound_why": self._order_bound(sc, gap_used)[1], - "order_draws": sc.get("order_draws") if self._order_bound(sc, gap_used)[0] is not None else None, - "sat_score": rank_score(sc["ref"]), "non_identifiable": []} + result = { + "method": "observability", + "engine": "analytic", + "conditions": n_seg if self.n_conditions is None else int(self.n_conditions), + "coordinates": list(self.znames), + "segments": n_seg, + "gap_order_used": 0 if run.series_gaps else run.mtot, + "identifiable": sc["rank_s"] == nz, + "rank": int(sc["rank_s"]), + "dim": int(nz), + "lie_order_used": int(sc["nt_used"]), + "lie_order_driver": sc.get("block_driver"), + "lie_uncertified": sc.get("uncertified"), + "lie_plateau": sc.get("plateau"), + "lie_certified": bool(sc.get("certified")), + "lie_block_orders": sc.get("block_orders"), + "gap_certified": None if not run.has_gaps or run.series_gaps else gap_why is None, + "gap_certificate": None if run.series_gaps else gap_why, + "series_certified": gap_why is None if run.series_gaps else None, + "series_certificate": gap_why if run.series_gaps else None, + "gap_bound": None if gap_used is None else int(gap_used["bound"]), + "order_bound": self._order_bound(sc, gap_used)[0], + "order_bound_why": self._order_bound(sc, gap_used)[1], + "order_draws": sc.get("order_draws") if self._order_bound(sc, gap_used)[0] is not None else None, + "sat_score": rank_score(sc["ref"]), + "non_identifiable": [], + } self.phys_params0 = [z for z in self.znames if z not in self.zsn] if self.joint: result["dim"] = len(self.phys_params0) @@ -764,27 +939,30 @@ def execute(self): result["rank"] = len(coords) self.gap_dirs = self._gap_dirs() if run.nuis_cols: - result["nuisance"] = {"names": [self.znames[i] for i in run.nuis_cols], - "pinned": int(sc["ref"].get("nuisance_pinned") or 0), - "exact_order": int(run.nuis_order), - "short": sc["rank_s"] != nz and - int(sc["nt_used"]) + (0 if run.series_gaps else run.mtot) + - (_margin() if self.verify else 0) > int(run.nuis_order)} + result["nuisance"] = { + "names": [self.znames[i] for i in run.nuis_cols], + "pinned": int(sc["ref"].get("nuisance_pinned") or 0), + "exact_order": int(run.nuis_order), + "short": sc["rank_s"] != nz + and int(sc["nt_used"]) + (0 if run.series_gaps else run.mtot) + (_margin() if self.verify else 0) + > int(run.nuis_order), + } if run.nuis_cols: result["projection"] = self._projection(sc) elif self.joint and not self._jx_regular(sc): - result["projection"] = {"status": "unchecked", - "of": "the resting states, whose Jacobian is singular at the base point"} + result["projection"] = { + "status": "unchecked", + "of": "the resting states, whose Jacobian is singular at the base point", + } if run.nuis_order is not None and not run.nuis_cols: # the chains of known inputs: exact up to their order, a polynomial stand-in past it - result["known_short"] = sc["rank_s"] != nz and \ - int(sc["nt_used"]) + (0 if run.series_gaps else run.mtot) + \ - (_margin() if self.verify else 0) > int(run.nuis_order) + result["known_short"] = sc["rank_s"] != nz and int(sc["nt_used"]) + (0 if run.series_gaps else run.mtot) + ( + _margin() if self.verify else 0 + ) > int(run.nuis_order) if sc["rank_s"] == nz: return self._modulo_nuisance(result) if self.joint: - self.scal_fixed = [l for l in run.leaf_names - if l not in set(self.phys_params0) | set(self.sys.state_base)] + self.scal_fixed = [l for l in run.leaf_names if l not in set(self.phys_params0) | set(self.sys.state_base)] else: self.scal_fixed = [l for l in run.leaf_names if l not in set(self.znames)] if self.joint and any(self.sys.cont_active(ci) for ci in self.sys.equil_conds): @@ -801,19 +979,35 @@ def _gap_dirs(self): sc = self.sc if sc["rank_s"] >= sc["rank"]: return [] - sr = _core.sym_series_rank(np.asarray(sc["ref"]["S"], dtype=np.int64), int(self.nz), - int(sc["ref"]["N"]), PRIMES[0], [], support=True, cores=int(self.run.cores)) + sr = _core.sym_series_rank( + np.asarray(sc["ref"]["S"], dtype=np.int64), + int(self.nz), + int(sc["ref"]["N"]), + PRIMES[0], + [], + support=True, + cores=int(self.run.cores), + ) supp = [int(x) for x in np.atleast_1d(sr["support"]) if int(x) not in set(self.run.nuis_cols)] - return [{"support": sym_sort([self.znames[i] for i in supp]), "type": "general", - "closed_form": False, "reason": "depends on the time between events"} - for _ in range(sc["rank"] - sc["rank_s"])] + return [ + { + "support": sym_sort([self.znames[i] for i in supp]), + "type": "general", + "closed_form": False, + "reason": "depends on the time between events", + } + for _ in range(sc["rank"] - sc["rank_s"]) + ] def _modulo_nuisance(self, result): """The report without the nuisance coordinates, their components moved to "input_vector".""" if not self.run.nuis_cols: return result - aux = result["nuisance"]["names"] + (list(self.atom_names) if self.transient else []) + \ - (list(self.zsn) if self.joint else []) + aux = ( + result["nuisance"]["names"] + + (list(self.atom_names) if self.transient else []) + + (list(self.zsn) if self.joint else []) + ) return report_physical(result, self.znames, aux, self.sc, self.nz, PRIMES[0], "input_vector") def _physical(self, result): @@ -821,21 +1015,34 @@ def _physical(self, result): coordinates.""" if self.joint: # the atoms of exponential leaves leave the joint report with the state columns - result = report_physical(result, self.znames, list(self.zsn) + list(self.atom_names), self.sc, - self.nz, PRIMES[0], "state_vector", flag_joint=True) + result = report_physical( + result, + self.znames, + list(self.zsn) + list(self.atom_names), + self.sc, + self.nz, + PRIMES[0], + "state_vector", + flag_joint=True, + ) elif self.transient: - result = report_physical(result, self.znames, self.atom_names, self.sc, self.nz, - PRIMES[0], "recast_vector") + result = report_physical(result, self.znames, self.atom_names, self.sc, self.nz, PRIMES[0], "recast_vector") return self._modulo_nuisance(result) def static_fields(self): """Fields of the static subsystems of the resting conditions at the solved point.""" run, sys = self.run, self.sys - return static_fields(self.multi, sys.models, sys.equil_conds, - [run.chain_groups[run.chain_idx[ci]] if run.has_gaps else [ci] - for ci in sys.equil_conds], - self.phys_params0, run.leaf_names, self.point0_solved, - strs(self.multi.get("forcings")), [sys.zero_of(ci) for ci in sys.equil_conds]) + return static_fields( + self.multi, + sys.models, + sys.equil_conds, + [run.chain_groups[run.chain_idx[ci]] if run.has_gaps else [ci] for ci in sys.equil_conds], + self.phys_params0, + run.leaf_names, + self.point0_solved, + strs(self.multi.get("forcings")), + [sys.zero_of(ci) for ci in sys.equil_conds], + ) def _continued(self, result): """Kernel directions of continued conditions by scalings, static fields or a direct point; None to go on.""" @@ -845,16 +1052,27 @@ def _continued(self, result): result["rank"] = int(result["dim"] - ker_dim) result["coordinates"] = self.phys_params0 chosen = self._scalings_and_statics(ker_dim) - if len(chosen) < ker_dim and self.closed_form and not self.stacked_quick and \ - not self.stacked_first and self._direct_kernel(ker_dim): + if ( + len(chosen) < ker_dim + and self.closed_form + and not self.stacked_quick + and not self.stacked_first + and self._direct_kernel(ker_dim) + ): result["rank"] = rank0 result["coordinates"] = coords0 result["series_certified"] = result["series_certificate"] = None self.gap_dirs = self._gap_dirs() return None result["non_identifiable"] = chosen + [ - {"support": [], "type": "general", "closed_form": False, - "reason": "not reconstructed along the continuation"} for _ in range(ker_dim - len(chosen))] + { + "support": [], + "type": "general", + "closed_form": False, + "reason": "not reconstructed along the continuation", + } + for _ in range(ker_dim - len(chosen)) + ] run = self.run self.field_chains = run.chain_groups if run.has_gaps else [[i] for i in range(len(self.multi["tapes"]))] self.field_joint = {"conds": self.sys.equil_conds, "solve": self.sys.solve_cond} @@ -876,6 +1094,7 @@ def _scalings_and_statics(self, ker_dim): def grows(r2): return int(_core.sym_rref_mod(r2.astype(np.float64), P0)["rank"]) > rows.shape[0] + for v in ws: if any(k in pp and not re.fullmatch(r"-?[0-9]+", str(w)) for k, w in v.items()): continue @@ -887,13 +1106,14 @@ def grows(r2): if grows(r2): rows = r2 vv = {k: str(w) for k, w in v.items() if k in pp and str(w) != "0"} - chosen.append({"support": sym_sort(list(vv)), "vector": vv, "type": "scaling", - "closed_form": True, "exact": True}) + chosen.append( + {"support": sym_sort(list(vv)), "vector": vv, "type": "scaling", "closed_form": True, "exact": True} + ) if len(chosen) == ker_dim: break if len(chosen) < ker_dim: stf = self.static_fields() - for f in (stf or []): + for f in stf or []: r2 = np.vstack([rows, f["lval"]]) if grows(r2): rows = r2 @@ -901,8 +1121,10 @@ def grows(r2): if len(chosen) == ker_dim: break if self.run.timing: - print(f"[sym] static subsystems: {len(stf or [])} field(s), {len(chosen)} of " - f"{ker_dim} directions with the scalings") + print( + f"[sym] static subsystems: {len(stf or [])} field(s), {len(chosen)} of " + f"{ker_dim} directions with the scalings" + ) return chosen def _direct_kernel(self, ker_dim): @@ -915,8 +1137,9 @@ def _direct_kernel(self, ker_dim): for i in range(len(sys.cont_off)): sys.cont_off[i] = True # under the diagonal start the base point need not solve directly, other points may - bases = [self.point0_solved] + ([random_point(len(self.point0_solved), seed=k) - for k in range(1, 4)] if sys.diag is not None else []) + bases = [self.point0_solved] + ( + [random_point(len(self.point0_solved), seed=k) for k in range(1, 4)] if sys.diag is not None else [] + ) pt_d = None for base in bases: try: @@ -935,10 +1158,15 @@ def _direct_kernel(self, ker_dim): rc = {"ok": False, "why": str(e)} direct = ok(rc) and nz - rank_of(rc) == ker_dim if state.env("LIEDIAG"): - print("[liediag] direct kernel for the continued conditions: " + - (f"no point: {rc.get('why')}" if not ok(rc) else - f"dimension {nz - rank_of(rc)} (rank {rc['rank']}, series {rank_of(rc)}), " - f"series kernel {ker_dim}")) + print( + "[liediag] direct kernel for the continued conditions: " + + ( + f"no point: {rc.get('why')}" + if not ok(rc) + else f"dimension {nz - rank_of(rc)} (rank {rc['rank']}, series {rank_of(rc)}), " + f"series kernel {ker_dim}" + ) + ) if not direct: sys.cont_off[:] = cont_saved if chained: @@ -952,16 +1180,20 @@ def _direct_kernel(self, ker_dim): def _peel(self): """The exact scalings of the model as tangents in the nullspace.""" from ...sym.scaling import scaling_symmetries_multi + tapes = self.multi["tapes"] if self.joint else scaling_tapes(self.multi) model_lines = [strs(t.get("model_lines")) for t in tapes] obs_lines = [strs(t.get("obs_lines")) for t in tapes] keys = ["\n".join([*m, "\x1f", *o]) for m, o in zip(model_lines, obs_lines)] keep = [i for i, k in enumerate(keys) if k not in keys[:i]] try: - res = scaling_symmetries_multi(per_cond_model=[model_lines[i] for i in keep], - per_cond_obs=[obs_lines[i] for i in keep], - inputs=strs(self.multi.get("forcings")) or None, - fixed=self.scal_fixed or None, recast=self.recast or None) + res = scaling_symmetries_multi( + per_cond_model=[model_lines[i] for i in keep], + per_cond_obs=[obs_lines[i] for i in keep], + inputs=strs(self.multi.get("forcings")) or None, + fixed=self.scal_fixed or None, + recast=self.recast or None, + ) except Exception as exc: swallow(exc, "scalings of the model") res = None @@ -971,35 +1203,52 @@ def _peel(self): def lift(w): # a scaling acts on the states by the scaling weights; with unknown inputs the lift gives their change - return {x: scaling_component(v, x) for x, v in w.items() if x in states and str(v) != "0"} \ - if self.run.nuis_cols else None - dirs = [{"vector": dict(w), "exact": True, "state_components": lift(w)} for w in ws] + \ - [dict(d, exact=_in_rational_span(d["vector"], ws)) for d in (res or {}).get("non_identifiable", [])] + return ( + {x: scaling_component(v, x) for x, v in w.items() if x in states and str(v) != "0"} + if self.run.nuis_cols + else None + ) + + dirs = [{"vector": dict(w), "exact": True, "state_components": lift(w)} for w in ws] + [ + dict(d, exact=_in_rational_span(d["vector"], ws)) for d in (res or {}).get("non_identifiable", []) + ] res = dict(res or {}, non_identifiable=dirs) if self.joint: sys = self.sys res = joint_expand_scal(res, sys.state_base, sys.kc, sys.held_param_of, sys.pinned()) res["non_identifiable"] = list(res["non_identifiable"]) + self._condition_scalings( - model_lines, obs_lines, keys, keep, [d["vector"] for d in res["non_identifiable"]]) + model_lines, obs_lines, keys, keep, [d["vector"] for d in res["non_identifiable"]] + ) if not res["non_identifiable"]: return [], np.zeros((self.nz, 0), dtype=np.int64) - peel = peel_scalings(res, self.znames, self.nz, np.asarray(self.sc["point0"])[self.z_slots], - PRIMES[0], self.N, - modulo=(self.free_cols, self.run.nuis_cols) if self.run.nuis_cols else None, - shifts={str(r["L"]) for r in self.recast or [] if not r.get("inverted")}) + peel = peel_scalings( + res, + self.znames, + self.nz, + np.asarray(self.sc["point0"])[self.z_slots], + PRIMES[0], + self.N, + modulo=(self.free_cols, self.run.nuis_cols) if self.run.nuis_cols else None, + shifts={str(r["L"]) for r in self.recast or [] if not r.get("inverted")}, + ) return peel["scaling"], peel["Bmat"] def _condition_scalings(self, model_lines, obs_lines, keys, keep, known): """Exact scalings whose state weights differ between the resting conditions, each checked on every tape with the state weights of the condition of the tape; those in the span of `known` are left out.""" from ...sym.scaling import scaling_symmetries_per_condition, verify_scalings + sys = self.sys tapes = self.multi["tapes"] rest = [strs(tapes[i].get("ver_rest")) for i in keep] try: found = scaling_symmetries_per_condition( - [model_lines[i] for i in keep], [obs_lines[i] for i in keep], - inputs=strs(self.multi.get("forcings")) or None, fixed=self.scal_fixed or None, extra_model=rest) + [model_lines[i] for i in keep], + [obs_lines[i] for i in keep], + inputs=strs(self.multi.get("forcings")) or None, + fixed=self.scal_fixed or None, + extra_model=rest, + ) except Exception as exc: swallow(exc, "scalings per condition") return [] @@ -1041,6 +1290,7 @@ def _condition_scalings(self, model_lines, obs_lines, keys, keep, known): def _residual(self, result): """Scalings peeled, the residual directions reconstructed, the rank proven.""" from .reconstruct import Reconstruction + sc, run, nz, P = self.sc, self.run, self.nz, PRIMES[0] piv = {int(x) for x in np.atleast_1d(sc["pivots"])} self.free_cols = [c for c in range(nz) if c not in piv] @@ -1054,8 +1304,12 @@ def _residual(self, result): residual = [] bfs = [null_residues(sc["ref"], fc, P).reshape(nz, 1) for fc in self.free_cols] if bfs: - piv = {int(x) for x in np.atleast_1d(_core.sym_rref_mod( - np.concatenate([B.reshape(nz, -1)] + bfs, axis=1).astype(np.float64), P)["piv"])} + piv = { + int(x) + for x in np.atleast_1d( + _core.sym_rref_mod(np.concatenate([B.reshape(nz, -1)] + bfs, axis=1).astype(np.float64), P)["piv"] + ) + } keep = [j for j in range(len(bfs)) if scal_cols + j in piv] residual = [self.free_cols[j] for j in keep] B = np.concatenate([B.reshape(nz, -1)] + [bfs[j] for j in keep], axis=1) @@ -1073,8 +1327,13 @@ def _residual(self, result): support = [] for fc in residual: v = null_residues(sc["ref"], fc, P) - support.append({"support": sym_sort([self.znames[i] for i in np.nonzero(v)[0]]), - "type": "general", "closed_form": False}) + support.append( + { + "support": sym_sort([self.znames[i] for i in np.nonzero(v)[0]]), + "type": "general", + "closed_form": False, + } + ) result["non_identifiable"] = self.scaling + support + self.gap_dirs run.stage("reconstruction") result = self._physical(result) @@ -1085,6 +1344,7 @@ def _residual(self, result): run.stage("field proof") if not state.get("inner"): from .proof import chain_bound + result["bound"] = chain_bound(self, result) kernel = {"coords": list(self.znames), "N": self.N, "p": P} if state.get("random_kernel"): @@ -1094,9 +1354,12 @@ def _residual(self, result): return {"rerun_blocks": True} result["kernel"] = kernel if not self.closed_form: - result["non_identifiable"] = [d if d.get("type") == "scaling" else - {"support": d.get("support"), "type": d.get("type"), - "closed_form": False} for d in result["non_identifiable"]] + result["non_identifiable"] = [ + d + if d.get("type") == "scaling" + else {"support": d.get("support"), "type": d.get("type"), "closed_form": False} + for d in result["non_identifiable"] + ] run.stage("done (stacked)" if not _settled(result) else "done (stacked, rank settled)") result["stacked"] = bool(run.ss_constraint) return result @@ -1141,6 +1404,7 @@ def _kept_cols(self): def _phys_vector(self, vec, env): """The closed form {name: expr} at `env` on the physical coordinates; None where it does not evaluate.""" from ..closedform import eval_modq + P = PRIMES[0] if env is None or not _rational_forms(list(vec.values())): return None @@ -1167,6 +1431,7 @@ def _in_kernel(self, vec, env): def _complete_forward(self, dirs): """Kernel-refuted forward closed forms completed by their solved rates, eta_R = sum_c dR/dc eta_c.""" import sympy as spy + lines = (self.multi.get("tapes") or [{}])[0].get("constraint_model") if not self.joint or not lines: return dirs @@ -1194,12 +1459,12 @@ def _complete_forward(self, dirs): moved[str(E)] = E * L * comp[str(n)] for r in missing: R = spy.Symbol(r) - sol = next((spy.solve(spy.fraction(spy.together(e))[0], R) for e in eqs - if R in e.free_symbols), []) + sol = next((spy.solve(spy.fraction(spy.together(e))[0], R) for e in eqs if R in e.free_symbols), []) if len(sol) != 1: raise InapplicableError(r) - comp[r] = spy.cancel(sum((spy.diff(sol[0], spy.Symbol(c)) * v for c, v in moved.items()), - spy.Integer(0))) + comp[r] = spy.cancel( + sum((spy.diff(sol[0], spy.Symbol(c)) * v for c, v in moved.items()), spy.Integer(0)) + ) full = {k: str(v).replace("**", "^") for k, v in comp.items() if v != 0} env = self._kernel_point() # an absent solved rate either stays or moves with the others: the form as @@ -1208,16 +1473,33 @@ def _complete_forward(self, dirs): out.append(d) elif self._in_kernel(full, env) is not False: back = recast_backsub(full, self.recast) if self.recast else full - out.append(dict(d, vector=back, support=sym_sort(list(full)), - checked=full if self.recast else d.get("checked"))) + out.append( + dict( + d, + vector=back, + support=sym_sort(list(full)), + checked=full if self.recast else d.get("checked"), + ) + ) else: - out.append({"support": sym_sort(list(full)), "type": "general", - "closed_form": False, "reason": "no closed form on the kernel"}) + out.append( + { + "support": sym_sort(list(full)), + "type": "general", + "closed_form": False, + "reason": "no closed form on the kernel", + } + ) except SYMPY_FAILS as exc: sympy_fail(exc) - out.append({"support": sym_sort(list(vec) + missing), "type": "general", - "closed_form": False, "reason": "a solved rate of the forward route " - "has no closed form"}) + out.append( + { + "support": sym_sort(list(vec) + missing), + "type": "general", + "closed_form": False, + "reason": "a solved rate of the forward route has no closed form", + } + ) return out def _eliminate_states(self, dirs): @@ -1241,8 +1523,9 @@ def _eliminate_states(self, dirs): continue try: # entries of the leaves of terms at rest leave the report, resting states in them stay - held = any(states & {str(x) for x in model_sympify(v).free_symbols} - for k, v in vec.items() if k not in atoms) + held = any( + states & {str(x) for x in model_sympify(v).free_symbols} for k, v in vec.items() if k not in atoms + ) out.append(self._rewrite_in_coords(d, vec, eqs, states, coords) if held else d) except SYMPY_FAILS as exc: sympy_fail(exc) @@ -1252,6 +1535,7 @@ def _eliminate_states(self, dirs): @staticmethod def _rewrite_in_coords(d, vec, eqs, states, coords): import sympy as spy + comp0 = {k: model_sympify(v) for k, v in vec.items()} def held(c): @@ -1266,8 +1550,14 @@ def normal(c): def solvable(e, c): num, den = spy.fraction(spy.together(e)) - cand = [x for x in num.free_symbols if str(x) in coords and x not in den.free_symbols - and any(x in v.free_symbols for v in c.values()) and spy.degree(num, x) == 1] + cand = [ + x + for x in num.free_symbols + if str(x) in coords + and x not in den.free_symbols + and any(x in v.free_symbols for v in c.values()) + and spy.degree(num, x) == 1 + ] return num, sorted(cand, key=str) # orders of substitution that solve the same equations for the same coordinates reach the same components and @@ -1303,6 +1593,7 @@ def _search_from(c, left, solved): if r is not None: return r return None + comp = search(comp0, list(range(len(eqs)))) if comp is None: return d @@ -1314,6 +1605,7 @@ def _independent(self, dirs): """Independent closed forms on the kernel, filled with support-only kernel directions until they span it.""" from ..closedform import eval_modq from ..finalize import public_symmetry + P = PRIMES[0] phys = self._kept_cols() n = len(phys) @@ -1328,8 +1620,11 @@ def _independent(self, dirs): gen = public_symmetry(d)["generator"] # the resting-state columns of the joint system have no physical component gen = {k: v for k, v in gen.items() if not _CSUFFIX.search(k)} if gen else gen - at = env if env is not None or not gen else \ - (None if rest & {t for x in gen.values() for t in tok.findall(str(x))} else leaves) + at = ( + env + if env is not None or not gen + else (None if rest & {t for x in gen.values() for t in tok.findall(str(x))} else leaves) + ) inside = None if not gen else self._in_kernel(gen, at) if inside is None and d.get("checked") and env is not None: # a form with recast or exponential terms, in the coordinates it was checked in @@ -1379,8 +1674,9 @@ def _independent(self, dirs): if len(supp) == 1: keep.append(self._unit_fill(self.znames.index(supp[0]))) continue - keep.append({"support": supp, "type": "general", "closed_form": False, - "reason": "not reconstructed in closed form"}) + keep.append( + {"support": supp, "type": "general", "closed_form": False, "reason": "not reconstructed in closed form"} + ) return keep def _distances(self): @@ -1391,8 +1687,9 @@ def _distances(self): for l in strs(t.get("model_lines")): lhs, e = l.split("=", 1) rhs[lhs.strip()] = set(re.findall(r"[A-Za-z_.][A-Za-z0-9_.]*", e)) - reach = set(re.findall(r"[A-Za-z_.][A-Za-z0-9_.]*", " ".join(l.split("=", 1)[-1] - for l in strs(t.get("obs_lines"))))) + reach = set( + re.findall(r"[A-Za-z_.][A-Za-z0-9_.]*", " ".join(l.split("=", 1)[-1] for l in strs(t.get("obs_lines")))) + ) k, seen = 0, set() while reach - seen: for x in reach - seen: @@ -1440,6 +1737,7 @@ def _entry_orders(self, names, top): import sympy as spy from ...sym.exact import SIZE_CAP, _zero + try: tapes = [] for t in self.multi["tapes"]: @@ -1451,16 +1749,23 @@ def _entry_orders(self, names, top): except SYMPY_FAILS as exc: sympy_fail(exc) return {} - nxt = {str(x): str(e) for rhs, _ in tapes for x, e in rhs.items() - if str(x) in names and e.is_Symbol and str(e) in names} + nxt = { + str(x): str(e) + for rhs, _ in tapes + for x, e in rhs.items() + if str(x) in names and e.is_Symbol and str(e) in names + } out = {} for u in [nm for nm in names if nm not in set(nxt.values())]: k0 = top + 1 for rhs, obs in tapes: es, k = list(obs), 0 try: - while k < k0 and all(spy.count_ops(e) <= SIZE_CAP for e in es) \ - and all(_zero(spy.diff(e, spy.Symbol(u))) is True for e in es): + while ( + k < k0 + and all(spy.count_ops(e) <= SIZE_CAP for e in es) + and all(_zero(spy.diff(e, spy.Symbol(u))) is True for e in es) + ): es = [sum((spy.diff(e, x) * f for x, f in rhs.items()), spy.S.Zero) for e in es] k += 1 except SYMPY_FAILS as exc: @@ -1481,13 +1786,16 @@ def _projection(self, sc): entry = self._entry_orders(names, top) # a jet that k steps of the dependencies separate from an observable enters the rows from order k on; # jet j of an input that the Lie derivatives below order k0 do not hold enters from order k0 + j on - can = [j for j, nm in enumerate(names) - if dist.get(starts.get(nm, nm), dist.get(re.sub(r"_0$", "", nm), 0)) <= top - and entry.get(nm, 0) <= top] + can = [ + j + for j, nm in enumerate(names) + if dist.get(starts.get(nm, nm), dist.get(re.sub(r"_0$", "", nm), 0)) <= top and entry.get(nm, 0) <= top + ] def full(r): B = np.asarray(r.get("nuisance_block"), dtype=np.int64).reshape(-1, len(names)) return not can or int(_core.sym_rref_mod(B[:, can].astype(np.float64), int(r["p"]))["rank"]) == len(can) + # full column rank of the columns that can enter a row proves the rank, at the base point or at a uniform # point of the same rank base = dict(sc["ref"], p=PRIMES[0]) @@ -1529,15 +1837,20 @@ def _unit_fill(self, col): nm, sc = self.znames[col], self.sc e = {"support": [nm], "type": "scaling", "vector": {nm: 1}, "closed_form": True} try: - held = verify_in_nullspace(e, col, self.znames, self.leaf_names_aug, sc["point0"], sc["nt_used"], - self.kcall, 0, self.nz) + held = verify_in_nullspace( + e, col, self.znames, self.leaf_names_aug, sc["point0"], sc["nt_used"], self.kcall, 0, self.nz + ) except Exception as exc: swallow(exc, "unit direction at the verification points") held = False if held: return e - return {"support": [nm], "type": "general", "closed_form": False, - "reason": "the kernel holds it at the base point only"} + return { + "support": [nm], + "type": "general", + "closed_form": False, + "reason": "the kernel holds it at the base point only", + } def _gap_guard(self, sc, margin=2): """The rank at `margin` gap orders past the reported one, at the same point and Lie order.""" @@ -1552,10 +1865,19 @@ def _gap_guard(self, sc, margin=2): return {"ok": None, "method": "gap guard", "reason": "no kernel past the reported gap order"} base, top = int(rank_of(r0)), int(rank_of(r1)) if top > base: - return {"ok": False, "method": "gap guard", "kernel_rank": base, "kernel_rank_extended": top, - "reason": f"rank grows {base} -> {top} by gap order {mt + margin}"} - return {"ok": True, "method": "gap guard", "kernel_rank": base, - "reason": f"rank {base} stable through gap order {mt + margin}"} + return { + "ok": False, + "method": "gap guard", + "kernel_rank": base, + "kernel_rank_extended": top, + "reason": f"rank grows {base} -> {top} by gap order {mt + margin}", + } + return { + "ok": True, + "method": "gap guard", + "kernel_rank": base, + "reason": f"rank {base} stable through gap order {mt + margin}", + } def _guard_call(self, point, p, Nt): """The kernel at a higher Lie order, every chain cap raised with it.""" @@ -1597,27 +1919,46 @@ def _prove_by_scalings(self, result): def _prove_exact(self, result): """Closed forms proven over Q (proof.prove_exact).""" from .proof import prove_exact + prove_exact(self, result) def _prove_by_fields(self, result): """Proven when every kernel direction lies in the span of invariant fields.""" dirs = result.get("non_identifiable") or [] - if result.get("rank_proven") is None and result["rank"] < result["dim"] and dirs and \ - len(dirs) == result["dim"] - result["rank"] and all(d.get("exact") for d in dirs): + if ( + result.get("rank_proven") is None + and result["rank"] < result["dim"] + and dirs + and len(dirs) == result["dim"] - result["rank"] + and all(d.get("exact") for d in dirs) + ): result["rank_proven"] = len(dirs) result["rank_proof"] = "proven symmetries" return - if _settled(result) or result["rank"] >= result["dim"] or self.recast or self.run.nuis_cols \ - or state.get("inner") or self.stacked_quick or state.env("NOFIELDS"): + if ( + _settled(result) + or result["rank"] >= result["dim"] + or self.recast + or self.run.nuis_cols + or state.get("inner") + or self.stacked_quick + or state.env("NOFIELDS") + ): return run = self.run own = own_fields(result["non_identifiable"]) proof = {"ok": False, "why": "no closed form for every direction"} if own is not None: try: - proof = field_check(field_setup(self.multi, self.field_chains, run.cores, fields=own), - self.N, self.znames, run.leaf_names, self.point0_solved, - self.field_chains, self.field_joint) + proof = field_check( + field_setup(self.multi, self.field_chains, run.cores, fields=own), + self.N, + self.znames, + run.leaf_names, + self.point0_solved, + self.field_chains, + self.field_joint, + ) except RouteError as e: proof = {"ok": False, "why": str(e)} except Exception as e: @@ -1625,9 +1966,17 @@ def _prove_by_fields(self, result): proof = {"ok": False, "why": str(e)} if not proof.get("ok") and len(set(regime_keys(self.multi["tapes"]))) <= 3: try: - proof = field_proof(self.multi, self.N, self.znames, run.leaf_names, self.point0_solved, - self.field_chains, self.field_joint, run.cores, - fixed=self.field_fixed(self.N)) + proof = field_proof( + self.multi, + self.N, + self.znames, + run.leaf_names, + self.point0_solved, + self.field_chains, + self.field_joint, + run.cores, + fixed=self.field_fixed(self.N), + ) except RouteError as e: proof = {"ok": False, "why": str(e)} except Exception as e: @@ -1646,10 +1995,12 @@ def _joint_check(checks): return checks[0] oks = [c.get("ok") for c in checks] grow = [c["grow_at"] for c in checks if c.get("grow_at") is not None] - return {"ok": False if False in oks else (None if None in oks else True), - "grow_at": max(grow) if grow else None, - "method": " and ".join(c["method"] for c in checks), - "reason": "; ".join(f"{c['method']}: {c.get('reason')}" for c in checks)} + return { + "ok": False if False in oks else (None if None in oks else True), + "grow_at": max(grow) if grow else None, + "method": " and ".join(c["method"] for c in checks), + "reason": "; ".join(f"{c['method']}: {c.get('reason')}" for c in checks), + } def _settled(result): @@ -1657,21 +2008,47 @@ def _settled(result): return result.get("rank_proven") is not None or result.get("rank_fields") is not None -def observability_analytic_multi(multi, closed_form=False, cores=1, equil_zero_states=(), - cond_zero_states=(), t0events=(), n_conditions=None, chain_of=None, - n_gaps=0, implicit_steady_state=False, control=None, verify=False, - codim_spec=None): +def observability_analytic_multi( + multi, + closed_form=False, + cores=1, + equil_zero_states=(), + cond_zero_states=(), + t0events=(), + n_conditions=None, + chain_of=None, + n_gaps=0, + implicit_steady_state=False, + control=None, + verify=False, + codim_spec=None, +): """The observability analysis of compiled tapes; the raw result or None.""" K = len(multi.get("tapes") or []) def build(idx): """The Analysis of the conditions `idx`.""" + def part(x): x = list(x or []) return [x[i] for i in idx] if len(x) == K else x + m = multi if len(idx) == K else select.restrict(multi, idx) - return Analysis(m, closed_form, cores, equil_zero_states, part(cond_zero_states), part(t0events), - n_conditions, part(chain_of), n_gaps, implicit_steady_state, control, verify, codim_spec) + return Analysis( + m, + closed_form, + cores, + equil_zero_states, + part(cond_zero_states), + part(t0events), + n_conditions, + part(chain_of), + n_gaps, + implicit_steady_state, + control, + verify, + codim_spec, + ) def analyze(idx): an = build(idx) @@ -1680,6 +2057,7 @@ def analyze(idx): an.run.stage("done") out["timing"] = list(an.run.stages) return out + if select.eligible(multi, n_gaps, implicit_steady_state): out = _on_selection(multi, build, analyze, select.resting(multi, implicit_steady_state), cores) if out is not None: @@ -1691,6 +2069,7 @@ def _rest_on(build, conds, d): """_rest_proof() of the direction `d` on the resting conditions `conds`, at a point with the first of them seeded forward; the reason where it does not apply.""" from .proof import _rest_proof + try: an = build(conds) if an.sys.chained: @@ -1728,8 +2107,11 @@ def _on_selection(multi, build, analyze, rest, cores): if 2 * len(kept) > K: return None if state.env("TIMING"): - print(f"[select] {len(kept)} of {K} conditions ({sel['structures']} structures) at Lie order " - f"{sel['lie_order']}, rank {sel['rank']} at the point, {time.monotonic() - t0:.1f}s", flush=True) + print( + f"[select] {len(kept)} of {K} conditions ({sel['structures']} structures) at Lie order " + f"{sel['lie_order']}, rank {sel['rank']} at the point, {time.monotonic() - t0:.1f}s", + flush=True, + ) out = analyze(kept) if not isinstance(out, dict) or out.get("rerun_blocks"): return out @@ -1744,14 +2126,20 @@ def _on_selection(multi, build, analyze, rest, cores): sel["rank"] = more["rank"] kept = more["kept"] continue - cov = select.cover(multi, out, kept, cores, rest=(lambda conds, d: _rest_on(build, conds, d)) if rest - else None) + cov = select.cover(multi, out, kept, cores, rest=(lambda conds, d: _rest_on(build, conds, d)) if rest else None) if cov is None: return None if cov["ok"]: - out["selection"] = {"kept": list(kept), "conditions": K, "structures": sel["structures"], - "lie_order": sel["lie_order"], "rank_at_point": sel["rank"], "rounds": rnd + 1, - "dropped_by": cov["how"], "seconds": round(time.monotonic() - t0, 3)} + out["selection"] = { + "kept": list(kept), + "conditions": K, + "structures": sel["structures"], + "lie_order": sel["lie_order"], + "rank_at_point": sel["rank"], + "rounds": rnd + 1, + "dropped_by": cov["how"], + "seconds": round(time.monotonic() - t0, 3), + } out["conditions"] = K return out kept = sorted(set(kept) | set(cov["add"])) diff --git a/src/symident/detection/observability/context.py b/src/symident/detection/observability/context.py index ee76dfc..919015c 100644 --- a/src/symident/detection/observability/context.py +++ b/src/symident/detection/observability/context.py @@ -52,31 +52,87 @@ def iv(k): def sv(k): return conv(t.get(k), strs) - out = {"op": iv("op"), "a": iv("a"), "b": iv("b"), "cnum": sv("cnum"), "cden": sv("cden"), - "state_slots": iv("state_slots"), "f_out": iv("f_out"), "g_out": iv("g_out"), "ic_leaf": iv("ic_leaf"), - "ic_num": sv("ic_num"), "ic_den": sv("ic_den")} + + out = { + "op": iv("op"), + "a": iv("a"), + "b": iv("b"), + "cnum": sv("cnum"), + "cden": sv("cden"), + "state_slots": iv("state_slots"), + "f_out": iv("f_out"), + "g_out": iv("g_out"), + "ic_leaf": iv("ic_leaf"), + "ic_num": sv("ic_num"), + "ic_den": sv("ic_den"), + } if t.get("ic_op") is not None: - out.update({"ic_op": iv("ic_op"), "ic_a": iv("ic_a"), "ic_b": iv("ic_b"), "ic_cnum": sv("ic_cnum"), - "ic_cden": sv("ic_cden"), "ic_out": iv("ic_out")}) + out.update( + { + "ic_op": iv("ic_op"), + "ic_a": iv("ic_a"), + "ic_b": iv("ic_b"), + "ic_cnum": sv("ic_cnum"), + "ic_cden": sv("ic_cden"), + "ic_out": iv("ic_out"), + } + ) if t.get("leaf_slot") is not None: - out.update({"leaf_slot": ints(t["leaf_slot"]), "leaf_src": ints(t["leaf_src"]), - "leaf_num": strs(t["leaf_num"]), "leaf_den": strs(t["leaf_den"])}) + out.update( + { + "leaf_slot": ints(t["leaf_slot"]), + "leaf_src": ints(t["leaf_src"]), + "leaf_num": strs(t["leaf_num"]), + "leaf_den": strs(t["leaf_den"]), + } + ) if t.get("ev_var_idx") is not None: - out.update({"ev_op": ints(t["ev_op"]), "ev_a": ints(t["ev_a"]), "ev_b": ints(t["ev_b"]), - "ev_cnum": strs(t["ev_cnum"]), "ev_cden": strs(t["ev_cden"]), - "ev_out": ints(t["ev_out"]), "ev_var_idx": ints(t["ev_var_idx"]), - "ev_method": ints(t["ev_method"]), "ev_state_slots": int(t.get("ev_state_slots", 0)), - "ev_leaf_only": [bool(x) for x in t.get("ev_leaf_only", [True] * len(t["ev_var_idx"]))]}) + out.update( + { + "ev_op": ints(t["ev_op"]), + "ev_a": ints(t["ev_a"]), + "ev_b": ints(t["ev_b"]), + "ev_cnum": strs(t["ev_cnum"]), + "ev_cden": strs(t["ev_cden"]), + "ev_out": ints(t["ev_out"]), + "ev_var_idx": ints(t["ev_var_idx"]), + "ev_method": ints(t["ev_method"]), + "ev_state_slots": int(t.get("ev_state_slots", 0)), + "ev_leaf_only": [bool(x) for x in t.get("ev_leaf_only", [True] * len(t["ev_var_idx"]))], + } + ) if t.get("tm_op") is not None: - out.update({"tm_op": ints(t["tm_op"]), "tm_a": ints(t["tm_a"]), "tm_b": ints(t["tm_b"]), - "tm_cnum": strs(t["tm_cnum"]), "tm_cden": strs(t["tm_cden"]), - "tm_out": ints(t["tm_out"])}) + out.update( + { + "tm_op": ints(t["tm_op"]), + "tm_a": ints(t["tm_a"]), + "tm_b": ints(t["tm_b"]), + "tm_cnum": strs(t["tm_cnum"]), + "tm_cden": strs(t["tm_cden"]), + "tm_out": ints(t["tm_out"]), + } + ) return out # tape fields that hold slot indices; a slot below n_leaves is a leaf -_SLOT_FIELDS = ("a", "b", "f_out", "g_out", "ic_leaf", "ic_a", "ic_b", "ic_out", "ev_a", "ev_b", "ev_out", - "tm_a", "tm_b", "tm_out", "leaf_src") +_SLOT_FIELDS = ( + "a", + "b", + "f_out", + "g_out", + "ic_leaf", + "ic_a", + "ic_b", + "ic_out", + "ev_a", + "ev_b", + "ev_out", + "tm_a", + "tm_b", + "tm_out", + "leaf_src", +) def read_columns(tapes, n_leaves, z_slots): @@ -132,9 +188,18 @@ def _with_gap_order(e, Mtot): # the series rows of gap order 0 are the rows themselves srows = np.zeros((e["srows"].shape[0], nz * m), dtype=np.int32) srows[:, ::m] = e["srows"] - return {"Nt": e["Nt"], "plain": e["plain"], "N": m, "nz": nz, "rows": rows, "tag": np.repeat(e["tag"], m), - "srows": srows, "stag": e["stag"].copy(), "ranks": None, - "bytes": rows.nbytes + srows.nbytes} + return { + "Nt": e["Nt"], + "plain": e["plain"], + "N": m, + "nz": nz, + "rows": rows, + "tag": np.repeat(e["tag"], m), + "srows": srows, + "stag": e["stag"].copy(), + "ranks": None, + "bytes": rows.nbytes + srows.nbytes, + } def _block_bytes(): @@ -157,8 +222,7 @@ def _block_bytes(): class Run: """Coordinates, tapes, chains and parallel budget of one analysis; nt_cap, mtot and cores_call change during it.""" - def __init__(self, multi, cores, ctrl, chain_of, n_gaps, t0events, cond_zero_states, - equil_zero_states): + def __init__(self, multi, cores, ctrl, chain_of, n_gaps, t0events, cond_zero_states, equil_zero_states): self.multi = multi self.ctrl = ctrl self.timing = state.env("TIMING") @@ -219,14 +283,26 @@ def modulo_nuisance(self, o, p, cols=None): if not self.nuis_cols: return o from .nuisance import quotient + if cols is None: return quotient(o, self.nuis_cols, p, self.nuis_drop) pos = {c: j for j, c in enumerate(cols)} - return quotient(o, [pos[c] for c in self.nuis_cols if c in pos], p, - [pos[c] for c in self.nuis_drop if c in pos]) - - _CHAIN_FIELDS = ("has_gaps", "chain_of", "chain_groups", "chain_idx", "first_of_chain", "max_gap", - "cores_call", "mtot", "nt_cap", "series_gaps") + return quotient( + o, [pos[c] for c in self.nuis_cols if c in pos], p, [pos[c] for c in self.nuis_drop if c in pos] + ) + + _CHAIN_FIELDS = ( + "has_gaps", + "chain_of", + "chain_groups", + "chain_idx", + "first_of_chain", + "max_gap", + "cores_call", + "mtot", + "nt_cap", + "series_gaps", + ) def as_chains(self): """Every tape a chain of one segment, whose gap order is then the series order.""" @@ -267,6 +343,7 @@ def par_map(self, xs, f, sys=None): def g(x): sys.set_route_state(base) return f(x), sys.route_state() + res = process_map(g, xs, self.cores, on_error=lambda x: None) sys.merge_route_states(base, [r[1] for r in res if r is not None]) return [None if r is None else r[0] for r in res] @@ -302,18 +379,37 @@ def chain_rows(self, idx, point, p, Nt, Mtot, threads, zs, cols): return None return self._keep_rows(key, _with_gap_order(e0, int(Mtot))) # the jets of the chain continue those of a call at a lower order - jets = hashlib.sha256(repr((self.chain_content(idx), point.tobytes(), int(p), int(Mtot), - np.asarray(z, dtype=np.int64).tobytes())).encode()).hexdigest() - r = _core.sym_obs_chain_rows(self.chain_tapes(idx), self.n_leaves, self.n_states, z, point, p, int(Nt), - int(Mtot), int(threads), int(Mtot) == 0, jets) + jets = hashlib.sha256( + repr( + (self.chain_content(idx), point.tobytes(), int(p), int(Mtot), np.asarray(z, dtype=np.int64).tobytes()) + ).encode() + ).hexdigest() + r = _core.sym_obs_chain_rows( + self.chain_tapes(idx), + self.n_leaves, + self.n_states, + z, + point, + p, + int(Nt), + int(Mtot), + int(threads), + int(Mtot) == 0, + jets, + ) if not ok(r): return None - e = {"Nt": int(r["Nt"]), "plain": bool(r["plain"]), "N": int(r["N"]), "nz": len(z), - "rows": np.asarray(r["rows"], dtype=np.int32).reshape(-1, len(z)), - "tag": np.atleast_1d(np.asarray(r["tag"], dtype=np.int32)), - "srows": np.asarray(r["srows"], dtype=np.int32).reshape(-1, len(z) * int(r["N"])), - "stag": np.atleast_1d(np.asarray(r["stag"], dtype=np.int32)), - "ranks": None if r.get("ranks") is None else np.atleast_1d(np.asarray(r["ranks"], dtype=np.int64))} + e = { + "Nt": int(r["Nt"]), + "plain": bool(r["plain"]), + "N": int(r["N"]), + "nz": len(z), + "rows": np.asarray(r["rows"], dtype=np.int32).reshape(-1, len(z)), + "tag": np.atleast_1d(np.asarray(r["tag"], dtype=np.int32)), + "srows": np.asarray(r["srows"], dtype=np.int32).reshape(-1, len(z) * int(r["N"])), + "stag": np.atleast_1d(np.asarray(r["stag"], dtype=np.int32)), + "ranks": None if r.get("ranks") is None else np.atleast_1d(np.asarray(r["ranks"], dtype=np.int64)), + } return self._keep_rows(key, e) def chain_content(self, idx): @@ -321,9 +417,14 @@ def chain_content(self, idx): memo = self.__dict__.setdefault("_chain_content", {}) key = tuple(idx) if key not in memo: - memo[key] = hashlib.sha256(repr([sorted((k, v.tolist() if hasattr(v, "tolist") else v) - for k, v in self.tapes[i].items()) - for i in idx]).encode()).hexdigest() + memo[key] = hashlib.sha256( + repr( + [ + sorted((k, v.tolist() if hasattr(v, "tolist") else v) for k, v in self.tapes[i].items()) + for i in idx + ] + ).encode() + ).hexdigest() return memo[key] def _keep_rows(self, key, e): @@ -359,8 +460,9 @@ def chain_kernel(self, idx, point, p, Nt, Mtot, threads, zs=None): if e is None: o = {"ok": False} else: - sel, ssel = (slice(None), slice(None)) if e["Nt"] == int(Nt) else \ - (e["tag"] <= int(Nt), e["stag"] <= int(Nt)) + sel, ssel = ( + (slice(None), slice(None)) if e["Nt"] == int(Nt) else (e["tag"] <= int(Nt), e["stag"] <= int(Nt)) + ) o = _core.sym_chain_reduce(e["rows"][sel], e["srows"][ssel], e["nz"], e["N"], p) if len(memo) >= 8 * max(1, len(self.chain_groups or ())): memo.clear() @@ -383,10 +485,13 @@ def stacked_chain_kernel(self, point, p, Nt, Mtot, caps, zs=None): nts = [min(int(Nt), int(caps[t])) if len(caps) == T else int(Nt) for t in range(T)] # the costly chains first, so that none starts last: the cost grows with the columns, the segments and # the square of the order - order = sorted(range(T), key=lambda t: -(nz if cols[t] is None else len(cols[t])) * - len(self.chain_groups[t]) * (nts[t] + 1) ** 2) - got = thread_map(lambda t: self.chain_kernel(self.chain_groups[t], point, p, nts[t], Mtot, 1, zs), - order, self.cores_call) + order = sorted( + range(T), + key=lambda t: -(nz if cols[t] is None else len(cols[t])) * len(self.chain_groups[t]) * (nts[t] + 1) ** 2, + ) + got = thread_map( + lambda t: self.chain_kernel(self.chain_groups[t], point, p, nts[t], Mtot, 1, zs), order, self.cores_call + ) per = [None] * T for t, o in zip(order, got): per[t] = o @@ -400,9 +505,15 @@ def stacked_chain_kernel(self, point, p, Nt, Mtot, caps, zs=None): if not rows.shape[0] or not sum(S.shape[0] for S in sers): return None rr = _core.sym_rref_mod(rows.astype(np.float64), p) - res = {"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), nz), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), "rank": int(rr["rank"]), "dim": nz} + res = { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), nz), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": nz, + } from ..fields import series_stack + res = series_stack(res, sers, nz, N, p, self.cores_call) return None if res["at_one"] else res @@ -411,7 +522,7 @@ def stacked_chain_batch(self, points, primes, Nt, Mtot, caps, zs=None): not apply.""" out = [] for pt, q in zip(points, primes): - o = self.stacked_chain_kernel(np.asarray(pt, dtype=np.int64)[:self.n_leaves], q, Nt, Mtot, caps, zs) + o = self.stacked_chain_kernel(np.asarray(pt, dtype=np.int64)[: self.n_leaves], q, Nt, Mtot, caps, zs) if o is None: return None out.append(o) @@ -436,19 +547,33 @@ def obs_block_calls(self): """The kernel per tape or chain, where the saturation decides the Lie order.""" zs, nl, ns = self.z_slots, self.n_leaves, self.n_states if self.has_gaps: + def mk(idx): def f(point, p, Nt, Mtot=0): - return self.modulo_nuisance(self.chain_kernel(idx, point, p, self.exact_nt(Nt, Mtot), - Mtot, 1), p) + return self.modulo_nuisance(self.chain_kernel(idx, point, p, self.exact_nt(Nt, Mtot), Mtot, 1), p) + return f + return [mk(idx) for idx in self.chain_groups] def mk1(i): def f(point, p, Nt, Mtot=0): - return self.modulo_nuisance(_core.sym_obs_null_multi( - [self.tapes[i]], nl, ns, zs, np.asarray(point, dtype=np.int64), p, - self.exact_nt(Nt), self.block_threads()), p) + return self.modulo_nuisance( + _core.sym_obs_null_multi( + [self.tapes[i]], + nl, + ns, + zs, + np.asarray(point, dtype=np.int64), + p, + self.exact_nt(Nt), + self.block_threads(), + ), + p, + ) + return f + return [mk1(i) for i in range(len(self.tapes))] def obs_block_profiles(self): @@ -457,6 +582,7 @@ def obs_block_profiles(self): return None zs, nl, ns = self.z_slots, self.n_leaves, self.n_states if self.has_gaps: + def mk(bi): idx = self.chain_groups[bi] @@ -464,18 +590,23 @@ def f(point, p, Nt): # the rank does not see the columns the chain does not read; the rows stay for the kernel at # the order the scan stops at cols = self.chain_columns(idx) - e = self.chain_rows(idx, np.asarray(point, dtype=np.int64), p, Nt, 0, self.block_threads(), - zs, cols) + e = self.chain_rows( + idx, np.asarray(point, dtype=np.int64), p, Nt, 0, self.block_threads(), zs, cols + ) if e is None or e["ranks"] is None: return {"ok": False} - return {"ok": True, "ranks": e["ranks"][:int(Nt) + 1], "cols": e["nz"]} + return {"ok": True, "ranks": e["ranks"][: int(Nt) + 1], "cols": e["nz"]} + return f + return [mk(bi) for bi in range(len(self.chain_groups))] def mk1(i): def f(point, p, Nt): - return _core.sym_obs_rank_profile([self.tapes[i]], nl, ns, zs, - np.asarray(point, dtype=np.int64), p, int(Nt), - self.block_threads()) + return _core.sym_obs_rank_profile( + [self.tapes[i]], nl, ns, zs, np.asarray(point, dtype=np.int64), p, int(Nt), self.block_threads() + ) + return f + return [mk1(i) for i in range(len(self.tapes))] diff --git a/src/symident/detection/observability/guard.py b/src/symident/detection/observability/guard.py index 75aa46b..5eb49bb 100644 --- a/src/symident/detection/observability/guard.py +++ b/src/symident/detection/observability/guard.py @@ -28,6 +28,7 @@ def rank_at(k): swallow(exc, "saturation guard") return None return int(rank_of(rk)) if _ok(rk) else None + top = rank_at(margin) if top is not None: max_r = max(max_r, top) @@ -43,9 +44,17 @@ def rank_at(k): if grow_at is None and top is not None and top > base: grow_at = int(nt_used + margin) stable = grow_at is None - return {"ok": stable, "method": "saturation guard", "lie_order_used": int(nt_used), - "orders_checked": int(nt_used + margin), "kernel_rank": base, "kernel_rank_extended": max_r, - "grow_at": grow_at, - "reason": (f"rank {base} stable through Lie order {nt_used + margin} ({margin} orders " - "beyond the reported saturation)") if stable else - (f"rank grows {base} -> {max_r} at Lie order {grow_at} (the reported Lie order was premature)")} + return { + "ok": stable, + "method": "saturation guard", + "lie_order_used": int(nt_used), + "orders_checked": int(nt_used + margin), + "kernel_rank": base, + "kernel_rank_extended": max_r, + "grow_at": grow_at, + "reason": ( + f"rank {base} stable through Lie order {nt_used + margin} ({margin} orders beyond the reported saturation)" + ) + if stable + else (f"rank grows {base} -> {max_r} at Lie order {grow_at} (the reported Lie order was premature)"), + } diff --git a/src/symident/detection/observability/homotopy.py b/src/symident/detection/observability/homotopy.py index 4c1e74a..a0e4ec3 100644 --- a/src/symident/detection/observability/homotopy.py +++ b/src/symident/detection/observability/homotopy.py @@ -114,8 +114,7 @@ def basis(self, ns, p): ns[key] = W return W k, T = len(V), V[0].shape[1] - M = [np.array([[int(V[b][g, t]) for b in range(k)] for g in self.gauge], dtype=np.int64) - for t in range(T)] + M = [np.array([[int(V[b][g, t]) for b in range(k)] for g in self.gauge], dtype=np.int64) for t in range(T)] X0 = _inv_mod(M[0], p) if X0 is None: return None @@ -170,7 +169,7 @@ def _derivative(self, grp, seed): def _relevance(self): """The parameters each entry depends on, by groups of eight, then one by one.""" self.rel = [[[] for _ in c] for c in self.cols] - groups = [self.pars[i:i + 8] for i in range(0, len(self.pars), 8)] + groups = [self.pars[i : i + 8] for i in range(0, len(self.pars), 8)] for gi, g in enumerate(groups, start=1): hit = self._derivative(g, 7919 * gi + 1) if hit is None: @@ -293,8 +292,9 @@ def fit_entry(self, a, i): e = {"expr": num if den == "1" else f"({num})/({den})", "reli": reli} if self._verified(a, i, e): return e - self.diag(f"entry {self.cols[a][i]} degree {dg}: the lift at {np_} prime(s) fails " - "at the verification prime") + self.diag( + f"entry {self.cols[a][i]} degree {dg}: the lift at {np_} prime(s) fails at the verification prime" + ) return None # ---- directions ------------------------------------------------------------------- @@ -307,15 +307,16 @@ def _anchors(self, fcs): if not self.fcs: return P1 = PRIMES[0] - B = np.array([[int(self.ns0["V"][free.index(fc)][c, 0]) % P1 for c in range(n_sh)] for fc in self.fcs], - dtype=np.int64) + B = np.array( + [[int(self.ns0["V"][free.index(fc)][c, 0]) % P1 for c in range(n_sh)] for fc in self.fcs], dtype=np.int64 + ) rr = _core.sym_rref_mod(B.astype(np.float64), P1) piv = [int(x) for x in np.atleast_1d(rr["piv"])] if len(piv) < len(self.fcs): self.diag("the residual directions are dependent on the shared columns") self.fcs = [] return - self.gauge = piv[:len(self.fcs)] + self.gauge = piv[: len(self.fcs)] if self.mode == "free": self.anchor = [] for fc in self.fcs: @@ -329,8 +330,9 @@ def _anchors(self, fcs): if self.mode != "free": self.anchor = list(self.gauge) skip = [set(self.gauge) if self.mode != "free" else {self.anchor[a]} for a in range(len(self.fcs))] - self.cols = [[c for c in range(n_sh) if c not in skip[a] and int(W[a][c, 0]) % P1] - for a in range(len(self.fcs))] + self.cols = [ + [c for c in range(n_sh) if c not in skip[a] and int(W[a][c, 0]) % P1] for a in range(len(self.fcs)) + ] def _verified(self, a, i, e): """The fitted entry against the Pade value at t = 1 on a fresh line at a prime outside the lift.""" @@ -379,10 +381,16 @@ def direction(self, a): return None route = "homotopy fit" if used: - route += f" in the parameters and the {self.sys.hom_kind}" + \ - (f" of condition {single[0] + 1}" if single and len(used) == 1 else "") - return {"support": sym_sort(list(entries)), "vector": entries, "type": "general", - "closed_form": True, "route": route} + route += f" in the parameters and the {self.sys.hom_kind}" + ( + f" of condition {single[0] + 1}" if single and len(used) == 1 else "" + ) + return { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "route": route, + } def _in_kernel(self, entries, mi_plain, tries=None, need=2): """Whether the shared kernel at `need` fresh uniform points holds `entries`, states at rest in `mi_plain`.""" @@ -422,8 +430,10 @@ def run(self, fcs): if self.ns0 is None: self.diag("no series kernel at the base") return None - self.diag(f"residual {','.join(map(str, fcs))}; base free {','.join(map(str, self.ns0['free']))}; " - f"shared {self.sys.n_shared}") + self.diag( + f"residual {','.join(map(str, fcs))}; base free {','.join(map(str, self.ns0['free']))}; " + f"shared {self.sys.n_shared}" + ) P2 = verify_prime() self.dv = {nm: int(x) % P2 for nm, x in zip(self.pars, random_point(len(self.pars), 424242))} self.nsv = self.line_null(self.dv, 2 * self.d_cap + 2, P2) diff --git a/src/symident/detection/observability/homstate.py b/src/symident/detection/observability/homstate.py index c3ca014..c56f3d4 100644 --- a/src/symident/detection/observability/homstate.py +++ b/src/symident/detection/observability/homstate.py @@ -76,6 +76,7 @@ def degree(e, x): except SYMPY_FAILS as exc: sympy_fail(exc) return None + if all(all(degree(e, x) in (0, 1) for x in syms if x in e.free_symbols) for e in eqs): return list(states), [str(e) for e in eqs] core = list(syms) @@ -124,8 +125,7 @@ def use(self, mis): used.append(mi) zero = set(sys.zero_of(ci)) | set(getattr(sys, "solve_held", [])) st = sys.hom_states[mi] if len(getattr(sys, "hom_states", [])) > mi else {} - cand = [nm for nm in sys.real_state_names - if nm in st and nm not in zero and st[nm][0] % PRIMES[0] != 0] + cand = [nm for nm in sys.real_state_names if nm in st and nm not in zero and st[nm][0] % PRIMES[0] != 0] core, rel = reduce_relations(sys.models[ci], cand, sorted(zero)) self.relations[mi] = rel for nm in cand: @@ -148,7 +148,6 @@ def names(self, reli): """The variables of a fit: the resting states, then the relevant parameters `reli`.""" return list(self.states) + list(reli) - def resting_subs(self): """Resting states as rational functions of the parameters where their equations are linear, else {}.""" subs = {} @@ -192,8 +191,7 @@ def banned(self, names): out = [] for mi in self.mis: ren = {nm: v for v, (m, nm) in self.var.items() if m == mi} - lines = [_IDENT.sub(lambda m: ren.get(m.group(0), m.group(0)), rhs) - for rhs in self.relations.get(mi, [])] + lines = [_IDENT.sub(lambda m: ren.get(m.group(0), m.group(0)), rhs) for rhs in self.relations.get(mi, [])] out += _leading(lines, names) return out @@ -261,8 +259,11 @@ def _line(self, d, T, p, seed): n = len(hom.base) out = (None, None) for j in range(_N_BASES + 1): - base = self.good_base.get(p, hom.base) if j == 0 else \ - np.array(hom.an.sc["pool"](self.pool0 + (j - 1) * (n + 1) + np.arange(n)), dtype=np.int64) + base = ( + self.good_base.get(p, hom.base) + if j == 0 + else np.array(hom.an.sc["pool"](self.pool0 + (j - 1) * (n + 1) + np.arange(n)), dtype=np.int64) + ) Sw = self.sys.hom_line(base, d, T, p, hom.nt) if Sw is None: continue @@ -334,9 +335,11 @@ def _fit(self, a, i, reli): for p in cands: R = self._rows(a, i, reli, mons, dg, p, T, need, 9973) v = None if R is None else self._null(R, p, order) - self.hom.diag(f"states {','.join(self.states)}: degree {dg}, {nm} monomials " - f"({len(banned)} leading terms out), rows {None if R is None else R.shape[0]}, " - f"nullity {getattr(self, 'nullity', None) if R is not None else None}") + self.hom.diag( + f"states {','.join(self.states)}: degree {dg}, {nm} monomials " + f"({len(banned)} leading terms out), rows {None if R is None else R.shape[0]}, " + f"nullity {getattr(self, 'nullity', None) if R is not None else None}" + ) if R is None: continue if v is None: @@ -357,8 +360,10 @@ def _fit(self, a, i, reli): rec = None lifted = rec is not None and not any(dd == "0" for dd in rec["den"]) good = lifted and self._verified(a, i, reli, rec, mons, T + 4) - self.hom.diag(f"degree {dg}, {len(primes)} prime(s): " + - ("verified" if good else "lifted, not verified" if lifted else "no lift")) + self.hom.diag( + f"degree {dg}, {len(primes)} prime(s): " + + ("verified" if good else "lifted, not verified" if lifted else "no lift") + ) if good: return {"expr": self._expr(rec, mons, self.names(reli)), "reli": reli} if len(primes) >= 6: diff --git a/src/symident/detection/observability/joint.py b/src/symident/detection/observability/joint.py index 36ec69f..ac0b2f1 100644 --- a/src/symident/detection/observability/joint.py +++ b/src/symident/detection/observability/joint.py @@ -29,12 +29,14 @@ def __init__(self, run): self.solve_held = list(dict.fromkeys(self.forcings + run.equil_zero_states)) self.held_state_params = multi.get("held_state_params") or {} self.models = [strs(t.get("constraint_model")) for t in multi["tapes"]] - is_equil = [len(strs(t.get("constraint_model"))) > 0 and run.first_of_chain[i] - for i, t in enumerate(multi["tapes"])] + is_equil = [ + len(strs(t.get("constraint_model"))) > 0 and run.first_of_chain[i] for i, t in enumerate(multi["tapes"]) + ] self.recast = list(multi.get("power_recast") or []) # power recasts and the states of other recasts, which start at their leaf values, are no resting unknowns - self.real_state_names = strs(multi.get("real_state_names")) if (self.recast or multi.get("rest_aux")) \ - else self.state_names + self.real_state_names = ( + strs(multi.get("real_state_names")) if (self.recast or multi.get("rest_aux")) else self.state_names + ) gen_names = [str(r["base"]) if r.get("inverted") else str(r["E"]) for r in self.recast] self.l_names = list(dict.fromkeys(str(r["L"]) for r in self.recast)) held_solve = {str(v) for v in self.held_state_params.values()} @@ -44,8 +46,7 @@ def __init__(self, run): held_solve |= set(inverted.values()) self.solve_param_names = [n for n in self.param_names + gen_names if n not in held_solve] self.held_param_of = {str(k): str(v) for k, v in self.held_state_params.items()} - self.held_names = [n for n in self.held_param_of - if n in self.real_state_names and n not in self.solve_held] + self.held_names = [n for n in self.held_param_of if n in self.real_state_names and n not in self.solve_held] z_state = set(strs(multi.get("z_state_names"))) znames = run.znames nz = len(znames) @@ -66,36 +67,53 @@ def __init__(self, run): wc[self.per_cond_cols] = self.n_shared + mi * self.n_st + np.arange(self.n_st) self.wide_cols.append(wc) self.state_base = [znames[i] for i in self.per_cond_cols] - self.znames_wide = [znames[i] for i in self.shared_idx] + \ - [f"{s}|c{mi + 1}" for mi in range(self.kc) for s in self.state_base] - self.z_slots_wide = np.concatenate([run.z_slots[self.shared_idx]] + - [run.z_slots[self.per_cond_cols]] * self.kc) \ - if nz else run.z_slots - self.z_state_names_wide = self.znames_wide[self.n_shared:self.nz_wide] if self.n_st else [] + self.znames_wide = [znames[i] for i in self.shared_idx] + [ + f"{s}|c{mi + 1}" for mi in range(self.kc) for s in self.state_base + ] + self.z_slots_wide = ( + np.concatenate([run.z_slots[self.shared_idx]] + [run.z_slots[self.per_cond_cols]] * self.kc) + if nz + else run.z_slots + ) + self.z_state_names_wide = self.znames_wide[self.n_shared : self.nz_wide] if self.n_st else [] self.nz_local = nz self.znames_local = list(znames) self.z_slots_local = run.z_slots.copy() self.z_index_local = {z: i for i, z in enumerate(znames)} zi = self.z_index_local - self.recast_rel = [{ - "base_col": zi.get(str(rc["base"])), "ECol": zi.get(str(rc["E"])), - "LCol": zi.get(str(rc["L"])), "exp_col": zi.get(str(rc["exp"])), - "exp_slot": run.slot(str(rc["exp"])), "LSlot": run.slot(str(rc["L"])), - "ESlot": run.slot(str(rc["E"])), "base_slot": run.slot(str(rc["base"])), - "base_param": str(rc["base"]) in self.param_names} for rc in self.recast] + self.recast_rel = [ + { + "base_col": zi.get(str(rc["base"])), + "ECol": zi.get(str(rc["E"])), + "LCol": zi.get(str(rc["L"])), + "exp_col": zi.get(str(rc["exp"])), + "exp_slot": run.slot(str(rc["exp"])), + "LSlot": run.slot(str(rc["L"])), + "ESlot": run.slot(str(rc["E"])), + "base_slot": run.slot(str(rc["base"])), + "base_param": str(rc["base"]) in self.param_names, + } + for rc in self.recast + ] # exponential leaves outside the resting model: their relations over the local columns self.exp_rel = run.multi.get("exp_relation") if run.multi.get("exp_atoms") else None self.exp_rel_fn = tape_fn(self.exp_rel, run.n_leaves) if self.exp_rel else None - self.df_droppable = set(self.forcings) | set(run.equil_zero_states) | \ - {s for z in run.cond_zero_states for s in (z or [])} | (set(run.leaf_names) - set(znames)) + self.df_droppable = ( + set(self.forcings) + | set(run.equil_zero_states) + | {s for z in run.cond_zero_states for s in (z or [])} + | (set(run.leaf_names) - set(znames)) + ) self.solve_cache = {} # primes at which a solve was continued along a line instead of solved at the point self.cont_primes = set() self.solve_secs = [0.0, 0] self.model_key = ["\n".join(self.models[ci] + self.zero_of(ci)) for ci in range(len(self.models))] if run.timing: - print(f"[sym] {self.kc} equilibrate condition(s), " - f"{len({self.model_key[c] for c in self.equil_conds})} distinct steady state(s)") + print( + f"[sym] {self.kc} equilibrate condition(s), " + f"{len({self.model_key[c] for c in self.equil_conds})} distinct steady state(s)" + ) sp = set(self.solve_param_names) self.model_params = [] for m in self.models: @@ -107,10 +125,10 @@ def __init__(self, run): if ci not in self.equil_conds: self.private_of.append([]) continue - other = {n for cj in self.equil_conds if self.model_key[cj] != self.model_key[ci] - for n in self.model_params[cj]} - cand = [n for n in self.model_params[ci] - if n not in other and n not in self.l_names and n not in held_vals] + other = { + n for cj in self.equil_conds if self.model_key[cj] != self.model_key[ci] for n in self.model_params[cj] + } + cand = [n for n in self.model_params[ci] if n not in other and n not in self.l_names and n not in held_vals] self.private_of.append([n for n in cand if run.slot(n) is not None]) self.fwd_solve_cache = {} self.fwd_cond = self.equil_conds[0] if self.equil_conds else None @@ -122,8 +140,11 @@ def __init__(self, run): n_eq = (max(self.equil_conds) + 1) if self.equil_conds else 0 self.cont_off = [False] * n_eq self.cont_seen = [False] * n_eq - self.chains = [run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]) - for mi in range(self.kc)] if run.has_gaps else None + self.chains = ( + [run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]) for mi in range(self.kc)] + if run.has_gaps + else None + ) self.fwd_sel = list(range(self.kc)) self.warm_off = False self.diag = self.diagonal_start() @@ -136,8 +157,7 @@ def chain(self): """Single segments as chains, for the series of the diagonal start.""" run = self.run run.as_chains() - self.chains = [run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]) - for mi in range(self.kc)] + self.chains = [run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]) for mi in range(self.kc)] self.chained = True def unchain(self): @@ -156,8 +176,11 @@ def diagonal_start(self): reps = list({self.model_key[ci]: ci for ci in reversed(self.equil_conds)}.values()) if len(reps) < 2 and not self.held_names: return None - cand = [n for n in self.solve_param_names if run.slot(n) is not None and n not in self.l_names - and n not in self.fwd_banned] + cand = [ + n + for n in self.solve_param_names + if run.slot(n) is not None and n not in self.l_names and n not in self.fwd_banned + ] try: ds = DiagonalStart(self.models, reps, self.fwd_cond, self.held_of, cand, keep=self.held_names) except SYMPY_FAILS as exc: @@ -168,8 +191,9 @@ def diagonal_start(self): return None good = ds.ok and self.diagonal_trial(ds) if run.timing: - print(f"[sym] diagonal start: Z = {ds.Z}, zero at the start {ds.S}" if good - else "[sym] diagonal start: none") + print( + f"[sym] diagonal start: Z = {ds.Z}, zero at the start {ds.S}" if good else "[sym] diagonal start: none" + ) return ds if good else None def diagonal_trial(self, ds): @@ -186,9 +210,17 @@ def diagonal_trial(self, ds): held = {n: 0 for n in self.held_names} or None try: for _ in range(6): - fw = solve_forward_modular(self.models[self.fwd_cond], list(self.real_state_names), - list(self.solve_param_names), sv, pv, p, forcings=forc, - keep_free=keep, held=self.held_names or None) + fw = solve_forward_modular( + self.models[self.fwd_cond], + list(self.real_state_names), + list(self.solve_param_names), + sv, + pv, + p, + forcings=forc, + keep_free=keep, + held=self.held_names or None, + ) if not fw.get("ok"): return False zero = [r for r, v in fw["rates"].items() if int(v) % p == 0] @@ -208,13 +240,25 @@ def diagonal_trial(self, ds): if ci != {self.model_key[c]: c for c in reversed(self.equil_conds)}[self.model_key[ci]]: continue pz = [z for z in ds.Z if z in set(self.model_params[ci])] - sol = continue_resting_state(self.models[ci], list(self.real_state_names), - list(self.solve_param_names), pv, {z: dz[z] for z in pz}, - x0, p, T, forcings=self.held_of(ci) or None, held=held) + sol = continue_resting_state( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + pv, + {z: dz[z] for z in pz}, + x0, + p, + T, + forcings=self.held_of(ci) or None, + held=held, + ) if not sol.get("ok"): return False - if any(not any(int(v) for v in sol["val_by"][x]) for x in ds.S - if x in sol["val_by"] and x not in self.held_of(ci)): + if any( + not any(int(v) for v in sol["val_by"][x]) + for x in ds.S + if x in sol["val_by"] and x not in self.held_of(ci) + ): return False except SYMPY_FAILS as exc: sympy_fail(exc) @@ -226,27 +270,10 @@ def diagonal_trial(self, ds): # ---- conditions ----------------------------------------------------------------- - - - - # ---- steady-state solves -------------------------------------------------------- - - - - - - # ---- continuation from the forward-seeded resting state -------------------------- - - - - - - - # ---- rows of one condition ------------------------------------------------------ def df_rows(self, sol, p): @@ -278,6 +305,7 @@ def cond_local(self, mi, obs, sc0, p, scale=True): """One condition's rows on the local columns of the condition, state columns scaled unless continued; None rejects the point.""" from ..fields import ser_inv, ser_mul + if not ok(obs): return None nz_l = self.nz_local @@ -333,8 +361,7 @@ def cond_local(self, mi, obs, sc0, p, scale=True): if self.exp_rel_fn is not None: if cont: return None - e_m = exp_rows(self.exp_rel, self.exp_rel_fn, self.znames_local, - np.asarray(sc0["ptc"], dtype=np.int64), p) + e_m = exp_rows(self.exp_rel, self.exp_rel_fn, self.znames_local, np.asarray(sc0["ptc"], dtype=np.int64), p) if e_m is None: return None e_m = np.asarray(e_m, dtype=np.int64).reshape(-1, nz_l) @@ -355,6 +382,7 @@ def series_of(sl): for j in range(min(Ns - 1, sc0["ser"].shape[1])): v[1 + j] = int(sc0["ser"][sl, j]) % p return v + for rc in self.recast_rel: if rc["base_slot"] is None or rc["ESlot"] is None: return None @@ -367,10 +395,15 @@ def series_of(sl): c_b2 = [(p - x) % p for x in ib] R1 = np.zeros((2, nz_l * Ns), dtype=np.int64) one = [1] + [0] * (Ns - 1) - for i, col, v in ((0, rc["ECol"], one), (0, rc["base_col"], c_b1), (0, rc["exp_col"], c_x1), - (1, rc["LCol"], one), (1, rc["base_col"], c_b2)): + for i, col, v in ( + (0, rc["ECol"], one), + (0, rc["base_col"], c_b1), + (0, rc["exp_col"], c_x1), + (1, rc["LCol"], one), + (1, rc["base_col"], c_b2), + ): if col is not None: - R1[i, col * Ns:(col + 1) * Ns] = v + R1[i, col * Ns : (col + 1) * Ns] = v rel_s.append(R1) rel.append(R1[:, np.arange(nz_l) * Ns]) parts = [d_r, e_z] + rel @@ -413,19 +446,23 @@ def _project(self, locs, p, cores): r_p, Q, r_ps, QS, prec, series = 0, [], 0, [], [], True for loc in locs: M = loc["M"][:, st_l + sh_l] - rr = _core.sym_rref_mod(M.astype(np.float64), p) if M.shape[0] else \ - {"piv": [], "R": np.zeros((0, M.shape[1]))} + rr = ( + _core.sym_rref_mod(M.astype(np.float64), p) + if M.shape[0] + else {"piv": [], "R": np.zeros((0, M.shape[1]))} + ) piv = np.atleast_1d(rr["piv"]).astype(np.int64) is_p = piv < n_first r_p += int(is_p.sum()) if np.any(~is_p): R = np.asarray(rr["R"], dtype=np.int64).reshape(len(piv), M.shape[1]) - Q.append(R[~is_p][:, n_first:n_first + len(sh_l)]) + Q.append(R[~is_p][:, n_first : n_first + len(sh_l)]) if loc["S"] is None: series = False continue - sp = _core.sym_series_project(np.asarray(loc["S"], dtype=np.int64), int(self.nz_local), - int(loc["N"]), p, list(st_l), int(cores)) + sp = _core.sym_series_project( + np.asarray(loc["S"], dtype=np.int64), int(self.nz_local), int(loc["N"]), p, list(st_l), int(cores) + ) r_ps += int(sp["r1"]) QS.append(np.asarray(sp["Q"], dtype=np.int64).reshape(-1, len(sh_l) * int(loc["N"]))) prec.extend(ints(sp["prec"])) @@ -436,15 +473,23 @@ def joint_rank(self, locs, p, cores): r_p, Q, r_ps, QS, prec, series = self._project(locs, p, cores) QQ = np.vstack(Q) if Q else None r_q = int(_core.sym_rref_mod(QQ.astype(np.float64), p)["rank"]) if QQ is not None and QQ.shape[0] else 0 - res = {"ok": True, "rank": int(r_p + r_q), "dim": self.nz_wide, "block_rank": True, - "pivots": np.zeros(0, dtype=np.int64)} + res = { + "ok": True, + "rank": int(r_p + r_q), + "dim": self.nz_wide, + "block_rank": True, + "pivots": np.zeros(0, dtype=np.int64), + } if not series or not locs: return res N = int(locs[0]["N"]) nsh = len(self.shared_idx) QSm = np.vstack(QS) if QS else np.zeros((0, nsh * N), dtype=np.int64) - r_qs = int(_core.sym_series_rank(QSm, nsh, N, p, [], cores=int(cores), row_prec=prec)["rank"]) \ - if QSm.shape[0] else 0 + r_qs = ( + int(_core.sym_series_rank(QSm, nsh, N, p, [], cores=int(cores), row_prec=prec)["rank"]) + if QSm.shape[0] + else 0 + ) res["rank_s"] = int(r_ps + r_qs) res["N"] = N return res @@ -456,12 +501,22 @@ def cond_obs(self, ci, ptc, p, Nt, Mtot, ser=None): run = self.run pt = np.asarray(ptc, dtype=np.int64) % p if run.has_gaps: - return _core.sym_obs_null_chain([run.chain_tapes(run.chain_groups[run.chain_idx[ci]])], - run.n_leaves, run.n_states, self.z_slots_local, pt, p, - run.exact_nt(Nt, Mtot), int(Mtot), 1, [], - None if ser is None else np.asarray(ser) % p) - return _core.sym_obs_null_multi([run.tapes[ci]], run.n_leaves, run.n_states, - self.z_slots_local, pt, p, run.exact_nt(Nt), 1) + return _core.sym_obs_null_chain( + [run.chain_tapes(run.chain_groups[run.chain_idx[ci]])], + run.n_leaves, + run.n_states, + self.z_slots_local, + pt, + p, + run.exact_nt(Nt, Mtot), + int(Mtot), + 1, + [], + None if ser is None else np.asarray(ser) % p, + ) + return _core.sym_obs_null_multi( + [run.tapes[ci]], run.n_leaves, run.n_states, self.z_slots_local, pt, p, run.exact_nt(Nt), 1 + ) def cond_obs_sel(self, scs, sel, p, Nt, Mtot): """cond_obs for the conditions `sel` (others None), one batch on chains.""" @@ -469,16 +524,26 @@ def cond_obs_sel(self, scs, sel, p, Nt, Mtot): out = [None] * self.kc if not run.has_gaps or len(sel) < 2: for mi in sel: - out[mi] = self.cond_obs(self.equil_conds[mi], scs[mi]["ptc"], p, Nt, Mtot, - scs[mi]["ser"] if scs[mi].get("cont") else None) + out[mi] = self.cond_obs( + self.equil_conds[mi], scs[mi]["ptc"], p, Nt, Mtot, scs[mi]["ser"] if scs[mi].get("cont") else None + ) return out seeds = np.vstack([np.asarray(scs[mi]["ptc"], dtype=np.int64) % p for mi in sel]) sers = [np.asarray(scs[mi]["ser"]) % p if scs[mi].get("cont") else None for mi in sel] res = _core.sym_obs_null_chain_seed_batch( - self.chains, list(sel), seeds, [p] * len(sel), run.n_leaves, run.n_states, - self.z_slots_local, run.exact_nt(Nt, Mtot), int(Mtot), int(min(run.cores_call, len(sel))), + self.chains, + list(sel), + seeds, + [p] * len(sel), + run.n_leaves, + run.n_states, + self.z_slots_local, + run.exact_nt(Nt, Mtot), + int(Mtot), + int(min(run.cores_call, len(sel))), [run.nt_cap[mi] for mi in sel] if len(run.nt_cap) == self.kc else [], - sers if any(s is not None for s in sers) else None) + sers if any(s is not None for s in sers) else None, + ) for k, mi in enumerate(sel): out[mi] = res[k] return out @@ -486,8 +551,7 @@ def cond_obs_sel(self, scs, sel, p, Nt, Mtot): def cond_obs_all(self, scs, p, Nt, Mtot): """cond_obs for every resting condition, one batch on chains when there are gaps.""" if not self.run.has_gaps or self.kc < 2: - return [self.cond_obs(self.equil_conds[mi], scs[mi]["ptc"], p, Nt, Mtot) - for mi in range(self.kc)] + return [self.cond_obs(self.equil_conds[mi], scs[mi]["ptc"], p, Nt, Mtot) for mi in range(self.kc)] return self.cond_obs_sel(scs, list(range(self.kc)), p, Nt, Mtot) def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): @@ -521,17 +585,20 @@ def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): sblocks.append(b["series"]) blocks.append(b["W"]) rr = _core.sym_rref_mod(np.vstack(blocks).astype(np.float64), p) - res = {"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.nz_wide), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), "rank": int(rr["rank"]), - "dim": self.nz_wide} + res = { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.nz_wide), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": self.nz_wide, + } if run.has_gaps: res = series_stack(res, sblocks, self.nz_wide, Mtot + 1, p, run.cores_call) return run.modulo_nuisance(res, p) def kcall_fwd(self, point, p, Nt, solve_rates): """The wide kernel with the forward solve for the turnover rates.""" - return self.kcall(point, p, Nt, self.run.mtot, - lambda pt, pp, cc: self.solve_cond_fwd(pt, pp, cc, solve_rates)) + return self.kcall(point, p, Nt, self.run.mtot, lambda pt, pp, cc: self.solve_cond_fwd(pt, pp, cc, solve_rates)) def kcall_fwd_shared(self, point, p, Nt, solve_rates, sel=None): """The forward kernel on the shared columns only, on the conditions `sel`.""" @@ -544,8 +611,11 @@ def kcall_fwd_shared(self, point, p, Nt, solve_rates, sel=None): if sc0 is None: return {"ok": False} scs[mi] = sc0 - obs = self.cond_obs_all(scs, p, Nt, run.mtot) if len(sel) == self.kc else \ - self.cond_obs_sel(scs, sel, p, Nt, run.mtot) + obs = ( + self.cond_obs_all(scs, p, Nt, run.mtot) + if len(sel) == self.kc + else self.cond_obs_sel(scs, sel, p, Nt, run.mtot) + ) locs = [] for mi in sel: loc = self.cond_local(mi, obs[mi], scs[mi], p) @@ -564,8 +634,9 @@ def kcall_fwd_shared(self, point, p, Nt, solve_rates, sel=None): if series and QS: QSm = np.vstack(QS) if QSm.shape[0]: - sr = _core.sym_series_rank(QSm, nsh, run.mtot + 1, p, [], at_one_below=rk, - cores=int(run.cores_call), row_prec=prec) + sr = _core.sym_series_rank( + QSm, nsh, run.mtot + 1, p, [], at_one_below=rk, cores=int(run.cores_call), row_prec=prec + ) if sr.get("R") is not None: piv = np.atleast_1d(sr["pivots"]).astype(np.int64) R = np.asarray(sr["R"], dtype=np.int64).reshape(len(piv), nsh) @@ -590,6 +661,7 @@ def fwd_select(self, point, p, Nt, solve_rates): def block_calls(self): """One condition's observability rows for the saturation.""" + def mk(mi): def f(point, p, Nt, Mtot=0): sc0 = self.solve_cond(point, p, self.equil_conds[mi]) @@ -597,7 +669,9 @@ def f(point, p, Nt, Mtot=0): self.run.ss_why = "joint solve failed" return {"ok": False} return self.cond_obs(self.equil_conds[mi], sc0["ptc"], p, Nt, Mtot, sc0.get("ser")) + return f + return [mk(mi) for mi in range(self.kc)] def stacked_profile(self): @@ -617,9 +691,17 @@ def f(point, p, Nt): return {"ok": False} return _core.sym_obs_chain_rank_profile( run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]), - run.n_leaves, run.n_states, self.z_slots_local, - np.asarray(sc0["ptc"], dtype=np.int64) % p, p, int(Nt), 1) + run.n_leaves, + run.n_states, + self.z_slots_local, + np.asarray(sc0["ptc"], dtype=np.int64) % p, + p, + int(Nt), + 1, + ) + return f + return [mk(mi) for mi in range(self.kc)] def chunk(self, point_list, prime_vec, Nt, cols=None, conds=None, touch=False): @@ -643,9 +725,11 @@ def embed(o): o["R"] = R if o.get("S") is not None: Nn = int(o["N"]) - o["S"] = series_embed(np.asarray(o["S"], dtype=np.int64).reshape(-1, len(loc_sel) * Nn), - Nn, loc_sel, nz_l, 1) + o["S"] = series_embed( + np.asarray(o["S"], dtype=np.int64).reshape(-1, len(loc_sel) * Nn), Nn, loc_sel, nz_l, 1 + ) return o + n_p = len(point_list) per_cond = [None] * n_p seed_rows, ser_rows, ev_chain, ev_prime = [], [], [], [] @@ -667,11 +751,24 @@ def embed(o): ser_rows.append(np.asarray(per[mi]["ser"]) % pp if per[mi].get("cont") else None) ev_chain.append(mi) ev_prime.append(pp) - kr = _core.sym_obs_null_chain_seed_batch( - self.chains, ev_chain, np.vstack(seed_rows), ev_prime, run.n_leaves, run.n_states, - self.z_slots_local[loc_sel], run.exact_nt(Nt, run.mtot), int(run.mtot), int(min(run.cores, len(ev_chain))), - [run.nt_cap[e] for e in ev_chain] if len(run.nt_cap) == self.kc else [], - ser_rows if any(s is not None for s in ser_rows) else None) if seed_rows else [] + kr = ( + _core.sym_obs_null_chain_seed_batch( + self.chains, + ev_chain, + np.vstack(seed_rows), + ev_prime, + run.n_leaves, + run.n_states, + self.z_slots_local[loc_sel], + run.exact_nt(Nt, run.mtot), + int(run.mtot), + int(min(run.cores, len(ev_chain))), + [run.nt_cap[e] for e in ev_chain] if len(run.nt_cap) == self.kc else [], + ser_rows if any(s is not None for s in ser_rows) else None, + ) + if seed_rows + else [] + ) out = [None] * n_p e = 0 for i in range(n_p): @@ -699,18 +796,35 @@ def embed(o): Nb = run.mtot + 1 sk = [c * Nb + j for c in cl for j in range(Nb)] out[i] = series_stack( - {"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), len(cl)), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), "rank": int(rr["rank"]), - "dim": len(cl)}, - [None if S is None else S[:, sk] for S in sblocks], len(cl), Nb, prime_vec[i], - run.cores) + { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), len(cl)), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": len(cl), + }, + [None if S is None else S[:, sk] for S in sblocks], + len(cl), + Nb, + prime_vec[i], + run.cores, + ) else: rr = _core.sym_rref_mod(np.vstack(blocks).astype(np.float64), prime_vec[i]) out[i] = series_stack( - {"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.nz_wide), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), "rank": int(rr["rank"]), - "dim": self.nz_wide}, - sblocks, self.nz_wide, run.mtot + 1, prime_vec[i], run.cores) + { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.nz_wide), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": self.nz_wide, + }, + sblocks, + self.nz_wide, + run.mtot + 1, + prime_vec[i], + run.cores, + ) return out hom_kind = "resting states" @@ -718,8 +832,7 @@ def embed(o): def hom_prepare(self, point): """Moves the parameters of the resting solve and the logarithms of the recast bases.""" - self.hom_params = list(self.solve_param_names) + [nm for nm in self.l_names - if nm not in self.solve_param_names] + self.hom_params = list(self.solve_param_names) + [nm for nm in self.l_names if nm not in self.solve_param_names] def rest_env(self, point, q): """The resting states of each condition at `point` modulo `q` as X_c, and as X with one condition, from the @@ -768,10 +881,17 @@ def hom_line(self, point, d, T, p, Nt): pv = self.joint_pv(point, p) dv = {k: v for k, v in d.items() if k in sp} try: - sol = continue_resting_state(self.models[ci], list(self.real_state_names), - list(self.solve_param_names), pv["param_vals"], dv, - ref["sol"]["val_by"], p, int(T), - forcings=self.held_of(ci) or None) + sol = continue_resting_state( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + pv["param_vals"], + dv, + ref["sol"]["val_by"], + p, + int(T), + forcings=self.held_of(ci) or None, + ) except SYMPY_FAILS as exc: sympy_fail(exc) sol = None @@ -782,14 +902,14 @@ def hom_line(self, point, d, T, p, Nt): return None ptc = np.array(ref["ptc"], dtype=np.int64) ser = np.zeros((run.n_leaves, T), dtype=np.int64) - self.hom_states.append({nm: [int(x) % p for x in vals[:T + 1]] for nm, vals in sol["val_by"].items()}) + self.hom_states.append({nm: [int(x) % p for x in vals[: T + 1]] for nm, vals in sol["val_by"].items()}) for nm, vals in sol["val_by"].items(): sl = run.slot(nm) if sl is None: continue v = [int(x) % p for x in vals] ptc[sl] = v[0] - ser[sl, :] = v[1:1 + T] + ser[sl, :] = v[1 : 1 + T] for nm, v in d.items(): sl = run.slot(nm) if sl is not None and (nm in sp or nm in self.l_names): @@ -802,9 +922,20 @@ def hom_line(self, point, d, T, p, Nt): try: chain = run.chain_tapes(run.chain_groups[run.chain_idx[ci]]) if run.has_gaps else [run.tapes[ci]] nt_c = [run.nt_cap[mi]] if run.has_gaps and len(run.nt_cap) == self.kc else [] - obs = _core.sym_obs_null_chain([chain], run.n_leaves, run.n_states, self.z_slots_local, - ptc % p, p, int(Nt), int(run.mtot) if run.has_gaps else 0, - 1, nt_c, ser % p, int(T)) + obs = _core.sym_obs_null_chain( + [chain], + run.n_leaves, + run.n_states, + self.z_slots_local, + ptc % p, + p, + int(Nt), + int(run.mtot) if run.has_gaps else 0, + 1, + nt_c, + ser % p, + int(T), + ) except Exception as exc: swallow(exc, "homotopy series") obs = None @@ -813,12 +944,10 @@ def hom_line(self, point, d, T, p, Nt): loc = self.cond_local(mi, obs, {"sol": sol, "ptc": ptc, "ser": ser, "cont": True}, p) if loc is None or loc["S"] is None: return None - blocks.append(series_embed(loc["S"], int(loc["N"]), list(self.wide_cols[mi]), - self.nz_wide, p)) + blocks.append(series_embed(loc["S"], int(loc["N"]), list(self.wide_cols[mi]), self.nz_wide, p)) return np.vstack(blocks) def pinned(self): """Per-condition state columns a condition holds at zero.""" base = set(self.state_base) - return [f"{z}|c{mi + 1}" for mi in range(self.kc) for z in self.zero_of(self.equil_conds[mi]) - if z in base] + return [f"{z}|c{mi + 1}" for mi in range(self.kc) for z in self.zero_of(self.equil_conds[mi]) if z in base] diff --git a/src/symident/detection/observability/narrow.py b/src/symident/detection/observability/narrow.py index 2f1dd01..d9dd315 100644 --- a/src/symident/detection/observability/narrow.py +++ b/src/symident/detection/observability/narrow.py @@ -38,6 +38,7 @@ def __init__(self, rec, bf, anchor): def res(rp, p, zvals=None): return self.residue(rp, p) + res.narrow = True self.res = res @@ -51,23 +52,33 @@ def kb(self, point_list, prime_vec, Nt): per = 2 * max(1, run.cores) out = [] for s in range(0, len(point_list), per): - out.extend(an.sys.chunk(point_list[s:s + per], prime_vec[s:s + per], Nt, self.cols, self.conds)) + out.extend(an.sys.chunk(point_list[s : s + per], prime_vec[s : s + per], Nt, self.cols, self.conds)) return [run.modulo_nuisance(o, q, self.cols) for o, q in zip(out, prime_vec)] if run.nuis_cols else out - M = np.vstack([np.asarray(pp[:run.n_leaves], dtype=np.int64) for pp in point_list]) + M = np.vstack([np.asarray(pp[: run.n_leaves], dtype=np.int64) for pp in point_list]) nc = self.cols if run.nuis_cols else None if run.has_gaps: - os_ = run.stacked_chain_batch(point_list, prime_vec, run.exact_nt(Nt, run.mtot), int(run.mtot), - list(run.nt_cap), self.zs) + os_ = run.stacked_chain_batch( + point_list, prime_vec, run.exact_nt(Nt, run.mtot), int(run.mtot), list(run.nt_cap), self.zs + ) if os_ is not None: return [run.modulo_nuisance(o, q, nc) for o, q in zip(os_, prime_vec)] if nc else os_ - os_ = _core.sym_obs_null_chain_point_batch([run.chain_tapes(idx) for idx in run.chain_groups], - run.n_leaves, run.n_states, self.zs, M, list(prime_vec), - run.exact_nt(Nt, run.mtot), int(run.mtot), run.cores, - list(run.nt_cap)) + os_ = _core.sym_obs_null_chain_point_batch( + [run.chain_tapes(idx) for idx in run.chain_groups], + run.n_leaves, + run.n_states, + self.zs, + M, + list(prime_vec), + run.exact_nt(Nt, run.mtot), + int(run.mtot), + run.cores, + list(run.nt_cap), + ) return [run.modulo_nuisance(o, q, nc) for o, q in zip(os_, prime_vec)] if nc else os_ tapes = run.kernel_tapes() if self.sub is None else self.sub[1] - os_ = _core.sym_obs_null_batch(tapes, run.n_leaves, run.n_states, self.zs, M, list(prime_vec), - run.exact_nt(Nt), run.cores) + os_ = _core.sym_obs_null_batch( + tapes, run.n_leaves, run.n_states, self.zs, M, list(prime_vec), run.exact_nt(Nt), run.cores + ) if not an.transient: return [run.modulo_nuisance(o, q, nc) for o, q in zip(os_, prime_vec)] if nc else os_ out = [] @@ -82,9 +93,15 @@ def kb(self, point_list, prime_vec, Nt): continue R0 = np.asarray(o["R"], dtype=np.int64).reshape(int(o["rank"]), self.m) rr = _core.sym_rref_mod(np.vstack([R0, rel_m[:, self.cols]]).astype(np.float64), p) - out.append({"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.m), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), - "rank": int(rr["rank"]), "dim": self.m}) + out.append( + { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), self.m), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": self.m, + } + ) return [run.modulo_nuisance(o, q, nc) for o, q in zip(out, prime_vec)] if nc else out def _cover(self): @@ -94,9 +111,17 @@ def _cover(self): an, run = self.an, self.an.run if an.joint or run.has_gaps or an.transient or run.nuis_cols or len(run.tapes) < 16: return - r = _core.sym_obs_cover(run.kernel_tapes(), run.n_leaves, run.n_states, self.zs, - np.asarray(an.sc["point0"][:run.n_leaves], dtype=np.int64), PRIMES[0], - run.exact_nt(self.nt), self.m - 1, run.cores) + r = _core.sym_obs_cover( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + self.zs, + np.asarray(an.sc["point0"][: run.n_leaves], dtype=np.int64), + PRIMES[0], + run.exact_nt(self.nt), + self.m - 1, + run.cores, + ) if not ok(r) or int(r["rank"]) != self.m - 1: return idx = ints(r["conditions"]) @@ -126,8 +151,7 @@ def residue(self, rp, p): v = np.zeros(m, dtype=np.int64) v[free] = 1 for ri, pc in enumerate(piv): - v[pc] = (p - int(R[ri, free[0]])) % p if len(free) == 1 else \ - (p - int(np.sum(R[ri, free]))) % p + v[pc] = (p - int(R[ri, free[0]])) % p if len(free) == 1 else (p - int(np.sum(R[ri, free]))) % p if v[self.fpos] == 0: return None out = np.zeros(self.an.nz, dtype=np.int64) @@ -157,8 +181,12 @@ def _jet(self, limit): if state.env("NOJET") or self.m > 6: return None from ...sym.jets import jet_generator - chains = run.chain_groups if run.has_gaps else \ - [[i] for i in (range(len(an.multi["tapes"])) if self.sub is None else self.sub[0])] + + chains = ( + run.chain_groups + if run.has_gaps + else [[i] for i in (range(len(an.multi["tapes"])) if self.sub is None else self.sub[0])] + ) conds = [] for idx in chains: segs = [] @@ -166,8 +194,15 @@ def _jet(self, limit): t = an.multi["tapes"][ti] if t.get("jet_f") is None: break - segs.append({"f": strs(t["jet_f"]), "g": strs(t["jet_g"]), "ic": strs(t.get("jet_ic")), - "ev": t.get("jet_ev") or [], "time_fixed": t.get("jet_time_fixed") is not False}) + segs.append( + { + "f": strs(t["jet_f"]), + "g": strs(t["jet_g"]), + "ic": strs(t.get("jet_ic")), + "ev": t.get("jet_ev") or [], + "time_fixed": t.get("jet_time_fixed") is not False, + } + ) conds.append({"segments": segs} if segs else None) if not conds or any(c is None for c in conds): return None @@ -181,8 +216,9 @@ def _jet(self, limit): reach.append(min(r) if r else 0) max_ord = int(min(24, max(8, max(reach) + 2 * self.m))) try: - jg = jet_generator(conds, [an.znames[c] for c in self.cols], an.znames[self.anchor], - max_order=max_ord, work_limit=limit) + jg = jet_generator( + conds, [an.znames[c] for c in self.cols], an.znames[self.anchor], max_order=max_ord, work_limit=limit + ) except SYMPY_FAILS as err: sympy_fail(err) rec.tlog(f"narrow: jet error: {err}") @@ -191,16 +227,25 @@ def _jet(self, limit): swallow(err, "jets") rec.tlog(f"narrow: jet error: {err}") jg = None - rec.tlog("narrow: jet closed form " + (f"found at order {int(jg['order'])}" - if jg is not None and jg.get("ok") else - f"not found ({'error' if jg is None else jg.get('reason')})")) + rec.tlog( + "narrow: jet closed form " + + ( + f"found at order {int(jg['order'])}" + if jg is not None and jg.get("ok") + else f"not found ({'error' if jg is None else jg.get('reason')})" + ) + ) if jg is not None and jg.get("reason") == "work limit": session.note("limits", f"jets: stopped after {limit} characters of jets") if jg is None or not jg.get("ok"): return None - return {"support": sym_sort(list(jg["vector"])), - "vector": {k: str(x).replace("**", "^") for k, x in jg["vector"].items()}, - "type": "general", "closed_form": True, "route": f"jets (order {int(jg['order'])})"} + return { + "support": sym_sort(list(jg["vector"])), + "vector": {k: str(x).replace("**", "^") for k, x in jg["vector"].items()}, + "type": "general", + "closed_form": True, + "route": f"jets (order {int(jg['order'])})", + } def _entries_fit(self, ref, rel): """Whether, past the direction cap, every entry stays within the cap of the sparse fit, so that no @@ -208,18 +253,35 @@ def _entries_fit(self, ref, rel): if not self.wide: return False an = self.an - r = direction_relevance(self.anchor, ref, ref["pivots"], an.z_slots, an.n_aug, an.sc["point0"], rel, - self.res) + r = direction_relevance(self.anchor, ref, ref["pivots"], an.z_slots, an.n_aug, an.sc["point0"], rel, self.res) aux = set(an.aux_leaves) - return max([0] + [len([x for x in e if x not in aux]) for e in r["rel_by_entry"]]) <= \ - an.ctrl["relevance_cap_sparse"] + return ( + max([0] + [len([x for x in e if x not in aux]) for e in r["rel_by_entry"]]) + <= an.ctrl["relevance_cap_sparse"] + ) def _fit(self, ref, base0, rel): an, rec = self.an, self.rec ctrl = dict(an.ctrl, relevance_cap_dir=an.n_aug) if self.wide else an.ctrl - d = interpolate_direction(self.anchor, ref, ref["pivots"], an.znames, an.z_slots, an.leaf_names_aug, - an.n_aug, base0, an.sc["pool"], rec.pool_next, an.sc["nt_used"], self.kc, - rel, self.res, ctrl, self.kb, aux_leaves=an.aux_leaves) + d = interpolate_direction( + self.anchor, + ref, + ref["pivots"], + an.znames, + an.z_slots, + an.leaf_names_aug, + an.n_aug, + base0, + an.sc["pool"], + rec.pool_next, + an.sc["nt_used"], + self.kc, + rel, + self.res, + ctrl, + self.kb, + aux_leaves=an.aux_leaves, + ) rec.pool_next = d["pool_next"] r = dict(d["entry"]) r.pop("relevant_leaves", None) @@ -242,8 +304,8 @@ def logw(v, pt, p): z = np.asarray(pt, dtype=np.int64)[zs] % p if not np.all(z[self.cols]): return None - return np.array([mulmod(v[c], mulmod(z[a], invmod(int(z[c]), p), p), p) for c in self.cols], - dtype=np.int64) + return np.array([mulmod(v[c], mulmod(z[a], invmod(int(z[c]), p), p), p) for c in self.cols], dtype=np.int64) + base0 = np.asarray(sc["point0"], dtype=np.int64) w0 = logw(want, base0, P) kinds = {"constant": want[self.cols] % P, "scaling": w0} @@ -254,8 +316,9 @@ def logw(v, pt, p): if v is None: return None got = {"constant": v[self.cols] % P, "scaling": logw(v, pt, P)} - kinds = {kd: x for kd, x in kinds.items() - if x is not None and got[kd] is not None and np.array_equal(got[kd], x)} + kinds = { + kd: x for kd, x in kinds.items() if x is not None and got[kd] is not None and np.array_equal(got[kd], x) + } if not kinds: return None kd = "constant" if "constant" in kinds else "scaling" @@ -275,8 +338,13 @@ def logw(v, pt, p): nm = an.znames[c] if w != "0": vec[nm] = w if kd == "constant" else (nm if w == "1" else f"({w})*{nm}") - return {"support": sym_sort(list(vec)), "vector": vec, "type": "general", "closed_form": True, - "route": f"narrow read-off ({kd})"} + return { + "support": sym_sort(list(vec)), + "vector": vec, + "type": "general", + "closed_form": True, + "route": f"narrow read-off ({kd})", + } def _shorter_order(self, ref, want): """The lowest Lie order among the powers of two from 4 below the order of the kernel that still gives the @@ -303,8 +371,15 @@ def run(self): # a column without rows at the base point: the direction of the coordinate itself nm = an.znames[self.anchor] rec.tlog(f"narrow dir (anchor {nm}): a column without rows") - return self._checked({"support": [nm], "vector": {nm: "1"}, "type": "general", "closed_form": True, - "route": "narrow (a column without rows)"}) + return self._checked( + { + "support": [nm], + "vector": {nm: "1"}, + "type": "general", + "closed_form": True, + "route": "narrow (a column without rows)", + } + ) self.fpos = self.cols.index(self.anchor) if an.joint and not self._touched(): return None @@ -314,13 +389,17 @@ def run(self): base = res(ref, P) want = mulmod(self.bf % P, invmod(int(self.bf[self.anchor]) % P, P), P) if base is None or not np.array_equal(base, want): - rec.tlog(f"narrow (anchor {an.znames[self.anchor]}): the restricted rows do not give the " - f"direction (rank {ref.get('rank') if ref else None} of {self.m})") + rec.tlog( + f"narrow (anchor {an.znames[self.anchor]}): the restricted rows do not give the " + f"direction (rank {ref.get('rank') if ref else None} of {self.m})" + ) return None if not run.has_gaps: ref = self._shorter_order(ref, want) - rec.tlog(f"narrow dir (anchor {an.znames[self.anchor]}): support {self.m} of {an.nz} columns, " - f"Lie order {self.nt}" + (f", {len(self.conds)} of {an.sys.kc} conditions" if an.joint else "")) + rec.tlog( + f"narrow dir (anchor {an.znames[self.anchor]}): support {self.m} of {an.nz} columns, " + f"Lie order {self.nt}" + (f", {len(self.conds)} of {an.sys.kc} conditions" if an.joint else "") + ) # a support past the jets is fitted only within the relevance cap, so the probe stops past it; where the # probe runs along the direction (Narrow.lanes) a sample costs one support kernel, and each entry is # bounded by the caps of an entry alone @@ -332,15 +411,23 @@ def run(self): return self._checked(e) if lanes is not None: cap, self.wide = an.n_aug, True - rel = rec.probe_groups(self.kb, ref["pivots"], rec.pool_next, res, ref, stop_above=cap, - vecs=want.reshape(-1, 1), lanes=lanes) + rel = rec.probe_groups( + self.kb, ref["pivots"], rec.pool_next, res, ref, stop_above=cap, vecs=want.reshape(-1, 1), lanes=lanes + ) rec.pool_next += an.n_aug * (ctrl["probe_retries"] + 16) if rel is None: - return {"support": sym_sort([an.znames[c] for c in self.cols]), "type": "general", "closed_form": False, - "reason": f"direction couples more than {cap} parameters, above relevance_cap_dir={cap}; " - f"raise the relevant cap"} - groups = [] if state.env("NOGROUP") or self._entries_fit(ref, rel) else \ - translation_groups(rel, ref, res, self.kb, sc, P, run.n_leaves) + return { + "support": sym_sort([an.znames[c] for c in self.cols]), + "type": "general", + "closed_form": False, + "reason": f"direction couples more than {cap} parameters, above relevance_cap_dir={cap}; " + f"raise the relevant cap", + } + groups = ( + [] + if state.env("NOGROUP") or self._entries_fit(ref, rel) + else translation_groups(rel, ref, res, self.kb, sc, P, run.n_leaves) + ) rec.pool_next += 4 * run.n_leaves base0 = np.array(sc["point0"], dtype=np.int64) mul = [v for g in groups if g.get("type") == "mul" for v in g["members"]] @@ -350,13 +437,25 @@ def run(self): ref1 = self.kc(pt1, P, sc["nt_used"]) if res(ref1, P) is not None: base0, ref = pt1, ref1 - rel = rec.probe_groups(self.kb, ref["pivots"], rec.pool_next, res, ref, base0, stop_above=cap, - vecs=res(ref, P).reshape(-1, 1), lanes=lanes) + rel = rec.probe_groups( + self.kb, + ref["pivots"], + rec.pool_next, + res, + ref, + base0, + stop_above=cap, + vecs=res(ref, P).reshape(-1, 1), + lanes=lanes, + ) if rel is None: - return {"support": sym_sort([an.znames[c] for c in self.cols]), "type": "general", - "closed_form": False, - "reason": f"direction couples more than {cap} parameters, above relevance_cap_dir={cap}; " - f"raise the relevant cap"} + return { + "support": sym_sort([an.znames[c] for c in self.cols]), + "type": "general", + "closed_form": False, + "reason": f"direction couples more than {cap} parameters, above relevance_cap_dir={cap}; " + f"raise the relevant cap", + } rec.pool_next += an.n_aug * (ctrl["probe_retries"] + 16) else: groups = [g for g in groups if g.get("type") != "mul"] @@ -386,8 +485,12 @@ def run(self): if groups: e["vector"] = shift_groups(e["vector"], groups, an.leaf_names_aug, base0) if e["vector"] is None: - return {"support": e["support"], "type": "general", "closed_form": False, - "reason": "translation-group back-substitution failed"} + return { + "support": e["support"], + "type": "general", + "closed_form": False, + "reason": "translation-group back-substitution failed", + } e["route"] = f"{e['route']}, {len(groups)} exchange group" + ("s" if len(groups) > 1 else "") return self._checked(e) @@ -397,11 +500,25 @@ def _checked(self, e): if rec.dir_batch is not None and not an.joint: e["pending_check"] = self.anchor return e - if not verify_in_nullspace(e, self.anchor, an.znames, an.leaf_names_aug, sc["point0"], sc["nt_used"], - an.kcall, rec.pool_next, an.nz, rec.dir_call, - env_fn=an.sys.rest_env if an.joint else None): - return {"support": e["support"], "type": "general", "closed_form": False, - "reason": "a closed form was reconstructed but failed verification at a fresh prime"} + if not verify_in_nullspace( + e, + self.anchor, + an.znames, + an.leaf_names_aug, + sc["point0"], + sc["nt_used"], + an.kcall, + rec.pool_next, + an.nz, + rec.dir_call, + env_fn=an.sys.rest_env if an.joint else None, + ): + return { + "support": e["support"], + "type": "general", + "closed_form": False, + "reason": "a closed form was reconstructed but failed verification at a fresh prime", + } return back_substituted(an, e) diff --git a/src/symident/detection/observability/nuisance.py b/src/symident/detection/observability/nuisance.py index 6d4bb2c..7c98464 100644 --- a/src/symident/detection/observability/nuisance.py +++ b/src/symident/detection/observability/nuisance.py @@ -32,9 +32,9 @@ def quotient(o, cols, p, drop=()): # the rows that hold no dropped column once those are eliminated first rest = [c for c in range(nz) if c not in set(drop)] Rd, pv = _rref(R[:, drop + rest], p) - keep = Rd[pv >= len(drop)][:, len(drop):] + keep = Rd[pv >= len(drop)][:, len(drop) :] R = np.zeros((keep.shape[0] + len(drop), nz), dtype=np.int64) - R[:keep.shape[0], rest] = keep + R[: keep.shape[0], rest] = keep R[np.arange(keep.shape[0], R.shape[0]), drop] = 1 R, pv = _rref(R, p) out = dict(o, R=R, pivots=pv, rank=int(R.shape[0]), nuisance_pinned=len(free), nuisance_block=block) @@ -57,6 +57,7 @@ def pinned(fr): E = np.zeros((len(fr), nz * N), dtype=np.int64) E[np.arange(len(fr)), np.asarray(fr, dtype=np.int64) * N] = 1 return np.vstack([S, E]) + if _series_rank(pinned(free), nz, N, p) != want: basis = [] for c in cols: diff --git a/src/symident/detection/observability/plain.py b/src/symident/detection/observability/plain.py index e90425f..dfbd11a 100644 --- a/src/symident/detection/observability/plain.py +++ b/src/symident/detection/observability/plain.py @@ -20,19 +20,26 @@ def __init__(self, run): self.run = run multi = run.multi self.transient = bool(multi.get("power_recast") or multi.get("exp_atoms")) - self.recast = [dict(r, inverted=False) for r in (multi.get("power_recast") or [])] \ - if self.transient else [] - self.atom_names = (strs(multi.get("recast_atom_names")) + strs(multi.get("exp_atoms"))) \ - if self.transient else [] + self.recast = [dict(r, inverted=False) for r in (multi.get("power_recast") or [])] if self.transient else [] + self.atom_names = ( + (strs(multi.get("recast_atom_names")) + strs(multi.get("exp_atoms"))) if self.transient else [] + ) self.exp_rel = multi.get("exp_relation") self.exp_rel_fn = tape_fn(self.exp_rel, run.n_leaves) if self.transient and multi.get("exp_atoms") else None zi = {z: i for i, z in enumerate(run.znames)} - self.recast_rel = [{ - "Ecol": zi.get(str(rc["E"])), "base_col": zi.get(str(rc["base"])), - "exp_col": zi.get(str(rc["exp"])), "Lcol": zi.get(str(rc["L"])), - "Eslot": run.slot(str(rc["E"])), "base_slot": run.slot(str(rc["base"])), - "exp_slot": run.slot(str(rc["exp"])), "Lslot": run.slot(str(rc["L"]))} - for rc in self.recast] + self.recast_rel = [ + { + "Ecol": zi.get(str(rc["E"])), + "base_col": zi.get(str(rc["base"])), + "exp_col": zi.get(str(rc["exp"])), + "Lcol": zi.get(str(rc["L"])), + "Eslot": run.slot(str(rc["E"])), + "base_slot": run.slot(str(rc["base"])), + "exp_slot": run.slot(str(rc["exp"])), + "Lslot": run.slot(str(rc["L"])), + } + for rc in self.recast + ] def relation_rows(self, point, p): """The linearized recast relations at the point; None where a base vanishes.""" @@ -67,8 +74,7 @@ def relation_rows(self, point, p): r2[rc["base_col"]] = (p - invb) % p rel.append(r2) if self.exp_rel_fn is not None: - e_m = exp_rows(self.exp_rel, self.exp_rel_fn, run.znames, - np.asarray(point, dtype=np.int64), p) + e_m = exp_rows(self.exp_rel, self.exp_rel_fn, run.znames, np.asarray(point, dtype=np.int64), p) if e_m is None: return None rel.extend(list(e_m)) @@ -85,12 +91,23 @@ def with_relations(self, o, point, p): if rel_m is None: return {"ok": False} rr = _core.sym_rref_mod(np.vstack([o_r, rel_m]).astype(np.float64), p) - res = {"ok": True, "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), nz), - "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), "rank": int(rr["rank"]), "dim": nz} + res = { + "ok": True, + "R": np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), nz), + "pivots": np.atleast_1d(rr["piv"]).astype(np.int64), + "rank": int(rr["rank"]), + "dim": nz, + } if run.has_gaps: Nn = int(o["N"]) - res = series_stack(res, [np.asarray(o["S"], dtype=np.int64).reshape(-1, nz * Nn), - series_const(rel_m, Nn)], nz, Nn, p, run.cores_call) + res = series_stack( + res, + [np.asarray(o["S"], dtype=np.int64).reshape(-1, nz * Nn), series_const(rel_m, Nn)], + nz, + Nn, + p, + run.cores_call, + ) return res def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): @@ -103,12 +120,22 @@ def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): caps = list(run.nt_cap) o = run.stacked_chain_kernel(pt, p, run.exact_nt(Nt, Mtot), int(Mtot), caps) if o is None: - o = _core.sym_obs_null_chain([run.chain_tapes(idx) for idx in run.chain_groups], run.n_leaves, - run.n_states, run.z_slots, pt, p, run.exact_nt(Nt, Mtot), int(Mtot), - run.cores_call, caps) + o = _core.sym_obs_null_chain( + [run.chain_tapes(idx) for idx in run.chain_groups], + run.n_leaves, + run.n_states, + run.z_slots, + pt, + p, + run.exact_nt(Nt, Mtot), + int(Mtot), + run.cores_call, + caps, + ) else: - o = _core.sym_obs_null_multi(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, pt, p, - run.exact_nt(Nt), run.cores_call) + o = _core.sym_obs_null_multi( + run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, pt, p, run.exact_nt(Nt), run.cores_call + ) return run.modulo_nuisance(self.with_relations(o, point, p) if self.transient else o, p) # ---- homotopy along parameter lines --------------------------------------------------- @@ -169,15 +196,26 @@ def hom_line(self, point, d, T, p, Nt): v = int(d.get(nm, 0)) % p ser[i, 0] = v line[spy.Symbol(nm)] = [int(point[i]) % p, v] - ptc = np.asarray(point[:run.n_leaves], dtype=np.int64) % p + ptc = np.asarray(point[: run.n_leaves], dtype=np.int64) % p blocks = [] chains = [run.chain_tapes(idx) for idx in run.chain_groups] if run.has_gaps else [[tp] for tp in run.tapes] caps = list(run.nt_cap) if run.has_gaps and len(run.nt_cap) == len(chains) else [None] * len(chains) for chain, cap in zip(chains, caps): try: - o = _core.sym_obs_null_chain([chain], run.n_leaves, run.n_states, run.z_slots, ptc, p, int(Nt), - int(run.mtot) if run.has_gaps else 0, 1, [] if cap is None else [cap], - ser, int(T)) + o = _core.sym_obs_null_chain( + [chain], + run.n_leaves, + run.n_states, + run.z_slots, + ptc, + p, + int(Nt), + int(run.mtot) if run.has_gaps else 0, + 1, + [] if cap is None else [cap], + ser, + int(T), + ) except Exception as exc: swallow(exc, "homotopy series") return None @@ -185,8 +223,9 @@ def hom_line(self, point, d, T, p, Nt): return None blocks.append(np.asarray(o["S"], dtype=np.int64).reshape(int(o["rank_s"]), -1)) try: - self.hom_states = [{x: series_of(e, line, T + 1, p) for x, e in self.ic_expr[ci].items()} - for ci in self.equil_conds] + self.hom_states = [ + {x: series_of(e, line, T + 1, p) for x, e in self.ic_expr[ci].items()} for ci in self.equil_conds + ] except NoSeriesError: return None return np.vstack(blocks) @@ -223,6 +262,15 @@ def stacked_profile(self): return None def f(point, p, Nt): - return _core.sym_obs_rank_profile(run.kernel_tapes(), run.n_leaves, run.n_states, run.z_slots, - np.asarray(point, dtype=np.int64), p, int(Nt), run.cores_call) + return _core.sym_obs_rank_profile( + run.kernel_tapes(), + run.n_leaves, + run.n_states, + run.z_slots, + np.asarray(point, dtype=np.int64), + p, + int(Nt), + run.cores_call, + ) + return f diff --git a/src/symident/detection/observability/proof.py b/src/symident/detection/observability/proof.py index 9bb50a9..c21da86 100644 --- a/src/symident/detection/observability/proof.py +++ b/src/symident/detection/observability/proof.py @@ -68,8 +68,12 @@ def _exact_scalings(an, dirs): # the logarithm of a scaled coordinate is translated: the component is the weight itself shifts = {str(r["L"]) for r in an.recast or []} for d in dirs: - v = _weights({k: model_sympify(str(x)) if k in shifts else spy.cancel(model_sympify(str(x)) / spy.Symbol(k)) - for k, x in d["vector"].items()}) + v = _weights( + { + k: model_sympify(str(x)) if k in shifts else spy.cancel(model_sympify(str(x)) / spy.Symbol(k)) + for k, x in d["vector"].items() + } + ) if not v: continue k0 = next(k for k, x in v.items() if x != 0) @@ -77,11 +81,13 @@ def _exact_scalings(an, dirs): if not w or not w.get(k0): continue c = spy.cancel(v[k0] / w[k0]) - if c.is_Rational and all(spy.cancel(v.get(k, 0) - c * w.get(k, 0)) == 0 - for k in set(v) | (set(w) & coords)): + if c.is_Rational and all( + spy.cancel(v.get(k, 0) - c * w.get(k, 0)) == 0 for k in set(v) | (set(w) & coords) + ): d["exact"], d["proof"] = True, None - d["state_components"] = {k: scaling_component(c * x, k) for k, x in w.items() - if x != 0 and k not in set(an.znames)} + d["state_components"] = { + k: scaling_component(c * x, k) for k, x in w.items() if x != 0 and k not in set(an.znames) + } break @@ -105,14 +111,16 @@ def powers(p): if p.base == b and p.exp.is_polynomial(n) and spy.degree(p.exp, n) == 1: c, k = spy.Poly(p.exp, n).all_coeffs() if c.is_Rational and k.is_Integer: - return E ** c * b ** k + return E**c * b**k return p # the components in the recast states as well, as the right-hand sides are if names: logs = {k: v for k, v in names.items() if not isinstance(k, tuple)} - out = {k: str(model_sympify(v).replace(lambda e: e.is_Pow and not e.exp.is_Integer, powers).xreplace(logs)) - for k, v in out.items()} + out = { + k: str(model_sympify(v).replace(lambda e: e.is_Pow and not e.exp.is_Integer, powers).xreplace(logs)) + for k, v in out.items() + } return {k: v for k, v in out.items() if v != "0"} @@ -200,6 +208,7 @@ def light_proofs(light, chains, dirs, joint, plain, forms, map_fn=None): A direction proven makes the others a new try, since their brackets may contain the field proven. With `map_fn` (f over items in workers) and many directions, a pass tries every direction with the fields proven before the pass.""" + def attempt(d, known): first = None for vec in forms(d): @@ -207,8 +216,16 @@ def attempt(d, known): if ex["ok"] is True: return vec, ex, None first = first or ex - return None, None, ("no lift through an inverted power recast" if first is None else - f"lift of the closed form: {first.get('why') or 'undecided'}") + return ( + None, + None, + ( + "no lift through an inverted power recast" + if first is None + else f"lift of the closed form: {first.get('why') or 'undecided'}" + ), + ) + known, todo = [], list(dirs) while todo: left = [] @@ -252,8 +269,14 @@ def prove_symbolic(result, systems): tapes = [{"ver_ic": list(ic), "ver_t0": [], "ver_ev": []} for _, _, ic in systems] chains = [[i] for i in range(len(systems))] states = list(dict.fromkeys(l.split("=", 1)[0].strip() for f, _, _ in systems for l in f)) - light = {"regimes": regimes, "gens": [[{}]] * len(regimes), "regime_of": [i + 1 for i in range(len(regimes))], - "joins": [], "states": states, "tapes": tapes} + light = { + "regimes": regimes, + "gens": [[{}]] * len(regimes), + "regime_of": [i + 1 for i in range(len(regimes))], + "joins": [], + "states": states, + "tapes": tapes, + } try: light = restricted_setup(light, chains, False) light_proofs(light, chains, dirs, False, True, representatives) @@ -290,12 +313,15 @@ def _rest_proof(an, d): back = {} for r in sys_.recast: b, n = spy.Symbol(str(r["base"])), spy.Symbol(str(r["exp"])) - back[spy.Symbol(str(r["E"]))] = b ** n + back[spy.Symbol(str(r["E"]))] = b**n back[spy.Symbol(str(r["L"]))] = spy.log(b) # pi and Euler's number as the fixed leaves of the tape eb = an.multi.get("exp_back") or {} - const = {model_sympify(v): spy.Symbol(n) for n, v in zip(eb.get("names") or [], eb.get("values") or []) - if v in ("pi", "exp(1)")} + const = { + model_sympify(v): spy.Symbol(n) + for n, v in zip(eb.get("names") or [], eb.get("values") or []) + if v in ("pi", "exp(1)") + } back.update(const) conds, base = [], {} pivot = _pivots(sys_) @@ -311,8 +337,11 @@ def _rest_proof(an, d): ren = {spy.Symbol(x): spy.Symbol(f"{x}_c{mi}") for x in names} ren.update({spy.Symbol(x): spy.Integer(0) for x in held}) ren.update(pivot) - F = {k: v.xreplace(back).xreplace(ren) for k, v in _rhs(sys_.models[ci]).items() - if str(k) in sys_.real_state_names} + F = { + k: v.xreplace(back).xreplace(ren) + for k, v in _rhs(sys_.models[ci]).items() + if str(k) in sys_.real_state_names + } seg = {k: v.xreplace(back).xreplace(ren) for k, v in _rhs(_lines(tape.get("model_lines"))).items()} if any(spy.cancel(seg.get(k, spy.Integer(0)) - v) != 0 for k, v in F.items()): return "an input switches on at the start" @@ -321,8 +350,9 @@ def _rest_proof(an, d): conds.append(({ren[k]: v for k, v in F.items() if str(k) in names}, xs, obs)) sol = sys_.solve_cond(an.sc["point0"], PRIMES[0], ci) if sol is not None: - base.update({y: spy.Integer(int(sol["ptc"][run.slot(x)])) for x, y in zip(names, xs) - if run.slot(x) is not None}) + base.update( + {y: spy.Integer(int(sol["ptc"][run.slot(x)])) for x, y in zip(names, xs) if run.slot(x) is not None} + ) vec = {k: str(model_sympify(v).xreplace(const)) for k, v in representatives(d)[0].items()} if len(sys_.equil_conds) == 1: one = {spy.Symbol(x): spy.Symbol(f"{x}_c1") for x in sys_.real_state_names} @@ -334,15 +364,20 @@ def _rest_proof(an, d): rest = [x for _, xs, _ in conds for x in xs] vsyms = set().union(*[model_sympify(v).free_symbols for v in vec.values()]) if vec else set() pt = dict(base) - pt.update({spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) - for n in {str(s_) for F, _, _ in conds for e in F.values() for s_ in e.free_symbols} - if run.slot(n) is not None}) + pt.update( + { + spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) + for n in {str(s_) for F, _, _ in conds for e in F.values() for s_ in e.free_symbols} + if run.slot(n) is not None + } + ) def regular(F, xs): J = [[_mod(spy.diff(F[x], y), pt, PRIMES[0]) for y in xs] for x in xs] if any(v is None for r in J for v in r): return False return int(rref_modp(np.array(J, dtype=np.int64).reshape(len(xs), len(xs)), PRIMES[0])["rank"]) == len(xs) + split = not vsyms & set(rest) and all(regular(F, xs) for F, xs, _ in conds) groups = [[c] for c in conds] if split else [conds] ids = [] @@ -356,8 +391,13 @@ def regular(F, xs): if par["params"]: # the solved rates describe the resting branch where their Jacobian is regular bc = {k: v for k, v in base.items() if k in set(xs)} - bc.update({spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) - for n in map(str, params) if run.slot(n) is not None}) + bc.update( + { + spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) + for n in map(str, params) + if run.slot(n) is not None + } + ) A = spy.Matrix([[spy.diff(n, q) for q in par["params"]] for n in par["eqs"]]) det = _mod(A.det(), bc, PRIMES[0]) if len(bc) >= len(xs) + len(params) else None if not det: @@ -370,8 +410,9 @@ def _static_states(an, light): """The states that no event targets and that rest at their resting values in every segment, alone.""" sys_, tapes = an.sys, light["tapes"] chains = an.field_chains - targets = {str(e["var"]) for ch in chains for i in ch - for e in _evs(tapes[i].get("ver_t0")) + _evs(tapes[i].get("ver_ev"))} + targets = { + str(e["var"]) for ch in chains for i in ch for e in _evs(tapes[i].get("ver_t0")) + _evs(tapes[i].get("ver_ev")) + } seg = [{str(k): v for k, v in _rhs(_lines(t.get("model_lines"))).items()} for t in tapes] stset = set(light["states"]) S = {x for x in sys_.real_state_names if x not in targets} @@ -382,8 +423,12 @@ def _static_states(an, light): for i in chains[mi]: for x in S: f = seg[i].get(x) - if f is None or x not in rest or ({str(y) for y in f.free_symbols} & stset) - S \ - or spy.cancel(f - rest[x]) != 0: + if ( + f is None + or x not in rest + or ({str(y) for y in f.free_symbols} & stset) - S + or spy.cancel(f - rest[x]) != 0 + ): drop.add(x) if not drop: break @@ -405,10 +450,18 @@ def affine_lift(setup, field, chains): xi = G * spy.Matrix(states) + a unknown = list(G) + list(a) lifted = dict(field, **{str(z): str(xi[i]) for i, z in enumerate(states)}) - ids = [e for _, e in regime_identities(rg, lifted)] + \ - [e for ch in chains for i in ch for ev in [_evs(setup["tapes"][i].get("ver_t0"))] if ev - for _, e in event_identities(ev, lifted, lifted, setup["states"])] + \ - [e for j in setup["joins"] for _, e in event_identities(j["ev"], lifted, lifted, setup["states"])] + ids = ( + [e for _, e in regime_identities(rg, lifted)] + + [ + e + for ch in chains + for i in ch + for ev in [_evs(setup["tapes"][i].get("ver_t0"))] + if ev + for _, e in event_identities(ev, lifted, lifted, setup["states"]) + ] + + [e for j in setup["joins"] for _, e in event_identities(j["ev"], lifted, lifted, setup["states"])] + ) eqs = [] for e in ids: e = spy.together(e) @@ -446,8 +499,11 @@ def _moved_proofs(an, light, dirs): for vec in representatives(d): try: field = moved_field(ctx, vec) - ex = exact_direction(setup, field, an.field_chains, True) if field is not None else \ - {"ok": None, "why": "no resting components keep the variety tangent"} + ex = ( + exact_direction(setup, field, an.field_chains, True) + if field is not None + else {"ok": None, "why": "no resting components keep the variety tangent"} + ) if ex["ok"] is not True and field is not None: lifted = affine_lift(setup, field, an.field_chains) if lifted is not None: @@ -481,21 +537,28 @@ def static_setup(an, light): for j, i in enumerate(chains[mi]): t = tapes[i] f = [f"{x} = {e.xreplace(sub)}" for x, e in _rhs(_lines(t.get("model_lines"))).items() if str(x) not in S] - g = [f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" - for l in _lines(t.get("obs_lines"))] + g = [ + f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" + for l in _lines(t.get("obs_lines")) + ] regimes.append({"f": f, "g": g}) regime_of.append(len(regimes)) ic = [l for l in _lines(t.get("ver_ic")) if l.split("=", 1)[0].strip() not in S] new_tapes.append(dict(t, ver_ic=ic)) if j: - joins.append({"from": len(regimes) - 2, "to": len(regimes) - 1, "ev": _evs(t.get("ver_ev")), - "chain": mi + 1}) + joins.append( + {"from": len(regimes) - 2, "to": len(regimes) - 1, "ev": _evs(t.get("ver_ev")), "chain": mi + 1} + ) order = [i for ch in chains for i in ch] by_tape = dict(zip(order, range(len(order)))) - return {"regimes": regimes, "gens": [[{}]] * len(regimes), - "regime_of": [regime_of[by_tape[i]] if i in by_tape else 1 for i in range(len(tapes))], - "joins": joins, "states": [x for x in light["states"] if x not in S], - "tapes": [new_tapes[by_tape[i]] if i in by_tape else tapes[i] for i in range(len(tapes))]} + return { + "regimes": regimes, + "gens": [[{}]] * len(regimes), + "regime_of": [regime_of[by_tape[i]] if i in by_tape else 1 for i in range(len(tapes))], + "joins": joins, + "states": [x for x in light["states"] if x not in S], + "tapes": [new_tapes[by_tape[i]] if i in by_tape else tapes[i] for i in range(len(tapes))], + } def _subs_events(evs, sub): @@ -530,10 +593,18 @@ def moved_setup(an, light): run = an.run if par["params"]: sol = sys_.solve_cond(an.sc["point0"], PRIMES[0], ci) - bc = {y: spy.Integer(int(sol["ptc"][run.slot(str(y))])) for y in Ssym - if sol is not None and run.slot(str(y)) is not None} - bc.update({spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) - for n in map(str, params) if run.slot(n) is not None}) + bc = { + y: spy.Integer(int(sol["ptc"][run.slot(str(y))])) + for y in Ssym + if sol is not None and run.slot(str(y)) is not None + } + bc.update( + { + spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) + for n in map(str, params) + if run.slot(n) is not None + } + ) A = spy.Matrix([[spy.diff(n, q) for q in par["params"]] for n in par["eqs"]]) if len(bc) < len(Ssym) + len(params) or not _mod(A.det(), bc, PRIMES[0]): return "the parametrization does not reach the resting branch at the base point" @@ -543,21 +614,33 @@ def moved_setup(an, light): for j, i in enumerate(chains[0]): t = tapes[i] f = [f"{x} = {e.xreplace(sub)}" for x, e in _rhs(_lines(t.get("model_lines"))).items() if str(x) not in S] - g = [f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" - for l in _lines(t.get("obs_lines"))] + g = [ + f"{l.split('=', 1)[0].strip()} = {model_sympify(l.split('=', 1)[1]).xreplace(sub)}" + for l in _lines(t.get("obs_lines")) + ] regimes.append({"f": f, "g": g}) regime_of.append(len(regimes)) ic = [l for l in _lines(t.get("ver_ic")) if l.split("=", 1)[0].strip() not in S] new_tapes.append(dict(t, ver_ic=ic, ver_t0=_subs_events(_evs(t.get("ver_t0")), sub))) if j: - joins.append({"from": len(regimes) - 2, "to": len(regimes) - 1, - "ev": _subs_events(_evs(t.get("ver_ev")), sub), "chain": 1}) + joins.append( + { + "from": len(regimes) - 2, + "to": len(regimes) - 1, + "ev": _subs_events(_evs(t.get("ver_ev")), sub), + "chain": 1, + } + ) order = list(chains[0]) by_tape = dict(zip(order, range(len(order)))) - setup = {"regimes": regimes, "gens": [[{}]] * len(regimes), - "regime_of": [regime_of[by_tape[i]] if i in by_tape else 1 for i in range(len(tapes))], - "joins": joins, "states": [x for x in light["states"] if x not in S], - "tapes": [new_tapes[by_tape[i]] if i in by_tape else tapes[i] for i in range(len(tapes))]} + setup = { + "regimes": regimes, + "gens": [[{}]] * len(regimes), + "regime_of": [regime_of[by_tape[i]] if i in by_tape else 1 for i in range(len(tapes))], + "joins": joins, + "states": [x for x in light["states"] if x not in S], + "tapes": [new_tapes[by_tape[i]] if i in by_tape else tapes[i] for i in range(len(tapes))], + } return setup, {"sub": sub, "par": par, "left": [x for x in Ssym if x not in sub]} @@ -571,9 +654,13 @@ def moved_field(ctx, vec): if left: # the solved parameters p = h(x, q) move as v(p) = h_x xi + h_q v(q) h = [sub[p] for p in solved] - rhs = spy.Matrix([comp.get(p, spy.Integer(0)).xreplace(sub) - sum( - (spy.diff(hp, q) * field.get(q, spy.Integer(0)) for q in set(field) - set(left)), spy.Integer(0)) - for p, hp in zip(solved, h)]) + rhs = spy.Matrix( + [ + comp.get(p, spy.Integer(0)).xreplace(sub) + - sum((spy.diff(hp, q) * field.get(q, spy.Integer(0)) for q in set(field) - set(left)), spy.Integer(0)) + for p, hp in zip(solved, h) + ] + ) J = spy.Matrix([[spy.diff(hp, x) for x in left] for hp in h]) if J.shape[0] != J.shape[1] or spy.cancel(J.det()) == 0: return None @@ -596,8 +683,12 @@ def chain_bound(an, result): """info["bound"] of the unproven closed directions from the degree of the kernel's rational system, or None.""" from ...gfp import verify_prime from ..bound import _vector_degree, chain_degree, drawn, identity_degree, no_degree, rest_identity_degree - dirs = [d for d in result.get("non_identifiable") or [] - if d.get("closed_form") and not d.get("exact") and d.get("vector")] + + dirs = [ + d + for d in result.get("non_identifiable") or [] + if d.get("closed_form") and not d.get("exact") and d.get("vector") + ] if not dirs: return None if an.run.nuis_cols: @@ -606,11 +697,15 @@ def chain_bound(an, result): chains = run.chain_groups if run.has_gaps else [[i] for i in range(len(tapes))] order = int(an.sc["nt_used"]) vecs = [d.get("checked") or representatives(d)[0] for d in dirs] - unchecked = sorted({d.get("route") or "" for d in dirs - if not (_checked_at_random(d.get("route")) or d.get("random_checked"))}) + unchecked = sorted( + {d.get("route") or "" for d in dirs if not (_checked_at_random(d.get("route")) or d.get("random_checked"))} + ) if unchecked: - return {"applies": False, "why": f"a direction of the route {unchecked[0]} is not checked at random " - "points modulo the verification prime"} + return { + "applies": False, + "why": f"a direction of the route {unchecked[0]} is not checked at random " + "points modulo the verification prime", + } rest = None if an.field_joint is not None: rest = _rest_degrees(an, verify_prime()) @@ -624,8 +719,11 @@ def chain_bound(an, result): fs, g, x0, events, times = forms for v in vecs: try: - d = chain_degree(fs, g, x0, events, order, int(run.mtot), v, times) if run.has_gaps else \ - identity_degree(fs[0], g, x0, order, v) + d = ( + chain_degree(fs, g, x0, events, order, int(run.mtot), v, times) + if run.has_gaps + else identity_degree(fs[0], g, x0, order, v) + ) if d is not None and getattr(an, "transient", False): # the linearized recast relations: entries of degree up to three d = max(d, _vector_degree([model_sympify(str(c)) for c in v.values()]) + 3) @@ -642,8 +740,13 @@ def chain_bound(an, result): degs.append(d) q, d, k = verify_prime(), max(degs), drawn(2) # the two passing points are a pair of the k drawn - return {"degree": d, "points": 2, "draws": k, "prime": int(q), - "probability": float(min(1.0, len(vecs) * math.comb(k, 2) * min(1.0, d / q) ** 2))} + return { + "degree": d, + "points": 2, + "draws": k, + "prime": int(q), + "probability": float(min(1.0, len(vecs) * math.comb(k, 2) * min(1.0, d / q) ** 2)), + } def _lines_dict(lines): @@ -655,9 +758,13 @@ def _jet_forms(tapes, ch): if any(not tapes[i].get("jet_f") for i in ch): return "no rational form of the kernel" t = tapes[ch[0]] - return ([_lines_dict(tapes[i]["jet_f"]) for i in ch], {f"_y{i}": e for i, e in enumerate(_lines(t.get("jet_g")))}, - _lines_dict(t.get("jet_ic")), [_evs(tapes[i].get("jet_ev")) for i in ch[1:]], - [str(tapes[i].get("ver_time") or "") for i in ch]) + return ( + [_lines_dict(tapes[i]["jet_f"]) for i in ch], + {f"_y{i}": e for i, e in enumerate(_lines(t.get("jet_g")))}, + _lines_dict(t.get("jet_ic")), + [_evs(tapes[i].get("jet_ev")) for i in ch[1:]], + [str(tapes[i].get("ver_time") or "") for i in ch], + ) def _chain_forms(an, ch): @@ -668,15 +775,20 @@ def _chain_forms(an, ch): if ci not in sys.equil_conds: return "a condition does not start at rest" zero = set(sys.held_of(ci)) - x0 = {x: sys.held_param_of[x] if x in sys.held_param_of else "0" if x in zero else x - for x in sys.real_state_names} + x0 = {x: sys.held_param_of[x] if x in sys.held_param_of else "0" if x in zero else x for x in sys.real_state_names} for e in _evs(tapes[ci].get("ver_t0")): x, v = str(e["var"]), str(e["value"]) - x0[x] = {"add": f"({x0.get(x, x)}) + ({v})", "replace": v, - "multiply": f"({x0.get(x, x)})*({v})"}[e.get("method", "replace")] + x0[x] = {"add": f"({x0.get(x, x)}) + ({v})", "replace": v, "multiply": f"({x0.get(x, x)})*({v})"}[ + e.get("method", "replace") + ] t = tapes[ci] - return ([_lines_dict(tapes[i].get("model_lines")) for i in ch], _lines_dict(t.get("obs_lines")), x0, - [_evs(tapes[i].get("ver_ev")) for i in ch[1:]], [str(tapes[i].get("ver_time") or "") for i in ch]) + return ( + [_lines_dict(tapes[i].get("model_lines")) for i in ch], + _lines_dict(t.get("obs_lines")), + x0, + [_evs(tapes[i].get("ver_ev")) for i in ch[1:]], + [str(tapes[i].get("ver_time") or "") for i in ch], + ) def _rest_degrees(an, q): @@ -692,8 +804,10 @@ def _rest_degrees(an, q): if "why" in r: return r if not sys.rest_jacobian_regular(ci, an.sc["point0"], q): - return {"why": f"the resting Jacobian of condition {sys.equil_conds.index(ci) + 1} is singular at " - "the points tried"} + return { + "why": f"the resting Jacobian of condition {sys.equil_conds.index(ci) + 1} is singular at " + "the points tried" + } out[ci] = r return out @@ -725,16 +839,20 @@ def _rests_read(an, v, ci, rest): def prove_exact(an, result): """Exact proofs of the closed directions: lift, resting output, fixed resting subsystem, combined fields.""" - dirs = [d for d in result.get("non_identifiable") or [] - if d.get("closed_form") and not d.get("exact") and d.get("vector")] + dirs = [ + d + for d in result.get("non_identifiable") or [] + if d.get("closed_form") and not d.get("exact") and d.get("vector") + ] if not dirs or state.get("inner"): return if state.env("NOFIELDS"): return _fail(dirs, "switched off (NOFIELDS)") joint = an.field_joint is not None try: - light = restricted_setup(field_setup(an.multi, an.field_chains, an.run.cores, fields=[{}]), - an.field_chains, joint) + light = restricted_setup( + field_setup(an.multi, an.field_chains, an.run.cores, fields=[{}]), an.field_chains, joint + ) except Exception as exc: swallow(exc, "exact proof") return _fail(dirs, f"field setup failed: {type(exc).__name__}") @@ -758,9 +876,15 @@ def prove_exact(an, result): light["jets"] = nuis + starts light["jet_tops"] = list(an.multi.get("nuisance_tops") or []) light["params"] = [z for z in an.znames if z not in set(light["states"]) | set(an.atom_names)] - light_proofs(light, an.field_chains, dirs, joint, not joint and not an.run.has_gaps and not nuis, - lambda d: _forms(an, d), map_fn=lambda f, xs: process_map(f, xs, an.run.cores, - on_error=lambda x: None)) + light_proofs( + light, + an.field_chains, + dirs, + joint, + not joint and not an.run.has_gaps and not nuis, + lambda d: _forms(an, d), + map_fn=lambda f, xs: process_map(f, xs, an.run.cores, on_error=lambda x: None), + ) dirs = [d for d in dirs if not d.get("exact")] if nuis: return _fail(dirs, "no combined lift with unknown inputs") @@ -835,8 +959,7 @@ def prove_exact(an, result): why = "no combination of the regime fields moves the parameters alike" for rep in representatives(d): try: - vec = {(k + INIT if k in init else k): str(model_sympify(v).xreplace(ren)) - for k, v in rep.items()} + vec = {(k + INIT if k in init else k): str(model_sympify(v).xreplace(ren)) for k, v in rep.items()} except SYMPY_FAILS as exc: sympy_fail(exc) continue diff --git a/src/symident/detection/observability/reconstruct.py b/src/symident/detection/observability/reconstruct.py index d1c6e47..8166531 100644 --- a/src/symident/detection/observability/reconstruct.py +++ b/src/symident/detection/observability/reconstruct.py @@ -53,6 +53,7 @@ def _actionable(reason): # samples of a dense fit past which the log-coordinate gauge is tried first _LOG_FIRST = 2000 + class Reconstruction: """The residual directions of one analysis, closed in turn by each route.""" @@ -101,8 +102,7 @@ def with_attempts(self, entries): out.append(e) continue supp = set(e.get("support") or []) - att = list(dict.fromkeys((r, why) for r, why, s in self.attempts - if s is None or not supp or supp & set(s))) + att = list(dict.fromkeys((r, why) for r, why, s in self.attempts if s is None or not supp or supp & set(s))) e = dict(e, attempts=att) if not _actionable(e.get("reason")): better = [why for _, why in att if _actionable(why)] @@ -202,16 +202,18 @@ def probe_groups(self, kb, piv0, first, res_fn, ref, base=None, stop_above=None, moved = [gi for gi, g in enumerate(groups) if zero[gi] is None or not zero[gi].all()] need = [gi for gi in moved if len(groups[gi]) == 1] cands = [None] * len(groups) - for gi, cd in zip(need, kb([perts[gi] for gi in need], [P] * len(need), sc["nt_used"]) - if need else []): + for gi, cd in zip(need, kb([perts[gi] for gi in need], [P] * len(need), sc["nt_used"]) if need else []): cands[gi] = cd nxt = [] for gi, g in enumerate(groups): cd = cands[gi] piv_ok = ok(cd) and ints(cd["pivots"]) == piv0 v = res_fn(cd, P) if piv_ok else None - stays = v is not None and np.array_equal(np.asarray(v), np.asarray(bv)) if zero is None else \ - zero[gi] is not None and bool(zero[gi].all()) + stays = ( + v is not None and np.array_equal(np.asarray(v), np.asarray(bv)) + if zero is None + else zero[gi] is not None and bool(zero[gi].all()) + ) if stays: # the kernel stays, but a residue fn in log coordinates divides by z for li in g: @@ -225,8 +227,7 @@ def probe_groups(self, kb, piv0, first, res_fn, ref, base=None, stop_above=None, h = len(g) // 2 nxt.extend([g[:h], g[h:]]) elif piv_ok: - rp[g[0]] = {"rp": cd, "zvals": perts[gi][zs] if len(zs) else None, - "pertval": perts[gi][g[0]]} + rp[g[0]] = {"rp": cd, "zvals": perts[gi][zs] if len(zs) else None, "pertval": perts[gi][g[0]]} if stop_above is not None and g[0] not in aux: found += 1 else: @@ -249,9 +250,11 @@ def narrow_ok(self): """Whether the reconstruction may narrow onto column subsets.""" an, run = self.an, self.an.run return ( - an.can_batch or (run.has_gaps and not run.ss_constraint and not an.joint and not an.transient) + an.can_batch + or (run.has_gaps and not run.ss_constraint and not an.joint and not an.transient) or (an.transient and not run.has_gaps and not run.ss_constraint and not an.recast) - or an.chunked) + or an.chunked + ) def narrowed(self): """Directions closed on their own support, minimal-support candidates first.""" @@ -288,6 +291,7 @@ def narrowed(self): swallow(exc, "narrow route") if state.env("ROUTEDIAG"): import traceback + traceback.print_exc() e = None if i >= first and not (e is not None and e.get("closed_form")): @@ -302,7 +306,7 @@ def narrowed(self): if any("pending_check" in e for e in out): out, span = self._confirm(out, span) self.tlog(f"narrow: {len(out)} of {len(self.residual)} closed") - self.closed = np.concatenate([self.closed, span[:, an.scal_rows.shape[0]:]], axis=1) + self.closed = np.concatenate([self.closed, span[:, an.scal_rows.shape[0] :]], axis=1) self.drop_spanned(span) return out @@ -312,19 +316,43 @@ def _confirm(self, out, span): an = self.an n0 = span.shape[1] - len(out) pend = [i for i, e in enumerate(out) if "pending_check" in e] - res = verify_batch([out[i] for i in pend], [out[i]["pending_check"] for i in pend], an.znames, - an.leaf_names_aug, len(self.sc["point0"]), self.sc["nt_used"], self.dir_batch, an.nz) + res = verify_batch( + [out[i] for i in pend], + [out[i]["pending_check"] for i in pend], + an.znames, + an.leaf_names_aug, + len(self.sc["point0"]), + self.sc["nt_used"], + self.dir_batch, + an.nz, + ) good = {i: r for i, r in zip(pend, res)} kept, cols = [], list(range(n0)) for i, e in enumerate(out): f = e.pop("pending_check", None) if f is not None and good[i] is None: - good[i] = verify_in_nullspace(e, f, an.znames, an.leaf_names_aug, self.sc["point0"], - self.sc["nt_used"], an.kcall, self.pool_next, an.nz, self.dir_call) + good[i] = verify_in_nullspace( + e, + f, + an.znames, + an.leaf_names_aug, + self.sc["point0"], + self.sc["nt_used"], + an.kcall, + self.pool_next, + an.nz, + self.dir_call, + ) if f is not None and not good[i]: - self.attempt("narrow", {"support": e["support"], "type": "general", "closed_form": False, - "reason": "a closed form was reconstructed but failed verification at a " - "fresh prime"}) + self.attempt( + "narrow", + { + "support": e["support"], + "type": "general", + "closed_form": False, + "reason": "a closed form was reconstructed but failed verification at a fresh prime", + }, + ) continue kept.append(back_substituted(an, e) if f is not None else e) cols.append(n0 + i) @@ -340,7 +368,7 @@ def statics(self): Np = N[p_cols, :] % P span = an.scal_tangents.copy() out = [] - for f in (stf or []): + for f in stf or []: val = [int(f["val"][pp.index(an.znames[c])]) for c in p_cols] cc = _core.sym_solve_mod(Np, val, P) if cc is None: @@ -352,8 +380,11 @@ def statics(self): continue span = np.concatenate([span, vw.reshape(nz, 1)], axis=1) self.closed = np.concatenate([self.closed, vw.reshape(nz, 1)], axis=1) - an.static_rows = np.asarray(f["lval"]).reshape(1, -1) if an.static_rows is None else \ - np.vstack([an.static_rows, f["lval"]]) + an.static_rows = ( + np.asarray(f["lval"]).reshape(1, -1) + if an.static_rows is None + else np.vstack([an.static_rows, f["lval"]]) + ) out.append({k: v for k, v in f.items() if k not in ("val", "lval")}) if out: self.drop_spanned(span) @@ -377,9 +408,19 @@ def _forward_entries(self, closed): trial = dict(e, vector=vec) # the form states the columns off the resting states phys = [i for i, z in enumerate(an.znames) if not _CSUFFIX.search(z)] - held = verify_in_nullspace(trial, col, an.znames, an.leaf_names_aug, self.sc["point0"], - self.sc["nt_used"], an.kcall, self.pool_next, an.nz, - cols=phys, env_fn=an.sys.rest_env) + held = verify_in_nullspace( + trial, + col, + an.znames, + an.leaf_names_aug, + self.sc["point0"], + self.sc["nt_used"], + an.kcall, + self.pool_next, + an.nz, + cols=phys, + env_fn=an.sys.rest_env, + ) e["random_checked"] = held is True and not trial.get("partial_check") except Exception as exc: swallow(exc, "forward form at random points") @@ -402,8 +443,11 @@ def _forward_checked(self, entries): v = an._phys_vector(e.get("checked") or e["vector"], env) if e.get("closed_form") else None if v is not None and (not np.any(v) or in_span(span, v, len(phys), P)): n_open += 1 - self.attempt("forward", reason="the forward form lies in the span of the directions found", - support=e.get("support")) + self.attempt( + "forward", + reason="the forward form lies in the span of the directions found", + support=e.get("support"), + ) continue if v is not None: span = np.concatenate([span, v.reshape(-1, 1)], axis=1) @@ -416,14 +460,19 @@ def _forward_checked(self, entries): free.append(fc) span = np.concatenate([span, r.reshape(-1, 1)], axis=1) if len(free) < n_open: - free = self.residual[len(self.residual) - n_open:] + free = self.residual[len(self.residual) - n_open :] out = [] for fc in self.residual: if fc in free: res = self.residues(fc) - out.append({"support": sym_sort([an.znames[i] for i in phys if res[i] % P]), - "type": "general", "closed_form": False, - "reason": "the forward form lies in the span of the directions found"}) + out.append( + { + "support": sym_sort([an.znames[i] for i in phys if res[i] % P]), + "type": "general", + "closed_form": False, + "reason": "the forward form lies in the span of the directions found", + } + ) else: out.append(kept.pop(0)) return out @@ -469,9 +518,23 @@ def _forward_multi(self): an, sys = self.an, self.an.sys try: return perprime_forward_multi( - self.residual, self.sc, an.kcall, sys.kcall_fwd, an.znames, an.z_slots, an.leaf_names_aug, - an.nz, an.scaling, strs(an.multi.get("z_state_names")), self.ctrl, self.phys_cols, - sys.models, sys.real_state_names, sys.solve_param_names, sys.held_of(0)) + self.residual, + self.sc, + an.kcall, + sys.kcall_fwd, + an.znames, + an.z_slots, + an.leaf_names_aug, + an.nz, + an.scaling, + strs(an.multi.get("z_state_names")), + self.ctrl, + self.phys_cols, + sys.models, + sys.real_state_names, + sys.solve_param_names, + sys.held_of(0), + ) except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -501,23 +564,42 @@ def rest_kind(self): def forward_first(self, stacked_ss, late=False): """Residual directions from the forward route, first under msolve, after the fast routes under a resultant.""" an, sys = self.an, self.an.sys - if not (an.run.ss_constraint and not stacked_ss and self.residual and an.joint - and len({sys.model_key[c] for c in sys.equil_conds}) == 1): + if not ( + an.run.ss_constraint + and not stacked_ss + and self.residual + and an.joint + and len({sys.model_key[c] for c in sys.equil_conds}) == 1 + ): return [] kind = self.rest_kind() # the leaves of non-rational terms at rest: the entries are simple in the drawn resting states leaves = bool(an.multi.get("rest_aux")) if (kind != ("core" if late else "msolve")) and not (leaves and not late): return [] + def run(): try: fwd = perprime_forward_shared( - self.sc, an.kcall, sys.kcall_fwd, an.znames, an.z_slots, an.leaf_names_aug, an.nz, - an.scaling, strs(an.multi.get("z_state_names")), self.ctrl, self.phys_cols, - sys.models, sys.real_state_names, sys.solve_param_names, sys.held_of(0), + self.sc, + an.kcall, + sys.kcall_fwd, + an.znames, + an.z_slots, + an.leaf_names_aug, + an.nz, + an.scaling, + strs(an.multi.get("z_state_names")), + self.ctrl, + self.phys_cols, + sys.models, + sys.real_state_names, + sys.solve_param_names, + sys.held_of(0), kcall_fwd_sh=sys.kcall_fwd_shared, select_fn=sys.fwd_select, - map_fn=self.fork_map) + map_fn=self.fork_map, + ) except SYMPY_FAILS as err: sympy_fail(err) if state.env("ROUTEDIAG"): @@ -529,10 +611,13 @@ def run(): print(f"[fwds] error: {err}") fwd = None return self._forward_multi() if fwd is None else fwd + fwd = self._forward_retrying(run) closed = self._forward_adopt(fwd) - self.tlog(f"forward {'after the fast routes' if late else 'first'} (resting state: {kind}): " + - ("not adopted" if closed is None else "every direction closed")) + self.tlog( + f"forward {'after the fast routes' if late else 'first'} (resting state: {kind}): " + + ("not adopted" if closed is None else "every direction closed") + ) if closed is None: for d in fwd or []: self.attempt("forward", d) @@ -555,12 +640,19 @@ def homotopy(self, interp): """`interp` with the open directions closed along parameter lines through the base point.""" an, run = self.an, self.an.run open_ = [i for i, e in enumerate(interp) if not e.get("closed_form")] - why = ("switched off (reconst_control(homotopy=False))" if not self.ctrl.get("homotopy", True) else - "needs the joint resting state" if run.ss_constraint and not an.joint else - "not run where the kernel depends on the time between events" - if run.has_gaps and not run.series_gaps and (self.sc.get("ref") or {}).get("at_one") else - "not run where an event time depends on the parameters" if run.has_gaps and self._moving_times() else - "not run in transient recast coordinates" if getattr(an, "transient", False) else None) + why = ( + "switched off (reconst_control(homotopy=False))" + if not self.ctrl.get("homotopy", True) + else "needs the joint resting state" + if run.ss_constraint and not an.joint + else "not run where the kernel depends on the time between events" + if run.has_gaps and not run.series_gaps and (self.sc.get("ref") or {}).get("at_one") + else "not run where an event time depends on the parameters" + if run.has_gaps and self._moving_times() + else "not run in transient recast coordinates" + if getattr(an, "transient", False) + else None + ) if open_ and why is not None: self.attempt("homotopy", reason=why) if not (open_ and why is None and len(interp) == len(self.residual)): @@ -578,8 +670,9 @@ def homotopy(self, interp): d["vector"] = recast_backsub(d["vector"], an.recast) for i in open_: if self.residual[i] not in found: - self.attempt("homotopy", reason="no closed form along parameter lines", - support=interp[i].get("support")) + self.attempt( + "homotopy", reason="no closed form along parameter lines", support=interp[i].get("support") + ) out = [found.get(self.residual[i], e) if i in open_ else e for i, e in enumerate(interp)] self.tlog(f"homotopy: {len(found)} of {len(open_)} open direction(s) closed") return out @@ -597,11 +690,18 @@ def fields(self, partial=False): if fs is not None: try: # a field is taken only outside the scalings and the directions closed before - out = field_directions(fs, an.N, len(self.residual), - np.vstack([an.scal_rows, self.closed.T]) if self.closed.shape[1] - else an.scal_rows, an.znames, - an.run.leaf_names, an.point0_solved, an.field_chains, - an.field_joint, partial=partial) + out = field_directions( + fs, + an.N, + len(self.residual), + np.vstack([an.scal_rows, self.closed.T]) if self.closed.shape[1] else an.scal_rows, + an.znames, + an.run.leaf_names, + an.point0_solved, + an.field_chains, + an.field_joint, + partial=partial, + ) except RouteError as err: self.attempt("invariant fields", reason=str(err)) out = None @@ -609,9 +709,15 @@ def fields(self, partial=False): swallow(exc, "field directions") out = None is_partial = isinstance(out, dict) and out.get("partial") - self.tlog("global symmetries: " + ("no close" if out is None else - f"{len(out['dirs'] if is_partial else out)} direction(s) closed" + - (", the rest sampled" if is_partial else ""))) + self.tlog( + "global symmetries: " + + ( + "no close" + if out is None + else f"{len(out['dirs'] if is_partial else out)} direction(s) closed" + + (", the rest sampled" if is_partial else "") + ) + ) return out # ---- interpolation ---------------------------------------------------------------- @@ -624,16 +730,51 @@ def open_entry(reason): v = rfn(sc["ref"], P, self.zvals0) if rfn is not None else self.residues(fc) if v is None: v = self.residues(fc) - return {"support": sym_sort([an.znames[i] for i in np.nonzero(v)[0]]), "type": "general", - "closed_form": False, "reason": reason} - args = (an.znames, an.z_slots, an.leaf_names_aug, an.n_aug, sc["point0"], sc["pool"], - self.pool_next, sc["nt_used"], an.kcall) + return { + "support": sym_sort([an.znames[i] for i in np.nonzero(v)[0]]), + "type": "general", + "closed_form": False, + "reason": reason, + } + + args = ( + an.znames, + an.z_slots, + an.leaf_names_aug, + an.n_aug, + sc["point0"], + sc["pool"], + self.pool_next, + sc["nt_used"], + an.kcall, + ) if per_prime: - d = interpolate_perprime(fc, sc["ref"], sc["pivots"], *args, self.kb, self.rel_probe, - self.ctrl, aux_leaves=an.aux_leaves, phys_cols=self.phys_cols) + d = interpolate_perprime( + fc, + sc["ref"], + sc["pivots"], + *args, + self.kb, + self.rel_probe, + self.ctrl, + aux_leaves=an.aux_leaves, + phys_cols=self.phys_cols, + ) else: - d = interpolate_direction(fc, sc["ref"], sc["pivots"], *args, self.rel_probe, rfn, self.ctrl, - self.kb, bank, fast_only, aux_leaves=an.aux_leaves, degrees=degrees) + d = interpolate_direction( + fc, + sc["ref"], + sc["pivots"], + *args, + self.rel_probe, + rfn, + self.ctrl, + self.kb, + bank, + fast_only, + aux_leaves=an.aux_leaves, + degrees=degrees, + ) self.pool_next = d["pool_next"] e = dict(d["entry"]) e.pop("relevant_leaves", None) @@ -642,9 +783,17 @@ def open_entry(reason): verified = False if e.get("closed_form"): vargs = (e, fc, an.znames, an.leaf_names_aug, sc["point0"], sc["nt_used"], an.kcall) + def in_null(cols=None): - return verify_in_nullspace(*vargs, self.pool_next, an.nz, self.dir_call, cols=cols, - env_fn=an.sys.rest_env if an.joint else None) + return verify_in_nullspace( + *vargs, + self.pool_next, + an.nz, + self.dir_call, + cols=cols, + env_fn=an.sys.rest_env if an.joint else None, + ) + if per_prime: # a fit per prime states only the columns off the resting states and the anchor verified = in_null(None if self.phys_cols is None else self.phys_cols + [fc]) @@ -655,9 +804,11 @@ def in_null(cols=None): if e.get("closed_form") and not verified: e = open_entry("a closed form was reconstructed but failed verification at a fresh prime") if e.get("closed_form"): - e["route"] = ("fit per prime" if per_prime else "read-off" if fast_only else "fit") + \ - (" in log coordinates" if log_coords else "") + \ - (f" ({e['fit_how']})" if e.get("fit_how") else "") + e["route"] = ( + ("fit per prime" if per_prime else "read-off" if fast_only else "fit") + + (" in log coordinates" if log_coords else "") + + (f" ({e['fit_how']})" if e.get("fit_how") else "") + ) e.pop("fit_how", None) eb = an.multi.get("exp_back") or {} if an.recast or eb.get("names"): @@ -672,20 +823,31 @@ def gauge(self): """The residual directions of minimal support, computed once per residual.""" an, key = self.an, tuple(self.residual) if self._gauge is None or self._gauge[0] != key: - self._gauge = (key, minsupport_gauge(self.residual, an.scal_rows, PRIMES[0], an.nz, self.sc, - an.free_cols, cand_cap=self.ctrl["minsupport_cand_cap"])) + self._gauge = ( + key, + minsupport_gauge( + self.residual, + an.scal_rows, + PRIMES[0], + an.nz, + self.sc, + an.free_cols, + cand_cap=self.ctrl["minsupport_cand_cap"], + ), + ) return self._gauge[1] def full_probe(self): """The probe over all leaves, by bisection over leaf groups when there are many.""" an = self.an if an.n_aug > 150: + def all_res(rp, p, zvals=None): v = [null_residues(rp, fc, p) for fc in self.residual] return np.concatenate(v) if v else np.zeros(0, dtype=np.int64) + vecs = np.stack([self.residues(fc) for fc in self.residual], axis=1) if self.residual else None - return self.probe_groups(self.kb, self.sc["pivots"], self.probe_next, all_res, self.sc["ref"], - vecs=vecs) + return self.probe_groups(self.kb, self.sc["pivots"], self.probe_next, all_res, self.sc["ref"], vecs=vecs) return self.probe(self.kb, self.sc["pivots"], self.probe_next) def peeled(self): @@ -712,16 +874,23 @@ def peeled(self): def ms_try(self, ms, fast_only): """All directions in the minimal-support gauge, or None unless all close.""" if not fast_only: - self.tlog(f"ms gauge: {len(ms['anchors'])} anchor(s) for {len(self.residual)} residual " - f"direction(s), {sum(f is not None for f in ms['residue_fns'])} residue fn(s)") + self.tlog( + f"ms gauge: {len(ms['anchors'])} anchor(s) for {len(self.residual)} residual " + f"direction(s), {sum(f is not None for f in ms['residue_fns'])} residue fn(s)" + ) if len(ms["anchors"]) != len(self.residual) or all(f is None for f in ms["residue_fns"]): if not fast_only: n_ms = 0 if ms.get("vectors") is None else np.asarray(ms["vectors"]).shape[1] - self.attempt("minimal-support fit", reason=f"{n_ms} direction(s) of minimal support found for " - f"{len(self.residual)} within minsupport_cand_cap; raise it") + self.attempt( + "minimal-support fit", + reason=f"{n_ms} direction(s) of minimal support found for " + f"{len(self.residual)} within minsupport_cand_cap; raise it", + ) return None - rec = [self.one(anchor, ms["residue_fns"][gi], log_coords=True, fast_only=fast_only) - for gi, anchor in enumerate(ms["anchors"])] + rec = [ + self.one(anchor, ms["residue_fns"][gi], log_coords=True, fast_only=fast_only) + for gi, anchor in enumerate(ms["anchors"]) + ] for e in rec: self.attempt("minimal-support " + ("read-off" if fast_only else "fit"), e) return rec if all(e.get("closed_form") for e in rec) else None @@ -729,20 +898,36 @@ def ms_try(self, ms, fast_only): def dense(self, ms): """Each direction from a shared sample bank, per prime where it is missing, then in canonical and log gauges.""" an, sc, run = self.an, self.sc, self.an.run - metas = [direction_relevance(fc, sc["ref"], sc["pivots"], an.z_slots, an.n_aug, sc["point0"], - self.rel_probe, None) for fc in self.residual] + metas = [ + direction_relevance(fc, sc["ref"], sc["pivots"], an.z_slots, an.n_aug, sc["point0"], self.rel_probe, None) + for fc in self.residual + ] def zvals_of(pt): return np.asarray(pt)[an.z_slots] if len(an.z_slots) else None + needs, degrees = [], [] for fc, m in zip(self.residual, metas): - degs = entry_degrees(fc, sc["pivots"], sc["point0"], lambda rp, p, z, fc=fc: null_residues(rp, fc, p), - zvals_of, m, self.kb, sc["nt_used"], self.ctrl) + degs = entry_degrees( + fc, + sc["pivots"], + sc["point0"], + lambda rp, p, z, fc=fc: null_residues(rp, fc, p), + zvals_of, + m, + self.kb, + sc["nt_used"], + self.ctrl, + ) degrees.append(degs) # a direction with an entry past degree_cap cannot use the bank - needs.append(0 if "over" in degs else - dense_need(m["rel_by_entry"], self.ctrl, - [d if isinstance(d, int) else None for d in degs])["max_need"]) + needs.append( + 0 + if "over" in degs + else dense_need(m["rel_by_entry"], self.ctrl, [d if isinstance(d, int) else None for d in degs])[ + "max_need" + ] + ) # where the log-coordinate gauge closes a direction of large need, the gauge fit is the cheaper one early = [None] * len(self.residual) if any(nd > _LOG_FIRST for nd in needs): @@ -757,8 +942,18 @@ def zvals_of(pt): bank = None if dense_dir: union = sorted({x for i in dense_dir for x in metas[i]["relevant"]}) - bk = build_shared_bank(union, max(needs[i] for i in dense_dir), sc["point0"], sc["pool"], - self.pool_next, self.kb, sc["pivots"], sc["nt_used"], len(PRIMES), self.ctrl) + bk = build_shared_bank( + union, + max(needs[i] for i in dense_dir), + sc["point0"], + sc["pool"], + self.pool_next, + self.kb, + sc["pivots"], + sc["nt_used"], + len(PRIMES), + self.ctrl, + ) self.pool_next = bk["pool_next"] if bk.get("ok"): bank = bk @@ -769,8 +964,11 @@ def zvals_of(pt): if early[ii] is not None: interp.append(early[ii]) continue - r = self.one(fc, None, per_prime=True) if bank_missing else \ - self.one(fc, None, bank=bank, degrees=degrees[ii]) + r = ( + self.one(fc, None, per_prime=True) + if bank_missing + else self.one(fc, None, bank=bank, degrees=degrees[ii]) + ) if not r.get("closed_form") and run.ss_constraint and not bank_missing: self.attempt("dense fit", r) r = self.one(fc, None, per_prime=True) @@ -780,8 +978,9 @@ def zvals_of(pt): closed = self._forward_adopt(self._forward_retrying(self._forward_multi)) if closed is not None: interp = self._forward_checked(self._forward_entries(closed)) - self.tlog(f"forward-multi closed {sum(bool(e.get('closed_form')) for e in interp)} " - "residual direction(s)") + self.tlog( + f"forward-multi closed {sum(bool(e.get('closed_form')) for e in interp)} residual direction(s)" + ) if bank_missing: return interp @@ -795,6 +994,7 @@ def rescue(gauge, log_coords=False): self.attempt("log-coordinate gauge" if log_coords else "canonical gauge", rec) if rec.get("closed_form"): interp[ii] = rec + P, nz, scal_rows = PRIMES[0], an.nz, an.scal_rows if not all(e.get("closed_form") for e in interp): rescue(canon_gauge(self.residual, scal_rows, P, nz, sc)) @@ -817,13 +1017,22 @@ def run(self): skip = set(state.get("open_coords") or ()) held = [fc for fc in self.residual if an.znames[fc] in skip] self.residual = [fc for fc in self.residual if an.znames[fc] not in skip] - held = [{"support": sym_sort([an.znames[i] for i in np.nonzero(self.residues(fc))[0]]), "type": "general", - "closed_form": False, "reason": "a direction of the fresh coordinates of a switch surface", - "kernel_residue": self.residues(fc).tolist()} for fc in held] + held = [ + { + "support": sym_sort([an.znames[i] for i in np.nonzero(self.residues(fc))[0]]), + "type": "general", + "closed_form": False, + "reason": "a direction of the fresh coordinates of a switch surface", + "kernel_residue": self.residues(fc).tolist(), + } + for fc in held + ] if an.joint and self.residual: self.tlog("solve fill: " + ("serial" if run.cores <= 1 else f"fork, {run.cores} cores")) - self.tlog(f"start: {len(self.residual)} residual direction(s)" + - (f", {len(held)} of fresh coordinates left open" if held else "")) + self.tlog( + f"start: {len(self.residual)} residual direction(s)" + + (f", {len(held)} of fresh coordinates left open" if held else "") + ) static_part = self.statics() if an.joint and self.residual else [] stacked_ss = an.stacked_first and run.ss_constraint fwd_first = self.forward_first(stacked_ss) @@ -851,11 +1060,19 @@ def run(self): if not self.residual or fields_closed: self.rel_probe = [None] * an.n_aug elif ms_early is not None: + def ms_res(rp, p, zvals=None): v = [f(rp, p) for f in ms_early["residue_fns"]] return None if any(x is None for x in v) else np.concatenate(v) - self.rel_probe = self.probe_groups(self.kb, self.sc["pivots"], self.probe_next, ms_res, - self.sc["ref"], vecs=np.asarray(ms_early["vectors"])) + + self.rel_probe = self.probe_groups( + self.kb, + self.sc["pivots"], + self.probe_next, + ms_res, + self.sc["ref"], + vecs=np.asarray(ms_early["vectors"]), + ) else: self.rel_probe = self.full_probe() self.tlog("relevance probe done" + (" (minimal-support gauge)" if ms_early is not None else "")) @@ -884,8 +1101,18 @@ def ms_res(rp, p, zvals=None): if interp is None: interp = self.homotopy(self.dense(ms)) # an open direction keeps the kernel vector found for it, so that the kernel fill does not repeat it - interp = [e if e.get("closed_form") else dict(e, kernel_residue=self.residues(fc).tolist()) - for e, fc in zip(interp, self.residual)] + interp = [ + e if e.get("closed_form") else dict(e, kernel_residue=self.residues(fc).tolist()) + for e, fc in zip(interp, self.residual) + ] self.tlog(f"reconstruction done: {sum(bool(e.get('closed_form')) for e in interp)}/{len(interp)} closed") - return (an.scaling + narrowed + peeled + static_part + list(field_part) + fwd_first - + self.with_attempts(list(interp)) + held) + return ( + an.scaling + + narrowed + + peeled + + static_part + + list(field_part) + + fwd_first + + self.with_attempts(list(interp)) + + held + ) diff --git a/src/symident/detection/observability/rest.py b/src/symident/detection/observability/rest.py index 51931d6..5f5aacb 100644 --- a/src/symident/detection/observability/rest.py +++ b/src/symident/detection/observability/rest.py @@ -43,18 +43,26 @@ def held_of(self, ci): def joint_pv(self, point, p): """Parameter, log and held-pivot values of a point for the steady-state solve.""" + def val(nm): s = self.run.slot(nm) return 0 if s is None else int(point[s]) % p - return {"param_vals": {nm: val(nm) for nm in self.solve_param_names}, - "l_vals": {nm: val(nm) for nm in self.l_names} if self.l_names else None, - "held_vals": {nm: val(self.held_param_of[nm]) for nm in self.held_names} - if self.held_names else None} + + return { + "param_vals": {nm: val(nm) for nm in self.solve_param_names}, + "l_vals": {nm: val(nm) for nm in self.l_names} if self.l_names else None, + "held_vals": {nm: val(self.held_param_of[nm]) for nm in self.held_names} if self.held_names else None, + } def solve_key(self, p, pv, ci): """Cache key of the steady state solve of condition `ci` at the values `pv` mod `p`.""" - return (self.model_key[ci], p, tuple(pv["param_vals"][n] for n in self.model_params[ci]), - tuple((pv["l_vals"] or {}).values()), tuple((pv["held_vals"] or {}).values())) + return ( + self.model_key[ci], + p, + tuple(pv["param_vals"][n] for n in self.model_params[ci]), + tuple((pv["l_vals"] or {}).values()), + tuple((pv["held_vals"] or {}).values()), + ) def solve_raw(self, p, pv, ci): """The modular steady state of condition `ci` at the values `pv`, or None on failure.""" @@ -63,11 +71,18 @@ def solve_raw(self, p, pv, ci): t0 = time.monotonic() try: out = solve_steady_state_modular( - model=self.models[ci], state_names=list(self.real_state_names), - param_names=list(self.solve_param_names), param_vals=pv["param_vals"], prime=p, - forcings=self.held_of(ci) or None, t0events=ev_c, recast=self.recast or None, - l_vals=pv["l_vals"], joint_mode=True, - held_states=pv["held_vals"] if self.held_names else None) + model=self.models[ci], + state_names=list(self.real_state_names), + param_names=list(self.solve_param_names), + param_vals=pv["param_vals"], + prime=p, + forcings=self.held_of(ci) or None, + t0events=ev_c, + recast=self.recast or None, + l_vals=pv["l_vals"], + joint_mode=True, + held_states=pv["held_vals"] if self.held_names else None, + ) except MsolveMissingError: raise except SYMPY_FAILS as exc: @@ -108,9 +123,15 @@ def merge_route_states(self, base, states): def rest_kind(self, p, pv, ci): """resting_kind() of condition `ci` at the values `pv`.""" - return resting_kind(self.models[ci], list(self.real_state_names), list(self.solve_param_names), - pv["param_vals"], p, forcings=self.held_of(ci) or None, - held_states=pv["held_vals"] if self.held_names else None) + return resting_kind( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + pv["param_vals"], + p, + forcings=self.held_of(ci) or None, + held_states=pv["held_vals"] if self.held_names else None, + ) def warm_solves(self, pts, primes, conds=None): """The solve cache for a batch of points, in forked workers.""" @@ -136,11 +157,14 @@ def warm_solves(self, pts, primes, conds=None): if len(jobs) < 2: return t0 = time.monotonic() - res = process_map(lambda j: self.solve_raw(j["p"], j["pv"], j["ci"]), jobs, - min(run.cores, len(jobs)), on_error=lambda j: None) + res = process_map( + lambda j: self.solve_raw(j["p"], j["pv"], j["ci"]), jobs, min(run.cores, len(jobs)), on_error=lambda j: None + ) if run.timing: - print(f"[sym] warm fill: {len(jobs)} solve(s), fork x{min(run.cores, len(jobs))}, " - f"{time.monotonic() - t0:.1f}s") + print( + f"[sym] warm fill: {len(jobs)} solve(s), fork x{min(run.cores, len(jobs))}, " + f"{time.monotonic() - t0:.1f}s" + ) for j, r in zip(jobs, res): if r is not None: self.solve_cache[j["key"]] = r if r.get("ok") else {"ok": False} @@ -148,7 +172,7 @@ def warm_solves(self, pts, primes, conds=None): def _seed(self, point, p, sol, ci, rates=None): """The point with the solved resting states (and rates) in the leaves.""" run = self.run - ptc = np.array(point[:run.n_leaves], dtype=np.int64) + ptc = np.array(point[: run.n_leaves], dtype=np.int64) for r, v in (rates or {}).items(): s = run.slot(r) if s is not None: @@ -219,8 +243,13 @@ def rest_system(self, ci, pinned=True): """(balances, states, parameters, linear) of the resting solve of condition `ci`: held pivots as parameters, with `pinned` each split balance replaced by the factor the session pinned.""" held = tuple(sorted(self.held_names)) - c = _ss_compile(list(self.models[ci]), list(self.real_state_names), list(self.solve_param_names), - set(self.held_of(ci)), held) + c = _ss_compile( + list(self.models[ci]), + list(self.real_state_names), + list(self.solve_param_names), + set(self.held_of(ci)), + held, + ) params, states, polys, linear, plan = list(c[0]), list(c[1]), list(c[2]), c[9], c[11] if plan is not None: keep = [(s, P) for s, P in zip(states, polys) if str(s) not in set(held)] @@ -245,9 +274,14 @@ def rest_degree(self, ci, point): vals = dict(pv["param_vals"], **(pv["held_vals"] or {})) conj = _conjugate(tuple(polys), tuple(states), {s: int(vals.get(str(s), 0)) for s in params}) if conj is not True: - return {"why": f"the resting states of condition {k} have " + - ("several branches over Q(theta)" if conj is False else - "branches that are not decided over Q(theta)")} + return { + "why": f"the resting states of condition {k} have " + + ( + "several branches over Q(theta)" + if conj is False + else "branches that are not decided over Q(theta)" + ) + } return {"bezout": bd[0], "jac": bd[1]} def solve_cond_fwd(self, point, p, ci, solve_rates): @@ -257,20 +291,32 @@ def solve_cond_fwd(self, point, p, ci, solve_rates): def rd(nm): s = run.slot(nm) return 0 if s is None else int(point[s]) % p + sv = {nm: rd(nm) for nm in self.real_state_names} pv = {nm: rd(nm) for nm in self.solve_param_names} - key = (self.model_key[ci], p, tuple(sv.values()), tuple(pv.values()), - solve_rates.key() if hasattr(solve_rates, "key") else tuple(solve_rates), - tuple(self.held_of(ci))) + key = ( + self.model_key[ci], + p, + tuple(sv.values()), + tuple(pv.values()), + solve_rates.key() if hasattr(solve_rates, "key") else tuple(solve_rates), + tuple(self.held_of(ci)), + ) sol = self.fwd_solve_cache.get(key) if sol is None: try: - sol = solve_forward_modular(self.models[ci], list(self.real_state_names), - list(self.solve_param_names), sv, pv, p, - forcings=self.held_of(ci) or None, - solve_rates=list(solve_rates), - state_solve=list(getattr(solve_rates, "state_solve", [])), - held=self.held_names or None) + sol = solve_forward_modular( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + sv, + pv, + p, + forcings=self.held_of(ci) or None, + solve_rates=list(solve_rates), + state_solve=list(getattr(solve_rates, "state_solve", [])), + held=self.held_names or None, + ) except SYMPY_FAILS as exc: sympy_fail(exc) sol = None @@ -288,15 +334,13 @@ def base_key(self, point, p): """Key of the diagonal base of a point: the values of the point off Z.""" jp = self.joint_pv(point, p) z = set(self.diag.Z) - return (p, tuple(v for n, v in jp["param_vals"].items() if n not in z), - tuple((jp["held_vals"] or {}).values())) + return (p, tuple(v for n, v in jp["param_vals"].items() if n not in z), tuple((jp["held_vals"] or {}).values())) def fwd_seed(self, point, p): """The first condition solved forward, at Z = 0 under the diagonal start; rates written into the point.""" run = self.run diag = self.diag - sv = {nm: (0 if run.slot(nm) is None else int(point[run.slot(nm)]) % p) - for nm in self.real_state_names} + sv = {nm: (0 if run.slot(nm) is None else int(point[run.slot(nm)]) % p) for nm in self.real_state_names} pv = self.joint_pv(point, p)["param_vals"] forc = list(self.held_of(self.fwd_cond)) keep = list(self.fwd_banned) @@ -310,17 +354,25 @@ def solve(): fr = self.fwd_rates try: return solve_forward_modular( - self.models[self.fwd_cond], list(self.real_state_names), - list(self.solve_param_names), sv, pv, p, forcings=forc or None, + self.models[self.fwd_cond], + list(self.real_state_names), + list(self.solve_param_names), + sv, + pv, + p, + forcings=forc or None, solve_rates=list(fr) if fr is not None else None, state_solve=list(fr.state_solve) if fr is not None else None, - keep_free=keep or None, held=self.held_names or None) + keep_free=keep or None, + held=self.held_names or None, + ) except SYMPY_FAILS as exc: sympy_fail(exc) return None except Exception as exc: swallow(exc, "forward seed") return None + sol = solve() if self.fwd_rates is None: for _ in range(5): @@ -351,11 +403,21 @@ def solve(): return None free = sorted(str(x) for x in self.real_state_names if x not in set(diag.S if diag is not None else ())) # the backward solves at other points take roots on the branch of the seed - pin_branch(self.models[self.fwd_cond], list(self.real_state_names), list(self.solve_param_names), forc, - self.held_names or None, {**pv, **sol["rates"], **sol["val_by"]}, p) - session.note("branches", f"forward seed: the resting states {', '.join(free) or '-'} drawn, the rates " - f"{', '.join(map(str, self.fwd_rates))} solved from the balances; the result holds " - "on the component of the resting set these values parametrize") + pin_branch( + self.models[self.fwd_cond], + list(self.real_state_names), + list(self.solve_param_names), + forc, + self.held_names or None, + {**pv, **sol["rates"], **sol["val_by"]}, + p, + ) + session.note( + "branches", + f"forward seed: the resting states {', '.join(free) or '-'} drawn, the rates " + f"{', '.join(map(str, self.fwd_rates))} solved from the balances; the result holds " + "on the component of the resting set these values parametrize", + ) point = np.array(point, dtype=np.int64) for r, v in zip(self.fwd_rates, rv): point[run.slot(r)] = v @@ -376,9 +438,13 @@ def cont_eligible(self, ci): return False if self.diag is not None: return self.fwd_on and ci in self.equil_conds - return (self.fwd_on and self.run.has_gaps and ci != self.fwd_cond - and self.model_key[ci] != self.model_key[self.fwd_cond] - and not self.held_names) + return ( + self.fwd_on + and self.run.has_gaps + and ci != self.fwd_cond + and self.model_key[ci] != self.model_key[self.fwd_cond] + and not self.held_names + ) def cont_active(self, ci): """Whether condition `ci` is eligible for continuation and the continuation is not switched off.""" @@ -389,8 +455,7 @@ def cont_trace(self, ci, success): if self.cont_seen[ci] or not self.run.timing: return self.cont_seen[ci] = True - print(f"[sym] condition {ci + 1}: " + - ("continued" if success else "continuation failed, solved directly")) + print(f"[sym] condition {ci + 1}: " + ("continued" if success else "continuation failed, solved directly")) def cont_params(self, ci): """The parameters condition `ci` is continued along.""" @@ -418,12 +483,18 @@ def cont_cond(self, point, p, ci): for n in priv: pv0[n] = 0 try: - sol = continue_resting_state(self.models[ci], list(self.real_state_names), - list(self.solve_param_names), pv0, - {n: pv["param_vals"][n] for n in priv}, - rest, p, self.cont_t, - forcings=self.held_of(ci) or None, - held={n: 0 for n in self.held_names} or None) + sol = continue_resting_state( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + pv0, + {n: pv["param_vals"][n] for n in priv}, + rest, + p, + self.cont_t, + forcings=self.held_of(ci) or None, + held={n: 0 for n in self.held_names} or None, + ) except SYMPY_FAILS as exc: sympy_fail(exc) sol = None @@ -436,7 +507,7 @@ def cont_cond(self, point, p, ci): return None elif not sol.get("ok"): return None - ptc = np.array(point[:run.n_leaves], dtype=np.int64) + ptc = np.array(point[: run.n_leaves], dtype=np.int64) ser = np.zeros((run.n_leaves, self.cont_t), dtype=np.int64) for nm, vals in sol["val_by"].items(): sl = run.slot(nm) @@ -444,7 +515,7 @@ def cont_cond(self, point, p, ci): continue v = [int(x) % p for x in vals] ptc[sl] = v[0] - ser[sl, :] = v[1:1 + self.cont_t] + ser[sl, :] = v[1 : 1 + self.cont_t] for nm in self.cont_params(ci): sl = run.slot(nm) if sl is None: @@ -462,15 +533,21 @@ def in_torus(self, sol, ci): """Whether a continued rest leaves the zero set of the diagonal start.""" if self.diag is None: return True - return all(any(int(v) for v in sol["val_by"][s]) - for s in self.diag.S if s in sol["val_by"] and s not in self.held_of(ci)) + return all( + any(int(v) for v in sol["val_by"][s]) + for s in self.diag.S + if s in sol["val_by"] and s not in self.held_of(ci) + ) @staticmethod def sol_at(sol, k): """The df payload of a continued solve at eps^k.""" - return {"df_jx": [[int(x[k]) for x in r] for r in sol["df_jx"]], - "df_jt": {th: [int(x[k]) for x in col] for th, col in sol["df_jt"].items()}, - "df_state_cols": sol["df_state_cols"], "df_param_cols": sol["df_param_cols"]} + return { + "df_jx": [[int(x[k]) for x in r] for r in sol["df_jx"]], + "df_jt": {th: [int(x[k]) for x in col] for th, col in sol["df_jt"].items()}, + "df_state_cols": sol["df_state_cols"], + "df_param_cols": sol["df_param_cols"], + } def rest_chart(self, point, p): """InputError where the resting values of the states inside non-rational terms do not vary independently of @@ -497,12 +574,17 @@ def rest_chart(self, point, p): e_z = np.zeros((len(zc), self.nz_local), dtype=np.int64) for i, c in enumerate(zc): e_z[i, c] = 1 - M = np.vstack([self.df_rows(sc0["sol"], p), e_z, - np.asarray(e_m, dtype=np.int64).reshape(-1, self.nz_local)]) % p + M = ( + np.vstack( + [self.df_rows(sc0["sol"], p), e_z, np.asarray(e_m, dtype=np.int64).reshape(-1, self.nz_local)] + ) + % p + ) rest = [c for c in range(self.nz_local) if c not in set(cols)] def rank(X): return int(_core.sym_rref_mod(X.astype(np.float64), p)["rank"]) if X.size else 0 + # the tangent space of the resting set projects onto the columns `cols` exactly when deleting them keeps # the rank of the rows if rank(M[:, rest]) < rank(M): @@ -512,7 +594,8 @@ def rank(X): f"non-rational terms, do not vary independently of the parameters inside these terms " f"({', '.join(sorted(z for z in A if z in set(self.param_names) and not z.startswith('_')))}); " f"no parameter outside these terms can be solved for them from the resting balances. " - f"Give the steady state through `trafo` or start from free initial values") + f"Give the steady state through `trafo` or start from free initial values" + ) def sat_prep(self, point, P1=None, rounds=8): """A point with every resting state solved at P1; failed conditions redraw their private parameters.""" @@ -531,8 +614,7 @@ def sat_prep(self, point, P1=None, rounds=8): if not failed: self.rest_chart(point, P1) return point - run.ss_why = ("joint solve failed for condition " + - ", ".join(str(c + 1) for c in dict.fromkeys(failed))) + run.ss_why = "joint solve failed for condition " + ", ".join(str(c + 1) for c in dict.fromkeys(failed)) redraw = list(dict.fromkeys(n for ci in failed for n in self.private_of[ci])) if any(len(self.private_of[ci]) == 0 for ci in failed): return None @@ -540,8 +622,10 @@ def sat_prep(self, point, P1=None, rounds=8): for k, nm in enumerate(redraw): point[run.slot(nm)] = vals[k] if run.timing: - print(f"[sym] redraw {','.join(redraw)} for condition(s) " - f"{','.join(str(c + 1) for c in dict.fromkeys(failed))}") + print( + f"[sym] redraw {','.join(redraw)} for condition(s) " + f"{','.join(str(c + 1) for c in dict.fromkeys(failed))}" + ) return None diff --git a/src/symident/detection/observability/select.py b/src/symident/detection/observability/select.py index 93d28bb..7e7b2a6 100644 --- a/src/symident/detection/observability/select.py +++ b/src/symident/detection/observability/select.py @@ -40,11 +40,16 @@ def eligible(multi, n_gaps, implicit_steady_state): return False if multi.get("equilibrate") and not resting(multi, implicit_steady_state): return False - if resting(multi, implicit_steady_state) and (multi.get("held_state_params") or multi.get("rest_aux") or - multi.get("rest_inverted")): + if resting(multi, implicit_steady_state) and ( + multi.get("held_state_params") or multi.get("rest_aux") or multi.get("rest_inverted") + ): return False - if multi.get("nuisance") or multi.get("nuisance_order") is not None or multi.get("power_recast") or \ - multi.get("exp_atoms"): + if ( + multi.get("nuisance") + or multi.get("nuisance_order") is not None + or multi.get("power_recast") + or multi.get("exp_atoms") + ): return False nz = len(multi.get("z_slots") or []) return all(t.get("ic_seed") is None and len(t.get("lie_reach") or []) == nz for t in tapes) @@ -88,12 +93,27 @@ def choose(multi, cores, nt=None, kept=()): nt = lie_reach_max(tapes) + 2 if nt is None else int(nt) for k in range(4): pt = random_point(int(multi["n_leaves"]), seed=session.current().seed("condition selection", k) % (1 << 31)) - r = _core.sym_obs_cover(kt, int(multi["n_leaves"]), int(multi["n_states"]), - np.asarray(multi["z_slots"], dtype=np.int64), pt, PRIMES[0], nt, nz, cores, - np.asarray(order, dtype=np.int64), first) + r = _core.sym_obs_cover( + kt, + int(multi["n_leaves"]), + int(multi["n_states"]), + np.asarray(multi["z_slots"], dtype=np.int64), + pt, + PRIMES[0], + nt, + nz, + cores, + np.asarray(order, dtype=np.int64), + first, + ) if ok(r): - return {"kept": sorted(ints(r["conditions"])), "rank": int(r["rank"]), "lie_order": nt, - "structures": n_struct, "taken": int(r["taken"])} + return { + "kept": sorted(ints(r["conditions"])), + "rank": int(r["rank"]), + "lie_order": nt, + "structures": n_struct, + "taken": int(r["taken"]), + } return None @@ -215,8 +235,17 @@ def _annihilated(multi, conds, fields, nt, cores): memo, out = {}, [] for c in conds: t = kernel_tapes([tape_fields(multi["tapes"][c], memo)]) - o = _core.sym_obs_annihilates(t, int(multi["n_leaves"]), int(multi["n_states"]), - np.asarray(multi["z_slots"], dtype=np.int64), pt, P, int(nt), V, cores) + o = _core.sym_obs_annihilates( + t, + int(multi["n_leaves"]), + int(multi["n_states"]), + np.asarray(multi["z_slots"], dtype=np.int64), + pt, + P, + int(nt), + V, + cores, + ) out.append(None if not ok(o) else [bool(x) for x in np.atleast_1d(o["zero"])]) return out @@ -319,7 +348,7 @@ def _bisect(conds, proven, cap=_SINGLE): if len(todo) + len(bad) >= cap: bad += part continue - todo += [part[:len(part) // 2], part[len(part) // 2:]] + todo += [part[: len(part) // 2], part[len(part) // 2 :]] return bad @@ -327,6 +356,7 @@ def _lifted(multi, pending, dirs, cores, at_rest=False): """The directions of `pending` ({direction: conditions}) whose lift of the closed form is proven on all of their conditions at once, `at_rest` where the conditions start at rest.""" from .proof import representatives + out = set() conds = sorted({c for cs in pending.values() for c in cs}) if not conds: @@ -348,8 +378,9 @@ def attempt(j, known): d = dirs[j] chains = [[pos[c]] for c in pending[j]] # the lift proven on the kept conditions first - proven = [dict(d["lift_form"], **d["state_components"])] if d.get("lift_form") and \ - d.get("state_components") else [] + proven = ( + [dict(d["lift_form"], **d["state_components"])] if d.get("lift_form") and d.get("state_components") else [] + ) for vec in proven + representatives(d): try: ex = exact_direction(light, vec, chains, at_rest, known=known) diff --git a/src/symident/detection/observability/start.py b/src/symident/detection/observability/start.py index b055267..59aa04d 100644 --- a/src/symident/detection/observability/start.py +++ b/src/symident/detection/observability/start.py @@ -30,8 +30,7 @@ def __init__(self, models, reps, fwd, held_of, candidates, keep=(), cap=12): self.rhs = {ci: _rhs(models[ci]) for ci in dict.fromkeys(self.reps + [fwd])} self.cand = set(candidates) base = {str(s) for s in self._symbols(self.fwd)} - priv = [str(s) for ci in self.reps for s in self._symbols(ci) - if str(s) in self.cand and str(s) not in base] + priv = [str(s) for ci in self.reps for s in self._symbols(ci) if str(s) in self.cand and str(s) not in base] Z = [z for z in dict.fromkeys(priv) if self._regular(Z=[z])] self.ok = False for _ in range(cap + 1): @@ -86,8 +85,9 @@ def _dead(self, Z, S): sub = {spy.Symbol(n): 0 for n in list(Z) + list(S) + list(self.held_of(self.fwd))} f0 = self.rhs[self.fwd] before = set().union(*(e.free_symbols for e in f0.values())) - after = set().union(*(spy.cancel(spy.together(e.xreplace(sub))).free_symbols - for k, e in f0.items() if k not in S)) + after = set().union( + *(spy.cancel(spy.together(e.xreplace(sub))).free_symbols for k, e in f0.items() if k not in S) + ) return sorted(str(x) for x in before - after if str(x) in self.cand and str(x) not in Z) def _symbols(self, ci): diff --git a/src/symident/detection/perprime.py b/src/symident/detection/perprime.py index c4412af..f1ca81e 100644 --- a/src/symident/detection/perprime.py +++ b/src/symident/detection/perprime.py @@ -10,8 +10,9 @@ from .sparse import _pivots_eq -def pinned_monomials(f, pivots, znames, leaf_names, point0, nt_used, kcall, nv, base_nv, - support_cols, rel_by_entry, rel_probe, max_exp=6): +def pinned_monomials( + f, pivots, znames, leaf_names, point0, nt_used, kcall, nv, base_nv, support_cols, rel_by_entry, rel_probe, max_exp=6 +): """Each entry of a support-pinned direction as a Laurent monomial; None otherwise.""" P = PRIMES[0] @@ -30,6 +31,7 @@ def find_exp(base, target, p): if acc == target: return -a return None + entries = {} for i, ci in enumerate(support_cols): reli = rel_by_entry[i] @@ -59,6 +61,7 @@ def mono_denom(pj): bv = int(point0[l]) % pj d = d * (pow(bv, a, pj) if a >= 0 else pow(invmod(bv, pj), -a, pj)) % pj return d + use_primes = [P] resid = [e0 * invmod(mono_denom(P), P) % P] for pj in PRIMES[1:]: @@ -85,16 +88,19 @@ def mono_denom(pj): expr = num_s if not den else f"({num_s})/({'*'.join(den)})" entries[znames[ci]] = simplify(expr) entries[znames[f]] = "1" - return {"support": sym_sort(list(entries)), "vector": entries, "type": "general", - "closed_form": True} + return {"support": sym_sort(list(entries)), "vector": entries, "type": "general", "closed_form": True} def _fallback(pool_next, znames, base_nv, reason): - return {"pool_next": pool_next, - "entry": {"support": sym_sort([znames[i] for i in np.nonzero(base_nv)[0]]), - "type": "general", "closed_form": False, "reason": reason}} - - + return { + "pool_next": pool_next, + "entry": { + "support": sym_sort([znames[i] for i in np.nonzero(base_nv)[0]]), + "type": "general", + "closed_form": False, + "reason": reason, + }, + } def _lift_const(vals, prs): @@ -104,15 +110,32 @@ def _lift_const(vals, prs): return rec["num"][0] if rec["den"][0] == "1" else f"{rec['num'][0]}/{rec['den'][0]}" -def interpolate_perprime(f, ref, pivots, znames, z_slots, leaf_names, n_leaves, point0, pool, - pool_next, nt_used, kcall, kbatch, rel_probe, ctrl, aux_leaves=(), - phys_cols=None): +def interpolate_perprime( + f, + ref, + pivots, + znames, + z_slots, + leaf_names, + n_leaves, + point0, + pool, + pool_next, + nt_used, + kcall, + kbatch, + rel_probe, + ctrl, + aux_leaves=(), + phys_cols=None, +): """Per-prime fits over the points each prime solves, coefficients lifted by CRT.""" n_p = len(PRIMES) aux = set(aux_leaves) def nv(rp, p): return null_residues(rp, f, p) + rel = direction_relevance(f, ref, pivots, z_slots, n_leaves, point0, rel_probe, None) base_nv, support_cols, rel_by_entry = rel["base_nv"], rel["support_cols"], rel["rel_by_entry"] if phys_cols is not None: @@ -124,10 +147,15 @@ def nv(rp, p): def ex(v): return [x for x in v if x not in aux] + max_rel_phys = max([0] + [len(ex(e)) for e in rel_by_entry]) if len(ex(relevant)) > ctrl["relevance_cap_dir"] or max_rel_phys > ctrl["relevance_cap_sparse"]: - return _fallback(pool_next, znames, base_nv, - f"direction couples {len(ex(relevant))} parameters (an entry up to {max_rel_phys})") + return _fallback( + pool_next, + znames, + base_nv, + f"direction couples {len(ex(relevant))} parameters (an entry up to {max_rel_phys})", + ) def const_entry(col): vals, prs = [], [] @@ -143,6 +171,7 @@ def const_entry(col): if not prs: return None return _lift_const(vals, prs) + if not relevant: entries = {} for c in support_cols: @@ -151,9 +180,16 @@ def const_entry(col): return _fallback(pool_next, znames, base_nv, "a constant entry could not be lifted") entries[znames[c]] = e entries[znames[f]] = "1" - return {"pool_next": pool_next, "entry": {"support": sym_sort(list(entries)), - "vector": entries, "type": "general", - "closed_form": True, "relevant_leaves": []}} + return { + "pool_next": pool_next, + "entry": { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "relevant_leaves": [], + }, + } nrel = len(relevant) bank_u = [np.zeros((0, nrel), dtype=np.int64) for _ in range(n_p)] bank_r = [np.zeros((0, len(support_cols)), dtype=np.int64) for _ in range(n_p)] @@ -192,6 +228,7 @@ def ensure_prime(j, need): if tries_p[j] >= 80 * need + 256: break return bank_u[j].shape[0] >= need + entries = {} for i, c in enumerate(support_cols): reli = rel_by_entry[i] @@ -238,19 +275,35 @@ def ensure_prime(j, need): if any(d == "0" for d in rec["den"]): continue n_mon = mons.shape[0] - fitted = {"num_n": rec["num"][:n_mon], "num_d": rec["den"][:n_mon], - "den_n": rec["num"][n_mon:], "den_d": rec["den"][n_mon:], "mons": mons} + fitted = { + "num_n": rec["num"][:n_mon], + "num_d": rec["den"][:n_mon], + "den_n": rec["num"][n_mon:], + "den_d": rec["den"][n_mon:], + "mons": mons, + } break if fitted is None: - return _fallback(box["pool_next"], znames, base_nv, - "a joint entry could not be fit per-prime within degree_cap/perprime_cap; " - "raise them or the direction is not a bounded-degree rational") + return _fallback( + box["pool_next"], + znames, + base_nv, + "a joint entry could not be fit per-prime within degree_cap/perprime_cap; " + "raise them or the direction is not a bounded-degree rational", + ) vars_ = [leaf_names[r] for r in reli] num_str = poly_string(fitted["num_n"], fitted["num_d"], fitted["mons"], vars_) den_str = poly_string(fitted["den_n"], fitted["den_d"], fitted["mons"], vars_) expr = num_str if den_str == "1" else f"({num_str})/({den_str})" entries[znames[c]] = simplify(expr) entries[znames[f]] = "1" - return {"pool_next": box["pool_next"], "entry": {"support": sym_sort(list(entries)), - "vector": entries, "type": "general", - "closed_form": True, "relevant_leaves": relevant}} + return { + "pool_next": box["pool_next"], + "entry": { + "support": sym_sort(list(entries)), + "vector": entries, + "type": "general", + "closed_form": True, + "relevant_leaves": relevant, + }, + } diff --git a/src/symident/detection/rank.py b/src/symident/detection/rank.py index b36b29f..12fcc74 100644 --- a/src/symident/detection/rank.py +++ b/src/symident/detection/rank.py @@ -27,10 +27,27 @@ def _next_order(rk, nt, nt_end, need, cols): return min(nt_end, top) -def saturate_certify(kcall, n_leaves, nz, max_m=0, *, warm, set_caps, probe_block=1, block_call=None, - budget=None, block_map=None, nt_min=0, nt_min_block=None, prep=None, - rank_cap=None, block_profile=None, checks=True, longest_first=False, - stacked_profile=None): +def saturate_certify( + kcall, + n_leaves, + nz, + max_m=0, + *, + warm, + set_caps, + probe_block=1, + block_call=None, + budget=None, + block_map=None, + nt_min=0, + nt_min_block=None, + prep=None, + rank_cap=None, + block_profile=None, + checks=True, + longest_first=False, + stacked_profile=None, +): """Saturated reference rank after raising the Lie and gap orders, or None without a usable point; `longest_first` scans the blocks of the highest known orders first, for blocks without shared state; `stacked_profile` gives the rank per Lie order of the stacked rows from one jet.""" @@ -100,8 +117,10 @@ def scan_nt(call1, point, Mtot, frm, need, label, lo0=0, prof1=None, rel=0.0): if not _ok(res): return None if lie_diag: - print(f"[liediag] {label} Mtot={Mtot} ranks from Lie order {max(1, frm)}: " - f"{','.join(str(x) for x in rk[max(1, frm):Nt + 1])} (nz={nz}, profile to {nt_try})") + print( + f"[liediag] {label} Mtot={Mtot} ranks from Lie order {max(1, frm)}: " + f"{','.join(str(x) for x in rk[max(1, frm) : Nt + 1])} (nz={nz}, profile to {nt_try})" + ) return {"res": res, "Nt": Nt, "grew": grew, "ranks": rk} if frm > 1 and frm > lo0: # the higher order first: the kernel of the lower one reads the rows of the higher one @@ -113,8 +132,10 @@ def scan_nt(call1, point, Mtot, frm, need, label, lo0=0, prof1=None, rel=0.0): return None if rank_score(lo) == rank_score(hi): if lie_diag: - print(f"[liediag] {label} Mtot={Mtot} rank {lo['rank']} flat over Lie order " - f"{frm}-{frm + need} (nz={nz})") + print( + f"[liediag] {label} Mtot={Mtot} rank {lo['rank']} flat over Lie order " + f"{frm}-{frm + need} (nz={nz})" + ) return {"res": hi, "Nt": frm + need, "grew": frm} if Mtot > 0 and frm > 1: memo = {} @@ -126,6 +147,7 @@ def at(o): def sc1(r): return rank_score(r) if _ok(r) else None + cap = nz + 1 + lo0 x, step = max(1, frm), need while True: @@ -148,8 +170,9 @@ def sc1(r): grew = hi Nt = min(cap, grew + need) if lie_diag: - print(f"[liediag] {label} Mtot={Mtot} galloped from {frm} to order {grew} in " - f"{len(memo)} calls (nz={nz})") + print( + f"[liediag] {label} Mtot={Mtot} galloped from {frm} to order {grew} in {len(memo)} calls (nz={nz})" + ) return {"res": at(Nt), "Nt": Nt, "grew": grew} Nt = max(1, frm) prev, flat, grew = -1, 0, Nt @@ -170,8 +193,10 @@ def sc1(r): prev = rank_score(r) Nt += 1 if lie_diag: - print(f"[liediag] {label} Mtot={Mtot} ranks from Lie order {max(1, frm)}: " - f"{','.join(map(str, ranks))} (nz={nz})") + print( + f"[liediag] {label} Mtot={Mtot} ranks from Lie order {max(1, frm)}: " + f"{','.join(map(str, ranks))} (nz={nz})" + ) return {"res": res, "Nt": Nt, "grew": grew} def lo_of(bi): @@ -187,8 +212,17 @@ def saturate_nt(point, Mtot, from_orders=None): return None if not per_block: # the stacked rows of many conditions stall and rise again: the plateau grows with the order - sb = scan_nt(kcall, point, Mtot, 1, need_used, "stacked", nt_min, stacked_profile, - rel=float(state.env_value("STACKEDPLATEAU", "0.5")) if stacked_profile is not None else 0.0) + sb = scan_nt( + kcall, + point, + Mtot, + 1, + need_used, + "stacked", + nt_min, + stacked_profile, + rel=float(state.env_value("STACKEDPLATEAU", "0.5")) if stacked_profile is not None else 0.0, + ) if sb is not None: sb["point"] = point return sb @@ -196,11 +230,12 @@ def saturate_nt(point, Mtot, from_orders=None): Nt, driver, block_ranks = 1, 0, None t_scan = time.monotonic() if block_map is not None: + def one(bi): known = from_orders is not None and len(from_orders) == len(block_call) frm = max(1, int(from_orders[bi])) if known else 1 - return scan_nt(block_call[bi], point, Mtot, frm, need_used, f"block {bi + 1}", - lo_of(bi), prof_of(bi)) + return scan_nt(block_call[bi], point, Mtot, frm, need_used, f"block {bi + 1}", lo_of(bi), prof_of(bi)) + # the blocks of the highest known orders first, so that the longest scans do not start last nb = len(block_call) idx = list(range(nb)) @@ -218,8 +253,7 @@ def one(bi): block_ranks = [s.get("ranks") for s in sbs] else: for bi in range(len(block_call)): - sb = scan_nt(block_call[bi], point, Mtot, Nt, need_used, f"block {bi + 1}", - lo_of(bi), prof_of(bi)) + sb = scan_nt(block_call[bi], point, Mtot, Nt, need_used, f"block {bi + 1}", lo_of(bi), prof_of(bi)) if sb is None: return None orders[bi] = sb["grew"] @@ -231,14 +265,22 @@ def one(bi): t_call = time.monotonic() r = kcall(point, P, Nt, Mtot) if timing: - print(f"[sat] Mtot {Mtot}: scans {t_caps - t_scan:.1f}s, caps {t_call - t_caps:.1f}s, " - f"call {time.monotonic() - t_call:.1f}s; orders {min(orders)}-{max(orders)}") + print( + f"[sat] Mtot {Mtot}: scans {t_caps - t_scan:.1f}s, caps {t_call - t_caps:.1f}s, " + f"call {time.monotonic() - t_call:.1f}s; orders {min(orders)}-{max(orders)}" + ) if not _ok(r): return None if lie_diag: print(f"[liediag] block Lie orders: {','.join(map(str, orders))} -> stacked order {Nt}, rank {r['rank']}") - return {"res": r, "Nt": Nt, "block_orders": orders, "block_driver": driver, "point": point, - "block_ranks": block_ranks} + return { + "res": r, + "Nt": Nt, + "block_orders": orders, + "block_driver": driver, + "point": point, + "block_ranks": block_ranks, + } hint = state.get("order_hint") using_hint = False @@ -255,14 +297,15 @@ def saturate_nt(point, Mtot, from_orders=None): # noqa: F811 if not _ok(r): return None bo_ = list(hint["block_orders"]) - return {"res": r, "Nt": Nt, "block_orders": bo_, "block_driver": int(np.argmax(bo_)), - "point": point} + return {"res": r, "Nt": Nt, "block_orders": bo_, "block_driver": int(np.argmax(bo_)), "point": point} sat = None for attempt in range(1, 51): if probe_block > 1 and attempt >= 2 and (attempt - 2) % probe_block == 0: - pts = [point0 if k == 0 else pool(pool_next + (k - 1) * n_leaves + np.arange(n_leaves)) - for k in range(probe_block)] + pts = [ + point0 if k == 0 else pool(pool_next + (k - 1) * n_leaves + np.arange(n_leaves)) + for k in range(probe_block) + ] warm(pts, [P] * probe_block) sat = saturate_nt(point0, 0) if sat is not None: @@ -285,6 +328,7 @@ def saturate_nt(point, Mtot, from_orders=None): # noqa: F811 def sat_log(what): if timing: print(f"[sat {time.monotonic() - sat_t0:7.1f}s] {what}") + sat_log(f"scanned, Lie order {sat['Nt']}") nt_used, mtot_used = sat["Nt"], (int(hint["Mtot"]) if hinted else 0) # why the gap order stopped: "full" proves it sufficient, "plateau", "cap" and "failed" do not @@ -302,8 +346,10 @@ def sat_log(what): if sat_m is None: gap_stop = "failed" break - sat_log(f"gap order {mtot_used + 1}: Lie order {sat_m['Nt']}, score " - f"{rank_score(sat_m['res'])} (was {rank_score(sat['res'])})") + sat_log( + f"gap order {mtot_used + 1}: Lie order {sat_m['Nt']}, score " + f"{rank_score(sat_m['res'])} (was {rank_score(sat['res'])})" + ) mtot_used += 1 if rank_score(sat_m["res"]) <= rank_score(sat["res"]): gap_stop = "plateau" @@ -374,14 +420,28 @@ def sat_log(what): break _, sat, point0, nt_used = best if best[0] < rank_max: - session.note("limits", "rank: no saturated point reached the rank seen at another prime " - "or point; a direction may be reported too many") - return {"ref": sat["res"], "nt_used": nt_used, "mtot_used": mtot_used, "gap_stop": gap_stop, - "point0": point0, "pool": pool, "pool_next": pool_next, - "block_orders": sat.get("block_orders"), "block_driver": sat.get("block_driver"), - "block_ranks": sat.get("block_ranks"), "budget": budget, "plateau": need_used, - "rank": sat["res"]["rank"], "rank_s": rank_of(sat["res"]), - "pivots": sat["res"]["pivots"]} + session.note( + "limits", + "rank: no saturated point reached the rank seen at another prime " + "or point; a direction may be reported too many", + ) + return { + "ref": sat["res"], + "nt_used": nt_used, + "mtot_used": mtot_used, + "gap_stop": gap_stop, + "point0": point0, + "pool": pool, + "pool_next": pool_next, + "block_orders": sat.get("block_orders"), + "block_driver": sat.get("block_driver"), + "block_ranks": sat.get("block_ranks"), + "budget": budget, + "plateau": need_used, + "rank": sat["res"]["rank"], + "rank_s": rank_of(sat["res"]), + "pivots": sat["res"]["pivots"], + } def nullspace_basis(ref, free_cols, P): diff --git a/src/symident/detection/rationalize.py b/src/symident/detection/rationalize.py index 09740e2..cd42712 100644 --- a/src/symident/detection/rationalize.py +++ b/src/symident/detection/rationalize.py @@ -67,12 +67,14 @@ def _time_rate(at, states): def _split_time(e, states): """`e` with every exp(a*time + b) split into exp(a*time)*exp(b).""" + def split(at): arg = spy.expand(at.args[0]) tpart = sum((t for t in spy.Add.make_args(arg) if t.has(TIME)), spy.Integer(0)) if tpart == 0 or tpart == arg or _time_rate(spy.exp(tpart), states) is None: return at return spy.exp(tpart) * spy.exp(arg - tpart) + return e.replace(lambda a: isinstance(a, spy.exp), split) @@ -81,8 +83,13 @@ def _injective_forms(e): of a power with odd numerator, the argument of exp.""" out = [] for c in (spy.Integer(1), spy.log(10), spy.log(2)): - out.append((spy.expand_power_exp(spy.exp(spy.expand(e * c))), f"exp({_str(c)}*y)" if c != 1 else "exp(y)", - "exp is injective on the reals")) + out.append( + ( + spy.expand_power_exp(spy.exp(spy.expand(e * c))), + f"exp({_str(c)}*y)" if c != 1 else "exp(y)", + "exp is injective on the reals", + ) + ) if isinstance(e, spy.exp): out.append((e.args[0], "log(y)", "exp is injective on the reals")) if e.is_Pow and e.exp.is_Rational and e.exp.p % 2: @@ -91,8 +98,9 @@ def _injective_forms(e): def _transcendental(e): - return [a for a in spy.preorder_traversal(e) if isinstance(a, (spy.exp, spy.log)) or - (a.is_Pow and not a.exp.is_Integer)] + return [ + a for a in spy.preorder_traversal(e) if isinstance(a, (spy.exp, spy.log)) or (a.is_Pow and not a.exp.is_Integer) + ] def _constant_states(parts, coords): @@ -162,16 +170,18 @@ def _reciprocal_log_params(exprs, cs): def _reciprocal_sub(rp): """Rewriter of exp(c/theta) to X^(c/g), rp: theta -> (X, g).""" + def repl(at): terms = spy.expand(at.args[0]).as_coefficients_dict() if len(terms) != 1: return at - (t, c), = terms.items() + ((t, c),) = terms.items() th = 1 / t if t.is_Pow and t.exp == -1 else None if th not in rp: return at X, g = rp[th] return X ** (c / g) if (c / g).is_Integer else at + return lambda e: e.replace(lambda a: isinstance(a, spy.exp), repl) @@ -179,8 +189,9 @@ def rationalize(parts, coords, states): """(parts, rewrites, logs): `parts` (as in discrete.Series) in rational form with the same fiber, the rewrites applied and {coordinate: (base, L)} for a coordinate theta read as b^(theta/L). A ValueError names the term that keeps the model from being rational.""" - states = {spy.Symbol(x) for x in states} | {spy.Symbol(x) for part in parts for seg in part["segments"] - for x in seg["f"]} + states = {spy.Symbol(x) for x in states} | { + spy.Symbol(x) for part in parts for seg in part["segments"] for x in seg["f"] + } cs = {spy.Symbol(c) for c in coords} - states rewrites = [] orig = {} @@ -189,9 +200,14 @@ def rationalize(parts, coords, states): d[k] = model_sympify(str(d[k])) constant = _constant_states(parts, set(coords)) for x in dict.fromkeys(constant): - rewrites.append({"rewrite": "constant", "state": x, - "why": f"{x} has no dynamics and takes numbers at the start and at the events: within a " - "segment it is that number"}) + rewrites.append( + { + "rewrite": "constant", + "state": x, + "why": f"{x} has no dynamics and takes numbers at the start and at the events: within a " + "segment it is that number", + } + ) exprs = [d[k] for d, k in _strings(parts)] # log coordinates: theta enters only through b^(c*theta), as X = b^(theta/L) with integer powers base_of = {t: b for t, b in _detect_log_params(exprs, states).items() if t in cs} @@ -205,9 +221,15 @@ def rationalize(parts, coords, states): for t, b in sorted(base_of.items(), key=lambda kv: str(kv[0])): logs[str(t)] = (b, den[t]) ex = f"{_str(b)}^({t}/{den[t]})" if den[t] != 1 else (f"exp({t})" if b == spy.E else f"{_str(b)}^{t}") - rewrites.append({"rewrite": "coordinate", "from": ex, "to": str(t), - "why": f"{ex} is a bijection of the real line onto the positive reals: the fiber in " - f"{t} is the image of the fiber in {ex}"}) + rewrites.append( + { + "rewrite": "coordinate", + "from": ex, + "to": str(t), + "why": f"{ex} is a bijection of the real line onto the positive reals: the fiber in " + f"{t} is the image of the fiber in {ex}", + } + ) # coordinates read only as exp(c/theta), as X = exp(g/theta) with integer powers recip = _reciprocal_log_params([d[k] for d, k in _strings(parts)], cs - set(base_of)) if recip: @@ -217,28 +239,45 @@ def rationalize(parts, coords, states): for t, g in sorted(recip.items(), key=lambda kv: str(kv[0])): logs[str(t)] = (spy.E, g, "reciprocal") ex = f"exp({_str(g)}/{t})" - rewrites.append({"rewrite": "coordinate", "from": ex, "to": str(t), - "why": f"{ex} is a bijection of the positive reals onto the reals above 1 and of the " - f"negative reals onto (0, 1): the fiber in {t} is the image of the fiber in {ex}"}) + rewrites.append( + { + "rewrite": "coordinate", + "from": ex, + "to": str(t), + "why": f"{ex} is a bijection of the positive reals onto the reals above 1 and of the " + f"negative reals onto (0, 1): the fiber in {t} is the image of the fiber in {ex}", + } + ) # observables under an injective function: the function goes seen = {} for part in parts: for seg in part["segments"]: for y, e in list(seg["g"].items()): - if _is_rational_expr(_split_time(e, states).replace( - lambda a: _time_rate(a, states) is not None, lambda a: spy.Integer(1))): + if _is_rational_expr( + _split_time(e, states).replace( + lambda a: _time_rate(a, states) is not None, lambda a: spy.Integer(1) + ) + ): continue if (y, e) in seen: seg["g"][y] = seen[(y, e)] continue for w, how, why in _injective_forms(e): w = _split_time(w, states) - if _is_rational_expr(w.replace(lambda a: _time_rate(a, states) is not None, - lambda a: spy.Integer(1))): + if _is_rational_expr( + w.replace(lambda a: _time_rate(a, states) is not None, lambda a: spy.Integer(1)) + ): seen[(y, e)] = seg["g"][y] = w - rewrites.append({"rewrite": "observable", "observable": y, "from": _str(e), "to": _str(w), - "why": f"y = {_str(e)} as {how}: {why}, so two values of the coordinates " - "with the same output keep it after the rewrite and back"}) + rewrites.append( + { + "rewrite": "observable", + "observable": y, + "from": _str(e), + "to": _str(w), + "why": f"y = {_str(e)} as {how}: {why}, so two values of the coordinates " + "with the same output keep it after the rewrite and back", + } + ) break # exp(a*time) as a state E with E' = a*E, E(0) = 1 rates = {} @@ -257,13 +296,21 @@ def rationalize(parts, coords, states): rates[a] = spy.Symbol(nm) for part in parts: for j, seg in enumerate(part["segments"]): - if j == 0 and seg.get("ic") is not None and spy.sympify(seg["t"]) != 0 and \ - any(v is not None for v in seg["ic"].values()): - raise ValueError("discrete() rewrites exp(a*time) as a state that starts at 1 at time 0; the " - f"condition {seg.get('label') or ''} starts at {seg['t']}") + if ( + j == 0 + and seg.get("ic") is not None + and spy.sympify(seg["t"]) != 0 + and any(v is not None for v in seg["ic"].values()) + ): + raise ValueError( + "discrete() rewrites exp(a*time) as a state that starts at 1 at time 0; the " + f"condition {seg.get('label') or ''} starts at {seg['t']}" + ) for d, k in _strings(parts): - d[k] = d[k].replace(lambda a: _time_rate(a, states) in rates if isinstance(a, spy.exp) else False, - lambda a: rates[_time_rate(a, states)]) + d[k] = d[k].replace( + lambda a: _time_rate(a, states) in rates if isinstance(a, spy.exp) else False, + lambda a: rates[_time_rate(a, states)], + ) for part in parts: for j, seg in enumerate(part["segments"]): for a, E in rates.items(): @@ -274,16 +321,24 @@ def rationalize(parts, coords, states): seg["ic"][str(E)] = None if free else spy.Integer(1) for a, E in rates.items(): ex = _str(spy.exp(a * TIME)) - rewrites.append({"rewrite": "time", "from": ex, "to": str(E), - "why": f"{E}' = {_str(a * E)}, {E}(0) = 1 has the unique solution {ex}"}) + rewrites.append( + { + "rewrite": "time", + "from": ex, + "to": str(E), + "why": f"{E}' = {_str(a * E)}, {E}(0) = 1 has the unique solution {ex}", + } + ) # a free power of a state at 0 through the normalized power (x/c_x)^alpha is a state of the part from .startpow import normalize + normalize(parts, cs, states) for d, k in _strings(parts): bad = _blocking(d[k]) if bad is not None: - raise NotRationalError(f"discrete() needs a model rational in the states and coordinates; {_str(bad)} " - "is not") + raise NotRationalError( + f"discrete() needs a model rational in the states and coordinates; {_str(bad)} is not" + ) # an entry the rewrites leave keeps the text it had o = orig.get((id(d), k)) d[k] = o if o is not None and d[k] == model_sympify(o) else _str(d[k]) @@ -312,7 +367,7 @@ def map_to_given(sig, logs): pos = {x: spy.Symbol(str(x), real=True) for x in img.free_symbols} img = spy.expand_log(spy.log(img.xreplace(pos)), force=True) * L / spy.log(b) if len(logs[str(s)]) > 2: - img = L ** 2 / img + img = L**2 / img img = spy.expand(spy.simplify(img)).xreplace({v: k for k, v in pos.items()}) out[s] = img return out @@ -325,8 +380,9 @@ def relation_to_given(r, logs): op = "<" if "<" in r else ">" lhs, rhs = r.split(op, 1) if lhs.strip() in logs and len(logs[lhs.strip()]) == 2: - return f"{lhs.strip()} {op} " + _str(map_to_given({spy.Symbol(lhs.strip()): model_sympify(rhs)}, - logs)[spy.Symbol(lhs.strip())]) + return f"{lhs.strip()} {op} " + _str( + map_to_given({spy.Symbol(lhs.strip()): model_sympify(rhs)}, logs)[spy.Symbol(lhs.strip())] + ) return f"{_str(to_given(model_sympify(lhs), logs))} {op} {_str(to_given(model_sympify(rhs), logs))}" e = model_sympify(r) terms = spy.Add.make_args(spy.expand(e)) diff --git a/src/symident/detection/relax.py b/src/symident/detection/relax.py index b2829a2..c46e22b 100644 --- a/src/symident/detection/relax.py +++ b/src/symident/detection/relax.py @@ -65,7 +65,7 @@ def _same_leaf(leaves, value): if isinstance(v, spy.exp) and isinstance(value, spy.exp): k = spy.cancel(value.args[0] / v.args[0]) if k.is_Integer: - return W ** k + return W**k elif v == value: return W return None @@ -82,10 +82,13 @@ def _log_states(f, g, pos): R = spy.cancel(e / x).replace(lambda a: isinstance(a, spy.log) and a.args[0] == x, lambda a: L) if R.has(x): continue - rest = [v.replace(lambda a: isinstance(a, spy.log) and a.args[0] == x, lambda a: L) - for z, v in f.items() if z != x] + \ - [v.replace(lambda a: isinstance(a, spy.log) and a.args[0] == x, lambda a: L) - for v in g.values() if not (v.is_Pow and v.base == x and v.exp.is_Integer) and v != x] + rest = [ + v.replace(lambda a: isinstance(a, spy.log) and a.args[0] == x, lambda a: L) for z, v in f.items() if z != x + ] + [ + v.replace(lambda a: isinstance(a, spy.log) and a.args[0] == x, lambda a: L) + for v in g.values() + if not (v.is_Pow and v.base == x and v.exp.is_Integer) and v != x + ] if any(v.has(x) for v in rest): continue out[x] = R @@ -115,8 +118,7 @@ def _start_power(x, al, B, f, g, tr, starts, states, ins, leaves, rewrites, take if c.free_symbols & jsyms: raise ValueError(f"the leading coefficient {_str(c)} of {x} reads a known input") if positive is None or not is_positive(c, positive): - raise ValueError(f"the leading coefficient {_str(c)} of {x}, which starts at 0, is not positive on the " - "domain") + raise ValueError(f"the leading coefficient {_str(c)} of {x}, which starts at 0, is not positive on the domain") Zs, Nn, lam = spy.Dummy("Z"), spy.Dummy("N"), spy.Dummy("lam", positive=True) def power_of(lf): @@ -126,13 +128,17 @@ def power_of(lf): return None q = spy.cancel(v.exp / al) return (v.base, int(q)) if q.is_Integer and q != 0 else None + sub = {B: Zs * Nn} for lf in leaves: bq = power_of(lf) if bq is not None and (spy.cancel(bq[0] - c) == 0 or spy.cancel(bq[0] * c - 1) == 0): sub[spy.Symbol(lf["name"])] = Zs ** (bq[1] if spy.cancel(bq[0] - c) == 0 else -bq[1]) - exprs = {**{("f", s): v for s, v in f.items()}, **{("g", y): v for y, v in g.items()}, - **{("t", s): v for s, v in tr.items() if s in states}} + exprs = { + **{("f", s): v for s, v in f.items()}, + **{("g", y): v for y, v in g.items()}, + **{("t", s): v for s, v in tr.items() if s in states}, + } vals = {k_: v.xreplace(sub) for k_, v in exprs.items()} # Z cancels in an expression where the cancelled form is free of it @@ -154,7 +160,7 @@ def power_of(lf): W = str(_fresh("si_W", taken)) leaves.append({"name": W, "kind": "power", "value": spy.Pow(c, al), "state": None}) vals = {k_: v.xreplace({Zs: spy.Symbol(W)}) for k_, v in vals.items()} - N = x ** al * spy.Pow(c, -al) + N = x**al * spy.Pow(c, -al) vals = {k_: v.xreplace({Nn: N}) for k_, v in vals.items()} # leaves that are powers of c_x or have the value 1 are gone gone = {P for P in sub if P != B} @@ -166,10 +172,20 @@ def power_of(lf): f = {s: vals[("f", s)] for s in f} g = {y: vals[("g", y)] for y in g} tr = {s: vals.get(("t", s), v) for s, v in tr.items()} - if moved or any(lf["kind"] == "power" and lf.get("state") is None and lf["value"] == spy.Pow(c, al) - for lf in leaves): - rewrites.append({"from": _str(x ** al), "to": _str(N), "state": None, "rate": None, "start": "0", - "order": k, "leading": _str(c)}) + if moved or any( + lf["kind"] == "power" and lf.get("state") is None and lf["value"] == spy.Pow(c, al) for lf in leaves + ): + rewrites.append( + { + "from": _str(x**al), + "to": _str(N), + "state": None, + "rate": None, + "start": "0", + "order": k, + "leading": _str(c), + } + ) return f, g, tr @@ -212,17 +228,28 @@ def relax(odes, observables, trafo, coords, inputs=(), positive=True): for x, L in Ls.items(): P = _fresh("si_P", taken) leaves.append({"name": str(P), "kind": "constant", "value": spy.log(starts[x].xreplace(params))}) - rewrites.append({"from": _str(x), "to": f"exp({L})", "state": str(L), "rate": _str(logx[x].xreplace( - {d: Ls[x] for d in logx[x].atoms(spy.Dummy)})), "start": str(P)}) + rewrites.append( + { + "from": _str(x), + "to": f"exp({L})", + "state": str(L), + "rate": _str(logx[x].xreplace({d: Ls[x] for d in logx[x].atoms(spy.Dummy)})), + "start": str(P), + } + ) tr[L] = starts[L] = P tr.pop(x, None) starts.pop(x) - f = {Ls.get(x, x): (logx[x].xreplace({d: Ls[x] for d in logx[x].atoms(spy.Dummy)}) if x in logx else v) - for x, v in f.items()} + f = { + Ls.get(x, x): (logx[x].xreplace({d: Ls[x] for d in logx[x].atoms(spy.Dummy)}) if x in logx else v) + for x, v in f.items() + } f = {x: v.xreplace(to_L) for x, v in f.items()} # an observable x^k is k*log(x), injective on the positive reals - g = {y: (v.exp * Ls[v.base] if v.is_Pow and v.base in Ls else Ls[v] if v in Ls else v.xreplace(to_L)) - for y, v in g.items()} + g = { + y: (v.exp * Ls[v.base] if v.is_Pow and v.base in Ls else Ls[v] if v in Ls else v.xreplace(to_L)) + for y, v in g.items() + } states = set(f) while True: exprs = list(f.values()) + list(g.values()) @@ -247,8 +274,10 @@ def relax(odes, observables, trafo, coords, inputs=(), positive=True): g = {y: v.xreplace({a: new}) for y, v in g.items()} continue if a.is_Pow and a.exp.is_Rational: - raise ValueError(f"a root or rational power, {_str(a)}, has an algebraic start: the relaxation needs a " - "transcendental term") + raise ValueError( + f"a root or rational power, {_str(a)}, has an algebraic start: the relaxation needs a " + "transcendental term" + ) reads = a.free_symbols for u in sorted(reads & ins, key=str): # a known input u inside a term is a state with a known start and the known input du as rate @@ -293,8 +322,9 @@ def relax(odes, observables, trafo, coords, inputs=(), positive=True): new = new.xreplace({W: same}) else: leaves.append({"name": str(W), "kind": kind, "value": w0, "state": str(nu)}) - rewrites.append({"from": _str(a), "to": _str(new), "state": str(nu), "rate": _str(f[nu]), - "start": _str(tr[nu])}) + rewrites.append( + {"from": _str(a), "to": _str(new), "state": str(nu), "rate": _str(f[nu]), "start": _str(tr[nu])} + ) f = {x: v.xreplace({a: new}) for x, v in f.items()} g = {y: v.xreplace({a: new}) for y, v in g.items()} for (x, al), B in zpow.items(): @@ -331,29 +361,44 @@ def relax(odes, observables, trafo, coords, inputs=(), positive=True): if c in used: continue cs = spy.Symbol(c) - hit = [lf for lf in leaves if lf["kind"] != "log" and cs in lf["value"].free_symbols - and lf["name"] not in dropped.values() and _monotone_in(lf["value"], cs)] + hit = [ + lf + for lf in leaves + if lf["kind"] != "log" + and cs in lf["value"].free_symbols + and lf["name"] not in dropped.values() + and _monotone_in(lf["value"], cs) + ] if not hit: - raise ValueError(f"{c} enters only through non-rational terms of the coordinates that do not determine " - "it") + raise ValueError(f"{c} enters only through non-rational terms of the coordinates that do not determine it") dropped[c] = hit[0]["name"] for lf in leaves: lf["absorbs"] = next((c for c, P in dropped.items() if P == lf["name"]), None) if zpow and not leaves and not rewrites: - raise ValueError("the free powers of states at 0 enter as (x/c_x)^alpha, which the count takes without " - "relaxation") + raise ValueError( + "the free powers of states at 0 enter as (x/c_x)^alpha, which the count takes without relaxation" + ) pos = None if positive is not None: dec = set(coords) if positive is True else {str(p) for p in positive} # a logarithm of the coordinates is signed - pos = sorted((dec - set(dropped)) | {lf["name"] for lf in leaves if lf["kind"] != "log" - and not isinstance(lf["value"], spy.log)} - | {str(x) for x in f if str(x).startswith("si_nu") and tr.get(x) == 1}) + pos = sorted( + (dec - set(dropped)) + | {lf["name"] for lf in leaves if lf["kind"] != "log" and not isinstance(lf["value"], spy.log)} + | {str(x) for x in f if str(x).startswith("si_nu") and tr.get(x) == 1} + ) pos = [p for p in pos if p in used or p in {str(x) for x in f}] - return {"odes": {str(x): _str(v) for x, v in f.items()}, "observables": {y: _str(v) for y, v in g.items()}, - "trafo": {str(k): _str(v) for k, v in tr.items()}, "leaves": leaves, "dropped": dropped, - "positive": pos, "rewrites": rewrites, "inputs": [u for u in inputs if spy.Symbol(u) in ins] + new_inputs, - "known": known} + return { + "odes": {str(x): _str(v) for x, v in f.items()}, + "observables": {y: _str(v) for y, v in g.items()}, + "trafo": {str(k): _str(v) for k, v in tr.items()}, + "leaves": leaves, + "dropped": dropped, + "positive": pos, + "rewrites": rewrites, + "inputs": [u for u in inputs if spy.Symbol(u) in ins] + new_inputs, + "known": known, + } def scalings_keep_leaves(symmetries, leaves, dropped): @@ -361,12 +406,14 @@ def scalings_keep_leaves(symmetries, leaves, dropped): connected set, else the reason: every direction that moves a leaf W is exact, a scaling or a constant shift of the leaves it moves, and moves no coordinate the starts read, the weights or shifts on these leaves form an invertible matrix, and no direction moves a coordinate read by the start of a leaf that none of them moves.""" + def reads(lfs): out = set() for lf in lfs: out |= {str(s) for s in lf["value"].free_symbols} # a coordinate replaced by a constant term P is a coordinate of the relaxed model return out - set(dropped) + names = {lf["name"] for lf in leaves if lf["absorbs"] is None} every = reads(leaves) rows, moved = [], set() @@ -388,8 +435,10 @@ def reads(lfs): return f"a direction moves {', '.join(sorted(sup & every))}, read by the starts of the new states" moved |= sup & names cols = sorted(moved) - if rows and (len(rows) != len(cols) or - spy.Matrix([[model_sympify(str(w.get(n, 0))) for n in cols] for w in rows]).rank() < len(cols)): + if rows and ( + len(rows) != len(cols) + or spy.Matrix([[model_sympify(str(w.get(n, 0))) for n in cols] for w in rows]).rank() < len(cols) + ): return "the weights or shifts on the new coordinates they move are no invertible matrix" still = reads([lf for lf in leaves if lf["absorbs"] is None and lf["name"] not in moved]) for s in symmetries: @@ -449,8 +498,18 @@ def d(u, c): for b, L in lam.items(): out += spy.diff(u, L) * spy.diff(b, c) / b return out - pt = {c: spy.Rational(rng.randint(2, 10 ** 6), rng.randint(2, 10 ** 6)) for c in cs} - pt.update({L: spy.Rational(rng.randint(2, 10 ** 6), rng.randint(2, 10 ** 6)) for L in lam.values()}) - J = spy.Matrix([[d(u, c).xreplace(pt) if not isinstance(u, spy.log) else (spy.diff(u.args[0], c) / - u.args[0]).xreplace(pt) for c in cs] for u in rows]) + + pt = {c: spy.Rational(rng.randint(2, 10**6), rng.randint(2, 10**6)) for c in cs} + pt.update({L: spy.Rational(rng.randint(2, 10**6), rng.randint(2, 10**6)) for L in lam.values()}) + J = spy.Matrix( + [ + [ + d(u, c).xreplace(pt) + if not isinstance(u, spy.log) + else (spy.diff(u.args[0], c) / u.args[0]).xreplace(pt) + for c in cs + ] + for u in rows + ] + ) return J.rank() == len(rows) diff --git a/src/symident/detection/relevance.py b/src/symident/detection/relevance.py index 88a5587..f2c2b05 100644 --- a/src/symident/detection/relevance.py +++ b/src/symident/detection/relevance.py @@ -20,6 +20,7 @@ def direction_relevance(f, ref, pivots, z_slots, n_leaves, point0, rel_probe, re def nv(rp, p, zvals=zvals0): return null_residues(rp, f, p) if residue_fn is None else residue_fn(rp, p, zvals) + optimistic = _optimistic(residue_fn) base_nv = nv(ref, P) if base_nv is None: @@ -44,17 +45,21 @@ def nv(rp, p, zvals=zvals0): for i, c in enumerate(support_cols): if nvp[c] != base_nv[c]: rel_by_entry[i].append(li) - return {"base_nv": base_nv, "support_cols": support_cols, "relevant": relevant, - "rel_by_entry": rel_by_entry} + return {"base_nv": base_nv, "support_cols": support_cols, "relevant": relevant, "rel_by_entry": rel_by_entry} def dense_need(rel_by_entry, ctrl, degrees=None): """Sample count the dense interpolation needs, and whether any entry is dense.""" + def is_dense(r): return 1 <= len(r) <= ctrl["relevance_cap"] + degs = degrees or [None] * len(rel_by_entry) - needs = [2 * math.comb(len(r) + (ctrl["degree_cap"] if d is None else d), len(r)) - 1 + ctrl["sample_slack"] - for r, d in zip(rel_by_entry, degs) if is_dense(r)] + needs = [ + 2 * math.comb(len(r) + (ctrl["degree_cap"] if d is None else d), len(r)) - 1 + ctrl["sample_slack"] + for r, d in zip(rel_by_entry, degs) + if is_dense(r) + ] return {"max_need": int(max(needs, default=0)), "any_dense": bool(needs)} @@ -106,9 +111,10 @@ def build_shared_bank(union, need_pts, point0, pool, pool_next, kbatch, pivots, points.append(cand[ci]) rps.append(rpc) if bd: - print(f"[bankdiag] union={nu} need_pts={need_pts} tries={tries} good={n_good} " - f"solve_fail={n_solve_fail} piv_mismatch={n_piv_mismatch}") + print( + f"[bankdiag] union={nu} need_pts={need_pts} tries={tries} good={n_good} " + f"solve_fail={n_solve_fail} piv_mismatch={n_piv_mismatch}" + ) if len(points) < need_pts: return {"ok": False, "pool_next": pool_next} - return {"ok": True, "U": U, "points": points, "rps": rps, "union": list(union), - "pool_next": pool_next} + return {"ok": True, "U": U, "points": points, "rps": rps, "union": list(union), "pool_next": pool_next} diff --git a/src/symident/detection/restchart.py b/src/symident/detection/restchart.py index 5625414..7b894be 100644 --- a/src/symident/detection/restchart.py +++ b/src/symident/detection/restchart.py @@ -16,7 +16,7 @@ def _atoms(e): def _nonzero_at(e, syms, rng): """Whether e is nonzero at a random rational point: then e is not the zero function.""" - pt = {s: spy.Rational(rng.randint(2, 10 ** 4), rng.randint(2, 10 ** 4)) for s in syms} + pt = {s: spy.Rational(rng.randint(2, 10**4), rng.randint(2, 10**4)) for s in syms} try: v = spy.cancel(e.xreplace(pt)) except ZeroDivisionError: @@ -94,6 +94,7 @@ def flat(e): d = dummies.setdefault(a, spy.Dummy("w")) e = e.xreplace({a: d}) return e + bal = {x: flat(spy.together(rhs[x])) for x in U} if any(_atoms(e) for e in bal.values()): raise ValueError("a transcendental term at rest is nested") @@ -107,12 +108,18 @@ def flat(e): inside = {s for a in dummies for s in a.free_symbols} def candidates(e): - return [p for p in sorted(e.free_symbols & cs, key=str) - if p not in inside and str(p) not in fixed and spy.Poly(e, p).degree() == 1] + return [ + p + for p in sorted(e.free_symbols & cs, key=str) + if p not in inside and str(p) not in fixed and spy.Poly(e, p).degree() == 1 + ] + nb = {p: sum(p in e.free_symbols for e in hb) for p in cs} exch = None - for key in (lambda p: (pos is None or str(p) in pos, nb[p], str(p)), - lambda p: (nb[p], pos is None or str(p) in pos, str(p))): + for key in ( + lambda p: (pos is None or str(p) in pos, nb[p], str(p)), + lambda p: (nb[p], pos is None or str(p) in pos, str(p)), + ): pick = [] for e in sorted(hb, key=lambda e: len(candidates(e))): c = [p for p in sorted(candidates(e), key=key) if p not in pick] @@ -124,14 +131,17 @@ def candidates(e): if exch is not None: break if exch is None: - raise ValueError("no coordinates enter the balances of " + ", ".join(map(str, H)) + " linearly with an " - "invertible coefficient matrix") + raise ValueError( + "no coordinates enter the balances of " + ", ".join(map(str, H)) + " linearly with an " + "invertible coefficient matrix" + ) back = {d: a.xreplace(held) for a, d in dummies.items()} exch = {p: v.xreplace(back) for p, v in exch.items()} sol = {x: v.xreplace(exch).xreplace(back) for x, v in sol.items()} def sub(e): return model_sympify(str(e)).xreplace(exch) + trafo = {str(x): _str(v) for x, v in {**start, **R, **sol}.items()} trafo = {k: _str(sub(v)) for k, v in trafo.items()} new_pos = positive @@ -142,8 +152,13 @@ def sub(e): if spy.Symbol(ev["var"]) in inside or spy.Symbol(ev["var"]) in H: raise ValueError(f"an event changes {ev['var']}, read by a transcendental term") evs.append({**ev, "value": _str(sub(ev["value"]))}) - return {"odes": {str(x): _str(sub(v)) for x, v in f.items()}, - "observables": {y: _str(sub(v)) for y, v in g.items()}, "trafo": trafo, "events": evs, - "exchanged": {str(p): _str(v) for p, v in exch.items()}, "rest": {str(x): str(r) for x, r in R.items()}, - "positive": new_pos, - "coordinates": [c for c in coords if spy.Symbol(c) not in exch] + [str(R[x]) for x in H]} + return { + "odes": {str(x): _str(sub(v)) for x, v in f.items()}, + "observables": {y: _str(sub(v)) for y, v in g.items()}, + "trafo": trafo, + "events": evs, + "exchanged": {str(p): _str(v) for p, v in exch.items()}, + "rest": {str(x): str(r) for x, r in R.items()}, + "positive": new_pos, + "coordinates": [c for c in coords if spy.Symbol(c) not in exch] + [str(R[x]) for x in H], + } diff --git a/src/symident/detection/series.py b/src/symident/detection/series.py index cd22c20..c57c6af 100644 --- a/src/symident/detection/series.py +++ b/src/symident/detection/series.py @@ -12,6 +12,7 @@ def series_null(S, nz, N, p): def Mk(k): return S[:, np.arange(nz) * N + k] + M0 = Mk(0) rr = _core.sym_rref_mod(M0.astype(np.float64), p) piv = [int(x) for x in np.atleast_1d(rr["piv"])] @@ -73,6 +74,7 @@ def conv(i): if i - j >= 0: acc = (acc + q[j] * s[i - j]) % p return acc + P = [conv(i) for i in range(dn + 1)] for i in range(dn + 1, N): if conv(i) != 0: @@ -82,11 +84,13 @@ def conv(i): def pade_at(pq, t, p): """The Pade approximant `pq` at `t` mod `p`, or None at a pole.""" + def ev(cf): acc = 0 for c in reversed(cf): acc = (acc * t + c) % p return acc + qv = ev(pq["Q"]) if qv == 0: return None diff --git a/src/symident/detection/sparse.py b/src/symident/detection/sparse.py index 310d937..05a0b94 100644 --- a/src/symident/detection/sparse.py +++ b/src/symident/detection/sparse.py @@ -32,6 +32,7 @@ def bot_reconcile(per_prime): def key(m): return [",".join(str(int(x)) for x in row) for row in np.asarray(m).reshape(len(m), -1)] + k1 = key(per_prime[0]["exps"]) t = len(k1) coef = np.zeros((t, np_), dtype=np.int64) @@ -45,8 +46,7 @@ def key(m): rec = rat_recon(coef, list(PRIMES[:np_])) if any(d == "0" for d in rec["den"]): return None - return {"exps": np.asarray(per_prime[0]["exps"], dtype=np.int64), "num": rec["num"], - "den": rec["den"]} + return {"exps": np.asarray(per_prime[0]["exps"], dtype=np.int64), "num": rec["num"], "den": rec["den"]} def laurent_assemble(per_prime, reli, leaf_names, nvar): @@ -65,11 +65,24 @@ def laurent_assemble(per_prime, reli, leaf_names, nvar): def _default_kbatch(kcall): def kb(pl, pv, Nt): return [kcall(pp, pr, Nt) for pp, pr in zip(pl, pv)] + return kb -def sparse_entry(reli, support_col, f, point0, leaf_names, nt_used, kcall, pivots, residue_fn=None, - ctrl=None, z_slots=None, kbatch=None): +def sparse_entry( + reli, + support_col, + f, + point0, + leaf_names, + nt_used, + kcall, + pivots, + residue_fn=None, + ctrl=None, + z_slots=None, + kbatch=None, +): """One wide entry by sparse Laurent interpolation; None if not a bounded Laurent polynomial.""" if kbatch is None: kbatch = _default_kbatch(kcall) @@ -132,8 +145,20 @@ def sparse_entry(reli, support_col, f, point0, leaf_names, nt_used, kcall, pivot return None -def general_rational_entry(reli, support_col, f, point0, leaf_names, nt_used, kcall, pivots, - residue_fn=None, ctrl=None, z_slots=None, kbatch=None): +def general_rational_entry( + reli, + support_col, + f, + point0, + leaf_names, + nt_used, + kcall, + pivots, + residue_fn=None, + ctrl=None, + z_slots=None, + kbatch=None, +): """One wide entry with a general denominator by Cauchy fits along rays and Ben-Or/Tiwari.""" if kbatch is None: kbatch = _default_kbatch(kcall) @@ -168,17 +193,18 @@ def ray_samples(u_list, p_vec, nt): rv.append((s + tj * v) % p_vec[i]) pv.append(p_vec[i]) out = sample_many(rv, pv) - return [out[i * (nt + 1):(i + 1) * (nt + 1)] for i in range(len(u_list))] + return [out[i * (nt + 1) : (i + 1) * (nt + 1)] for i in range(len(u_list))] def from_ray(rv, p, d_n, d_d): tn = list(range(d_n + d_d + 5)) - rv = rv[:len(tn)] + rv = rv[: len(tn)] if any(x is None for x in rv): return None res = _core.sym_cauchy_eval(tn, rv, d_n, d_d, p) if res.get("status") != "ok": return None return (int(res["N"]), int(res["D"])) + P1 = PRIMES[0] u0 = [(b * b + 3) % P1 for b in bases] deg = None @@ -240,6 +266,7 @@ def fit_poly(seq_list, cand_m): return None per_prime.append(r) return bot_reconcile(per_prime) + Nrc = fit_poly(Nseq, cand_n) if Nrc is None: return None diff --git a/src/symident/detection/startpow.py b/src/symident/detection/startpow.py index e04feb7..6b1be25 100644 --- a/src/symident/detection/startpow.py +++ b/src/symident/detection/startpow.py @@ -45,6 +45,7 @@ def start_powers(exprs, zero_states, cs): def substitute(e, x, alpha, N, Z=1): """`e` with each x^(c0 + c*alpha) as x^c0 * (Z*N)^c.""" + def repl(pw): if pw.base != x: return pw @@ -52,6 +53,7 @@ def repl(pw): if pe is None or pe[2] != alpha: return pw return x ** pe[0] * (Z * N) ** pe[1] + return spy.sympify(e).replace(lambda a: a.is_Pow and a.base == x, repl) @@ -60,16 +62,23 @@ def leading(f, ic, x, alpha): c, a rational function of the other symbols, in the model where every power of x with the exponent alpha is 0; a ValueError where k passes the cap. `f` and `ic` map state names to expressions; the start of x is 0.""" from .discrete import Series + N = spy.Dummy("N") f0 = {s: substitute(spy.sympify(v), x, alpha, N).xreplace({N: 0}) for s, v in f.items()} - syms = sorted({s for v in list(f0.values()) + [spy.sympify(v) for v in ic.values()] for s in v.free_symbols} - - {spy.Symbol(s) for s in f}, key=str) - part = {"segments": [{"f": {s: str(v) for s, v in f0.items()}, "g": {}, "t": "0", - "ic": {s: str(v) for s, v in ic.items()}}]} + syms = sorted( + {s for v in list(f0.values()) + [spy.sympify(v) for v in ic.values()] for s in v.free_symbols} + - {spy.Symbol(s) for s in f}, + key=str, + ) + part = { + "segments": [ + {"f": {s: str(v) for s, v in f0.items()}, "g": {}, "t": "0", "ic": {s: str(v) for s, v in ic.items()}} + ] + } ser = Series([part], [str(s) for s in syms]) ib = [str(s) for s in ser.parts[0]["st"]].index(str(x)) rng = random.Random("leading coefficient") - pt = [Fraction(rng.randint(2, 10 ** 6), rng.randint(2, 10 ** 6)) for _ in syms] + pt = [Fraction(rng.randint(2, 10**6), rng.randint(2, 10**6)) for _ in syms] if ser._outputs(pt, _ORDER_CAP, 0, Fraction(1), Fraction(0)) is None: raise ValueError(f"the model has a pole at the start of {x}") k = next((n for n, v in enumerate(ser.states0[ib]) if v != 0), None) @@ -96,8 +105,14 @@ def normalize(parts, cs, states): """`parts` (sympy entries, as in rationalize) with each free power of a state that starts at 0 written through the normalized power N = (x/c_x)^alpha, a state of the part named in part["spow"]; a power that does not enter as c_x^(-alpha) x^alpha with the leading coefficient c_x of x is left in place.""" - taken = {str(s) for part in parts for seg in part["segments"] for d in ("f", "g") for v in seg[d].values() - for s in spy.sympify(v).free_symbols} | {str(s) for s in states} + taken = { + str(s) + for part in parts + for seg in part["segments"] + for d in ("f", "g") + for v in seg[d].values() + for s in spy.sympify(v).free_symbols + } | {str(s) for s in states} for part in parts: segs = part["segments"] seg = segs[0] @@ -123,11 +138,13 @@ def repl(pw): if not q.is_Integer: return pw if spy.cancel(pw.base - c) == 0: - return Z ** q + return Z**q if spy.cancel(pw.base * c - 1) == 0: return Z ** (-q) return pw + return e.replace(lambda a: a.is_Pow and a.exp.has(alpha) and not a.base.free_symbols & {x}, repl) + new = {} for d in ("f", "g"): for key, v in seg[d].items(): @@ -214,6 +231,7 @@ def layered_flow(F, xs, params, order, o, z, skip, sp, alpha): D(x) x' = N(x) with x' of index n and layer m lambda_{n+1,m} times the term of index n + 1, and N = S Q with n c Q_n = sum_j (alpha j + j - n) x_{k+j} Q_{n-j}; False at a pole.""" from .discrete import _Eps, _lead, _ser_poly + one, zero = o.c[0], z.c[0] L, k, iN, ib = len(o.c), sp["k"], sp["N"], sp["base"] dx = {i: [] for i in range(len(F)) if i not in skip and i != iN} @@ -245,8 +263,7 @@ def layered_flow(F, xs, params, order, o, z, skip, sp, alpha): d = (nser[n] - rest) / dser[0] dx[i].append(d) # a term of layer m has index at least k*m - xs[i][n + 1] = _Eps([d.c[m] / lam(n + 1, m, k, alpha, one) if n + 1 >= k * m else zero - for m in range(L)]) + xs[i][n + 1] = _Eps([d.c[m] / lam(n + 1, m, k, alpha, one) if n + 1 >= k * m else zero for m in range(L)]) return True @@ -255,6 +272,7 @@ def layered_equations(F, xs, params, need, o, z, skip, sp, alpha, Q, add_eq, add D(x) x' = N(x) per index and layer, and n c Q_n = sum_j (alpha j + j - n) x_{k+j} Q_{n-j}, with c the leading coefficient of the base saturated.""" from .discrete import _Eps, _ser_poly + one = o.c[0] L, k, iN, ib = len(o.c), sp["k"], sp["N"], sp["base"] c = xs[ib][k].c[0] @@ -282,6 +300,7 @@ def proof(series, pi, positive): the leading coefficient c_x and the lowest coefficient of layer 1 of one observable have one sign on the domain; else they are named as premises.""" from .discrete import _Eps, _eval, _ser_poly + part = series.parts[pi] sp = part["spow"] seg = part["segs"][0] @@ -320,15 +339,17 @@ def proof(series, pi, positive): y.append((mser[n] - sum((eser[l_] * y[n - l_] for l_ in range(1, n + 1)), z)) / eser[0]) d = y[n1].c[1] cx, dx = spy.sympify(c.as_expr()), spy.sympify(d.as_expr()) - out.update({"leading": str(cx), "observable": series.labels[_row(series, pi, r)], "index": n1, - "coefficient": str(dx)}) + out.update( + {"leading": str(cx), "observable": series.labels[_row(series, pi, r)], "index": n1, "coefficient": str(dx)} + ) if d == 0: raise ValueError(f"the lowest coefficient of layer 1 of {out['observable']} vanishes") if not definite(cx, positive): premises.append(f"the leading coefficient {cx} of {sp['state']} is not zero on the domain") if not definite(dx, positive): - premises.append(f"the coefficient {dx} of t^({n1 - k} + {k}*{sp['alpha']}) in {out['observable']} is not " - "zero on the domain") + premises.append( + f"the coefficient {dx} of t^({n1 - k} + {k}*{sp['alpha']}) in {out['observable']} is not zero on the domain" + ) return out diff --git a/src/symident/detection/uinputs.py b/src/symident/detection/uinputs.py index c90508b..c7bead9 100644 --- a/src/symident/detection/uinputs.py +++ b/src/symident/detection/uinputs.py @@ -15,6 +15,7 @@ def unknown_chain(f, g, ic, unknown, length, unsupported, what): """(f, ic, jets): the right-hand sides with each unknown input a chain of `length` jet states, their starts free (None), and per jet name the input and the order; ValueError for a setting the count does not handle.""" from .core import _input_jets + if unsupported: raise ValueError(f"{what} handles unknown inputs in one condition without events, switches and equilibrate") taken = set(get_symbols(list(f.values()) + list(g.values()))) | set(f) @@ -101,6 +102,7 @@ def isolated(fib, p): the input jets they read of full column rank at a random point modulo p, and the number of those jets. Then the points of the fiber are isolated in the coordinates and these jets (Step 1 of the verified count).""" from .discrete import _Dual + series = fib.series zero = unread_jets(series, fib.orders) free = [key for key in series.inputs if key not in zero] @@ -110,8 +112,9 @@ def isolated(fib, p): cv = [_Dual(rng.randint(2, p - 1), [int(i == j) for j in range(m)], p) for i in range(n)] old = series.input_values series.input_values = {key: _Dual(0, [0] * m, p) for key in zero} - series.input_values.update({key: _Dual(rng.randint(2, p - 1), [int(n + k == j) for j in range(m)], p) - for k, key in enumerate(free)}) + series.input_values.update( + {key: _Dual(rng.randint(2, p - 1), [int(n + k == j) for j in range(m)], p) for k, key in enumerate(free)} + ) try: ys = series._outputs(cv, fib.order, 0, _Dual(1, [0] * m, p), _Dual(0, [0] * m, p)) except ZeroDivisionError: @@ -129,6 +132,7 @@ def _degrees(fib): jets of the inputs as coordinates of the point.""" from ..sym.degrees import Atoms, Deg, common from .discrete import _sparse, _sparse_deg + A = Atoms() series = fib.series old = series.input_values @@ -163,11 +167,14 @@ def count_certificate(fib, k, out): the coordinates, the points isolated in the coordinates and the jets that the output reads, and the Bezout number of the whole system.""" from .discrete import _MIN_BITS, _VERIFIED_AIM, _VERIFIED_BITS, q_count + series = fib.series ok, nread = isolated(fib, PRIMES[0]) if not ok: - out["why"] = ("the output coefficients do not determine the coordinates and the jets of the unknown inputs " - "they read at a random point modulo a prime") + out["why"] = ( + "the output coefficients do not determine the coordinates and the jets of the unknown inputs " + "they read at a random point modulo a prime" + ) return out degs = _degrees(fib) if degs is None: @@ -183,10 +190,10 @@ def count_certificate(fib, k, out): return out out["bits"] = bits rng = session.current().rng("verified count", tuple(fib.coords)) - pt = {s: spy.Integer(rng.randint(1, 2 ** bits)) for s in fib.syms} + pt = {s: spy.Integer(rng.randint(1, 2**bits)) for s in fib.syms} old = series.input_values zero = unread_jets(series, fib.orders) - series.input_values = {key: spy.Integer(0 if key in zero else rng.randint(1, 2 ** bits)) for key in series.inputs} + series.input_values = {key: spy.Integer(0 if key in zero else rng.randint(1, 2**bits)) for key in series.inputs} try: k2 = q_count(fib, pt) finally: @@ -209,6 +216,7 @@ def preserved(fib, sig, points=2, deeper=0): the jets of the states and the inputs.""" from ..sym.modp import _modp_rational from .discrete import Fiber, _gb_count + p = PRIMES[0] rng = session.current().rng("input check", tuple(fib.coords)) deep = Fiber(fib.series, [n + deeper for n in fib.orders], fib.positive) @@ -234,6 +242,7 @@ def input_state_map(parts, sig, states): h(x, theta, w) where these are linear in psi; every identity holds over Q(x, theta, w), and phi maps the given initial values. (phi(x(t)), psi(t)) is then a solution at sigma(theta) with the output of the solution at theta.""" from ..errors import SYMPY_FAILS, sympy_fail + if len(parts) != 1 or len(parts[0]["segments"]) != 1: return None seg = parts[0]["segments"][0] @@ -249,8 +258,10 @@ def input_state_map(parts, sig, states): # an input that enters through a derivative return None th = {s: e for s, e in sig.items() if s not in set(X)} - phi = {x: sig.get(ic[x], ic[x]).xreplace({ic[y]: y for y in X if ic.get(y) == y}) if ic.get(x) == x else x - for x in X} + phi = { + x: sig.get(ic[x], ic[x]).xreplace({ic[y]: y for y in X if ic.get(y) == y}) if ic.get(x) == x else x + for x in X + } psi = [spy.Dummy(str(w)) for w in W] img = {**th, **phi, **dict(zip(W, psi))} eqs = [F[x].xreplace(img) - sum((spy.diff(phi[x], y) * F[y] for y in X), spy.Integer(0)) for x in X] @@ -265,8 +276,11 @@ def input_state_map(parts, sig, states): if any(spy.cancel(e.xreplace(sub)) != 0 for e in eqs): return None for x in X: - if x in ic and ic[x] != x and spy.cancel(phi[x].xreplace({y: ic[y] for y in X if y in ic}) - - ic[x].xreplace(th)) != 0: + if ( + x in ic + and ic[x] != x + and spy.cancel(phi[x].xreplace({y: ic[y] for y in X if y in ic}) - ic[x].xreplace(th)) != 0 + ): return None except SYMPY_FAILS as exc: sympy_fail(exc) diff --git a/src/symident/detection/verify.py b/src/symident/detection/verify.py index ddfe632..d0266d2 100644 --- a/src/symident/detection/verify.py +++ b/src/symident/detection/verify.py @@ -42,8 +42,22 @@ def verify_direction(entry, f, znames, leaf_names, point0, nt_used, kcall, resid return False -def verify_in_nullspace(entry, f, znames, leaf_names, point0, nt_used, kcall, pool_next, nz, - dir_call=None, tries=6, need=2, cols=None, env_fn=None): +def verify_in_nullspace( + entry, + f, + znames, + leaf_names, + point0, + nt_used, + kcall, + pool_next, + nz, + dir_call=None, + tries=6, + need=2, + cols=None, + env_fn=None, +): """Gauge-independent check that a direction lies in the nullspace at `need` of `tries` fresh seeded points; `env_fn(point, q)` adds the values of names off the leaves, such as resting states.""" if entry.get("vector") is None: @@ -72,8 +86,11 @@ def verify_batch(entries, anchors, znames, leaf_names, n_point, nt_used, batch_f q = verify_prime() leaves = set(leaf_names) out = [None] * len(entries) - todo = [i for i, e in enumerate(entries) - if all(nm in znames and set(_IDENT.findall(str(ex))) <= leaves for nm, ex in e["vector"].items())] + todo = [ + i + for i, e in enumerate(entries) + if all(nm in znames and set(_IDENT.findall(str(ex))) <= leaves for nm, ex in e["vector"].items()) + ] passed = {i: 0 for i in todo} off = set() for k in range(tries): diff --git a/src/symident/detection/work.py b/src/symident/detection/work.py index 5765f89..671df7d 100644 --- a/src/symident/detection/work.py +++ b/src/symident/detection/work.py @@ -59,6 +59,7 @@ def msolve_memory(gib): old = MSOLVE_MEMORY if gib is None: from .. import state + gib = state.env_value("MSOLVE_GB") or None if gib is not None: MSOLVE_MEMORY = int(float(gib) * (1 << 30)) @@ -85,6 +86,7 @@ def apply(): resource.setrlimit(resource.RLIMIT_AS, (lim, lim)) except (OSError, ValueError): pass + return apply @@ -98,29 +100,29 @@ def run(cmd, input=None, text=False, memory=None): # the work caps of the global analysis; discrete() sets the public ones for one call (caps()) CAPS = { # nonzero entries of the matrices of the F4 rounds of one call of msolve, and the unknowns and terms of the input - "msolve_entries": 4 * 10 ** 8, + "msolve_entries": 4 * 10**8, "msolve_unknowns": 400, "msolve_terms": 100000, # the same for the short counts: the first count of discrete(), the size of a square subsystem, the check of a # resting state - "quick_entries": 6 * 10 ** 7, + "quick_entries": 6 * 10**7, "quick_unknowns": 400, "quick_terms": 100000, # entries of the matrices over GF(p) that the exact search reduces, and the verified functions past it - "search_entries": 5 * 10 ** 8, - "verified_entries": 2 * 10 ** 8, + "search_entries": 5 * 10**8, + "verified_entries": 2 * 10**8, # terms of a polynomial of the elimination of the states - "elimination_terms": 3 * 10 ** 6, + "elimination_terms": 3 * 10**6, # products of terms that the Taylor series of the outputs may take, (k + 1)^2 per order k and term - "series_products": 10 ** 10, + "series_products": 10**10, # permutations of coordinates tested as candidates "candidates": 20000, # points of the fiber that the reconstruction of the maps solves "map_points": 200, # products of terms in the Taylor series that the steps of the paths of the monodromy evaluate - "monodromy_products": 10 ** 9, + "monodromy_products": 10**9, # the terms of the expansion of the equations of a map of the states solved from the Lie derivatives of the outputs - "state_map_terms": 10 ** 5, + "state_map_terms": 10**5, # the Bezout number of the resting balances that SymPy is given, and the states of their largest coupled block "rest_bezout": 4, "rest_block": 8, @@ -165,8 +167,9 @@ def local_caps(**kw): def quick_msolve(): """The short caps of msolve (quick_entries, quick_unknowns, quick_terms) within the block, at most those in force.""" - with local_caps(**{k: min(cap(k), cap("quick" + k[6:])) for k in ("msolve_entries", "msolve_unknowns", - "msolve_terms")}): + with local_caps( + **{k: min(cap(k), cap("quick" + k[6:])) for k in ("msolve_entries", "msolve_unknowns", "msolve_terms")} + ): yield @@ -206,8 +209,9 @@ def run_msolve(cmd, text=True): out = [] total, buf, done = 0, b"", 0 # leaving the block closes both pipes and waits for the process - with subprocess.Popen(list(cmd) + ["-v", "2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, - preexec_fn=_limiter(MSOLVE_MEMORY)) as proc: + with subprocess.Popen( + list(cmd) + ["-v", "2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=_limiter(MSOLVE_MEMORY) + ) as proc: reader = threading.Thread(target=lambda: out.append(proc.stdout.read())) reader.start() try: diff --git a/src/symident/errors.py b/src/symident/errors.py index 2b154ee..56fca82 100644 --- a/src/symident/errors.py +++ b/src/symident/errors.py @@ -22,14 +22,23 @@ class InapplicableError(TypeError, ValueError): # failures of SymPy on a valid expression: no polynomial form, no solution method, a # value that is not a number, a pole, an expression too deep to traverse or to parse -SYMPY_FAILS = (BasePolynomialError, NotImplementedError, TypeError, ValueError, ArithmeticError, - RecursionError, SyntaxError, TokenError) +SYMPY_FAILS = ( + BasePolynomialError, + NotImplementedError, + TypeError, + ValueError, + ArithmeticError, + RecursionError, + SyntaxError, + TokenError, +) def swallow(exc, where): """Record `exc` from the route at `where` in info["errors"]; raise it on DEBUG, missing msolve or a prime rerun.""" from .gfp import NeedPrimesError from .sym.msolve import MsolveMissingError + if state.env("DEBUG") or isinstance(exc, (NeedPrimesError, MsolveMissingError)): raise exc session.note("errors", f"{where}: {type(exc).__name__}: {str(exc)[:200]}") @@ -45,8 +54,12 @@ def sympy_fail(exc): while tb is not None: in_sympy = in_sympy or "/sympy/" in tb.tb_frame.f_code.co_filename.replace("\\", "/") tb = tb.tb_next - if state.env("DEBUG") and isinstance(exc, (TypeError, ValueError)) and not isinstance(exc, InapplicableError) \ - and not in_sympy: + if ( + state.env("DEBUG") + and isinstance(exc, (TypeError, ValueError)) + and not isinstance(exc, InapplicableError) + and not in_sympy + ): raise exc s = state.get("session") if s is None or len(s.notes["errors"]) >= ERRORS_KEPT: diff --git a/src/symident/gfp.py b/src/symident/gfp.py index 8a01c95..29f6f0d 100644 --- a/src/symident/gfp.py +++ b/src/symident/gfp.py @@ -24,6 +24,7 @@ def verify_prime(): """The prime of the fresh-point checks: in a detection drawn from the seed of the detection among primes holding the roots.""" from . import state + s = state.get("session") if s is None: return _VERIFY[0] @@ -31,9 +32,10 @@ def verify_prime(): q = s.vprimes.get(key) if q is None: from sympy import prevprime + rng = s.rng("verification prime", key) while q is None: - c = int(prevprime(rng.randrange(2 ** 30 + 64, 1400000000))) + c = int(prevprime(rng.randrange(2**30 + 64, 1400000000))) if holds_roots(_ROOTS[0], c, _ROOTS[1]): q = c s.vprimes[key] = q @@ -53,6 +55,7 @@ def extra_primes(): def prime_run(n): """`n` primes: the engine primes, then lower primes holding the roots, without the verification prime.""" from sympy import prevprime + out, q = list(PRIMES), min(PRIMES) while len(out) < n: q = int(prevprime(q)) @@ -65,8 +68,10 @@ class NeedPrimesError(Exception): """Raised when an engine prime does not hold a root of the model; the analysis reruns under use_primes().""" def __init__(self, constants=(), degrees=()): - super().__init__("roots of degree %s and square roots of %s" % ( - ", ".join(map(str, degrees)) or "-", ", ".join(map(str, constants)) or "-")) + super().__init__( + "roots of degree %s and square roots of %s" + % (", ".join(map(str, degrees)) or "-", ", ".join(map(str, constants)) or "-") + ) self.constants = list(constants) self.degrees = list(degrees) @@ -90,6 +95,7 @@ def holds_roots(constants, q, degrees=()): def use_primes(constants=(), degrees=()): """Eight primes below the default ones that hold every root of the model: four engine, one check, three more.""" from sympy import Rational, prevprime + consts = [(Rational(c), int(k)) for c, k in constants] found, q = [], PRIMES[0] + 1 while len(found) < 8: @@ -116,9 +122,9 @@ def sieve(n): while True: is_p = np.ones(limit + 1, dtype=bool) is_p[:2] = False - for i in range(2, int(limit ** 0.5) + 1): + for i in range(2, int(limit**0.5) + 1): if is_p[i]: - is_p[i * i::i] = False + is_p[i * i :: i] = False pr = np.nonzero(is_p)[0] if len(pr) >= n: return [int(x) for x in pr[:n]] @@ -128,6 +134,7 @@ def sieve(n): def random_point(n, seed=1): """Residues below the smallest prime by the MINSTD generator, deterministic in seed and the session seed.""" from .session import current + m = 2147483647 x = current().seed("point", int(seed)) % m if x == 0: @@ -144,6 +151,7 @@ def random_point(n, seed=1): def uniform_point(n, q, seed=1): """Residues uniform on [0, q) by rejection from the MINSTD generator, deterministic in seed and the session seed.""" from .session import current + m = 2147483647 if not 1 < q < m: raise ValueError("uniform_point: the modulus is not between 2 and 2^31 - 2") @@ -198,7 +206,7 @@ def null_basis_rows(res, free_cols, p): R = np.asarray(res["R"], dtype=np.int64).reshape(-1, nz) piv = np.atleast_1d(np.asarray(res["pivots"], dtype=np.int64)) if len(piv): - out[:, piv] = ((p - R[:len(piv)][:, fc]) % p).T + out[:, piv] = ((p - R[: len(piv)][:, fc]) % p).T return out @@ -226,7 +234,7 @@ def _reduce(self, v): v = np.asarray(v, dtype=np.int64) % self.p if not self.k: return v - c = v[self.piv[:self.k]] + c = v[self.piv[: self.k]] nzr = np.nonzero(c)[0] if not len(nzr): return v @@ -246,7 +254,7 @@ def add(self, v): c = int(nzc[0]) v = v * invmod(int(v[c]), p) % p # the other rows lose their entry in the new pivot column - hit = np.nonzero(self.rows[:self.k, c])[0] + hit = np.nonzero(self.rows[: self.k, c])[0] if len(hit): f = self.rows[hit, c] self.rows[hit] = (self.rows[hit] - (f[:, None] * v[None, :]) % p) % p @@ -282,8 +290,7 @@ def rref_modp(M, p): M = np.asarray(M) nr, nc = M.shape if M.ndim == 2 else (0, 0) if nr == 0 or nc == 0: - return {"R": np.zeros((nr, nc), dtype=np.int64), "piv": np.zeros(0, dtype=np.int64), - "rank": 0} + return {"R": np.zeros((nr, nc), dtype=np.int64), "piv": np.zeros(0, dtype=np.int64), "rank": 0} rr = _core.sym_rref_mod(np.asarray(M, dtype=np.float64) % p, p) R = np.zeros((nr, nc), dtype=np.int64) rank = int(rr["rank"]) @@ -345,6 +352,7 @@ def red(R, p): if fac[i]: R[i] = (R[i] - mulmod(Sr["R"][j], fac[i], p)) % p return R + return red @@ -370,7 +378,9 @@ def fn(rp, p, zvals=None): for l in range(k): w = (w + mulmod(R[l], Binv[i, l], p)) % p return w + return fn + return {"anchors": [int(x) for x in dp], "residue_fns": [make(i) for i in range(k)]} @@ -383,6 +393,7 @@ def canon_gauge(residual_free, scal_rows, P, nz, sc): def resid(rp, p, zvals=None): return reduce_scal(np.stack([null_residues(rp, fc, p) for fc in residual_free]), p) + return gauge_from_rows(residual_free, resid, resid(sc["ref"], P), P, k, nz) @@ -411,12 +422,14 @@ def eta_rows(rp, p, zvals): continue R[:, c] = mulmod(R[:, c], invmod(zc, p), p) return reduce_scal(R, p) + return gauge_from_rows(residual_free, eta_rows, eta_rows(sc["ref"], P, zvals0), P, k, nz) def minsupport_gauge(residual_free, scal_rows, P, nz, sc, free_cols, cand_cap=20000): """Residual directions of minimal support as residue functions on their supports, outside the scalings.""" from .session import current + k = len(residual_free) raw = {"anchors": list(residual_free), "residue_fns": [None] * k} if k == 0: @@ -432,8 +445,8 @@ def left_null(B, keep, p): nr = B.shape[0] M = B[:, keep] rr = rref_modp(np.concatenate([M % p, np.eye(nr, dtype=np.int64)], axis=1), p) - z = np.nonzero(np.sum(rr["R"][:, :M.shape[1]] % p != 0, axis=1) == 0)[0] - return rr["R"][z, M.shape[1]:] % p + z = np.nonzero(np.sum(rr["R"][:, : M.shape[1]] % p != 0, axis=1) == 0)[0] + return rr["R"][z, M.shape[1] :] % p def comb(c, B, p): w = np.zeros(nz, dtype=np.int64) @@ -537,15 +550,22 @@ def fn(rp, p, zvals=None): continue eta[c] = int(mulmod(v[c], mulmod(za, invmod(zc, p), p), p)) return eta + fn.pinned_support = True return fn - return {"anchors": [fc["anchor"] for fc in found], "residue_fns": [make(fc) for fc in found], - "vectors": sel, "circuits": circuits} + + return { + "anchors": [fc["anchor"] for fc in found], + "residue_fns": [make(fc) for fc in found], + "vectors": sel, + "circuits": circuits, + } def sqrt_mod(a, p): """The smaller square root of a modulo the odd prime p, as the kernel takes it; None for a non-residue.""" from sympy.ntheory import sqrt_mod as _sqrt + r = _sqrt(int(a) % p, p) return None if r is None else min(r, p - r) @@ -596,6 +616,7 @@ def fn(point, p): return None v[s] = pow(v[a[i]], p - 2, p) return np.array([v[o] for o in out], dtype=np.int64) + return fn @@ -640,6 +661,7 @@ def gen(n, d): for s in gen(n - 1, d - e): out.append([e] + s) return out + rows = gen(nvar, degree) rows.sort(key=lambda r: sum(r)) return np.array(rows, dtype=np.int64) @@ -650,4 +672,5 @@ def rat_recon(residues, primes): if getattr(_core, "has_int128", True): return _core.sym_rat_recon(residues, primes) from .sym.linalg import sym_rat_recon_big + return sym_rat_recon_big(residues, primes) diff --git a/src/symident/install.py b/src/symident/install.py index b8ad48f..0620412 100644 --- a/src/symident/install.py +++ b/src/symident/install.py @@ -43,8 +43,7 @@ def msolve_check(path): with open(fi, "w") as fh: fh.write("x, y\n65521\nx^2+y-7,\nx*y-6\n") try: - r = subprocess.run([path, "-f", fi, "-o", fo, "-P", "1", "-t", "1"], - capture_output=True) + r = subprocess.run([path, "-f", fi, "-o", fo, "-P", "1", "-t", "1"], capture_output=True) except (OSError, subprocess.SubprocessError): return None if r.returncode != 0 or not os.path.exists(fo): @@ -61,11 +60,15 @@ def msolve_check(path): def _cache_bins(): - dirs = [d for d in glob.glob(os.path.join(cache_dir(), "deps-msolve-*")) - if os.path.exists(os.path.join(d, ".msolve-complete"))] + dirs = [ + d + for d in glob.glob(os.path.join(cache_dir(), "deps-msolve-*")) + if os.path.exists(os.path.join(d, ".msolve-complete")) + ] def key(d): return tuple(int(x) if x.isdigit() else 0 for x in os.path.basename(d)[12:].split(".")) + return [os.path.join(d, "bin", _EXE) for d in sorted(dirs, key=key, reverse=True)] @@ -134,11 +137,14 @@ def install_msolve(dir=None, version=None, jobs=None, quiet=False, ask=None): version = version or state.env_value("MSOLVE_VERSION") or MSOLVE_VERSION jobs = jobs or state.env_value("JOBS") if jobs is None: - jobs = max(1, min(8, len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") - else (os.cpu_count() or 2))) + jobs = max( + 1, min(8, len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 2)) + ) if sys.platform == "win32": - raise RuntimeError("install_msolve() does not build on Windows; set SYMIDENT_MSOLVE to " - "an msolve.exe, or place one in the cache, see find_msolve().") + raise RuntimeError( + "install_msolve() does not build on Windows; set SYMIDENT_MSOLVE to " + "an msolve.exe, or place one in the cache, see find_msolve()." + ) if not (shutil.which("curl") or shutil.which("wget")): raise RuntimeError("install_msolve() needs curl or wget to download the sources.") missing = [t for t in ("make", "m4") if not shutil.which(t)] @@ -148,22 +154,36 @@ def install_msolve(dir=None, version=None, jobs=None, quiet=False, ask=None): if ask is None: ask = sys.stdin is not None and sys.stdin.isatty() if ask: - reply = input(f"This downloads and builds msolve {version} with GMP, MPFR and FLINT\n" - f"into: {dir}\nIt requires network access and takes a few minutes. " - "Proceed? [Y/n] ").strip().lower() + reply = ( + input( + f"This downloads and builds msolve {version} with GMP, MPFR and FLINT\n" + f"into: {dir}\nIt requires network access and takes a few minutes. " + "Proceed? [Y/n] " + ) + .strip() + .lower() + ) if reply not in ("", "y", "yes"): print("Aborted; nothing was downloaded or written.") return None os.makedirs(dir, exist_ok=True) script = resources.files("symident").joinpath("tools", "build-msolve.sh") with resources.as_file(script) as sp: - env = dict(os.environ, **{"SYMIDENT_" + k: state.env_value(k) for k in - ("GMP_VERSION", "MPFR_VERSION", "FLINT_VERSION") - if state.env_value(k)}, - SYMIDENT_LIBS_CACHE=dir, SYMIDENT_MSOLVE_VERSION=str(version), - SYMIDENT_JOBS=str(int(jobs)), CC=os.environ.get("CC", "cc")) - r = subprocess.run(["sh", str(sp)], env=env, stdout=subprocess.PIPE, text=True, - stderr=subprocess.DEVNULL if quiet else None) + env = dict( + os.environ, + **{ + "SYMIDENT_" + k: state.env_value(k) + for k in ("GMP_VERSION", "MPFR_VERSION", "FLINT_VERSION") + if state.env_value(k) + }, + SYMIDENT_LIBS_CACHE=dir, + SYMIDENT_MSOLVE_VERSION=str(version), + SYMIDENT_JOBS=str(int(jobs)), + CC=os.environ.get("CC", "cc"), + ) + r = subprocess.run( + ["sh", str(sp)], env=env, stdout=subprocess.PIPE, text=True, stderr=subprocess.DEVNULL if quiet else None + ) if r.returncode != 0: raise RuntimeError("the msolve build failed; see the messages above.") lines = [line for line in r.stdout.splitlines() if line.strip()] diff --git a/src/symident/options.py b/src/symident/options.py index 224033f..e797fd3 100644 --- a/src/symident/options.py +++ b/src/symident/options.py @@ -1,12 +1,31 @@ """Settings of the observability engine.""" -def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse=30, degree_cap=4, - sample_slack=5, probe_retries=8, laurent_deg_num=4, laurent_deg_den=2, - laurent_cand_cap=200000, term_cap=60, general_deg_num=4, general_deg_den=3, - gap_order_cap=8, minsupport_cand_cap=20000, perprime_cap=120, perprime_min_primes=3, - homotopy=True, homotopy_degree=4, seed=0, exact_proof=True, - degree_cap_max=8, exact_work_cap=500000, input_jet_order=0): +def reconst_control( + relevance_cap=6, + relevance_cap_dir=24, + relevance_cap_sparse=30, + degree_cap=4, + sample_slack=5, + probe_retries=8, + laurent_deg_num=4, + laurent_deg_den=2, + laurent_cand_cap=200000, + term_cap=60, + general_deg_num=4, + general_deg_den=3, + gap_order_cap=8, + minsupport_cand_cap=20000, + perprime_cap=120, + perprime_min_primes=3, + homotopy=True, + homotopy_degree=4, + seed=0, + exact_proof=True, + degree_cap_max=8, + exact_work_cap=500000, + input_jet_order=0, +): """Saturation and closed-form reconstruction settings. Parameters @@ -66,23 +85,51 @@ def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse= ------- dict """ - if not (relevance_cap >= 0 and relevance_cap_dir >= 1 and relevance_cap_sparse >= relevance_cap - and degree_cap >= 0 and sample_slack >= 0 and probe_retries >= 1 and term_cap >= 1 - and laurent_deg_num >= 1 and laurent_deg_den >= 0 and laurent_cand_cap >= 1 - and general_deg_num >= 1 and general_deg_den >= 1 and gap_order_cap >= 0 - and minsupport_cand_cap >= 1 and perprime_cap >= 1 and perprime_min_primes >= 2 - and homotopy_degree >= 1 and degree_cap_max >= 0 and exact_work_cap > 0 - and input_jet_order >= 0): + if not ( + relevance_cap >= 0 + and relevance_cap_dir >= 1 + and relevance_cap_sparse >= relevance_cap + and degree_cap >= 0 + and sample_slack >= 0 + and probe_retries >= 1 + and term_cap >= 1 + and laurent_deg_num >= 1 + and laurent_deg_den >= 0 + and laurent_cand_cap >= 1 + and general_deg_num >= 1 + and general_deg_den >= 1 + and gap_order_cap >= 0 + and minsupport_cand_cap >= 1 + and perprime_cap >= 1 + and perprime_min_primes >= 2 + and homotopy_degree >= 1 + and degree_cap_max >= 0 + and exact_work_cap > 0 + and input_jet_order >= 0 + ): raise ValueError("reconst_control: invalid setting") - return {"relevance_cap": int(relevance_cap), "relevance_cap_dir": int(relevance_cap_dir), - "relevance_cap_sparse": int(relevance_cap_sparse), "degree_cap": int(degree_cap), - "sample_slack": int(sample_slack), "probe_retries": int(probe_retries), - "laurent_deg_num": int(laurent_deg_num), "laurent_deg_den": int(laurent_deg_den), - "laurent_cand_cap": int(laurent_cand_cap), "term_cap": int(term_cap), - "general_deg_num": int(general_deg_num), "general_deg_den": int(general_deg_den), - "gap_order_cap": int(gap_order_cap), "minsupport_cand_cap": int(minsupport_cand_cap), - "perprime_cap": int(perprime_cap), "perprime_min_primes": int(perprime_min_primes), - "homotopy": bool(homotopy), "homotopy_degree": int(homotopy_degree), - "seed": int(seed), - "exact_proof": bool(exact_proof), "degree_cap_max": int(max(degree_cap, degree_cap_max)), - "exact_work_cap": float(exact_work_cap), "input_jet_order": int(input_jet_order)} + return { + "relevance_cap": int(relevance_cap), + "relevance_cap_dir": int(relevance_cap_dir), + "relevance_cap_sparse": int(relevance_cap_sparse), + "degree_cap": int(degree_cap), + "sample_slack": int(sample_slack), + "probe_retries": int(probe_retries), + "laurent_deg_num": int(laurent_deg_num), + "laurent_deg_den": int(laurent_deg_den), + "laurent_cand_cap": int(laurent_cand_cap), + "term_cap": int(term_cap), + "general_deg_num": int(general_deg_num), + "general_deg_den": int(general_deg_den), + "gap_order_cap": int(gap_order_cap), + "minsupport_cand_cap": int(minsupport_cand_cap), + "perprime_cap": int(perprime_cap), + "perprime_min_primes": int(perprime_min_primes), + "homotopy": bool(homotopy), + "homotopy_degree": int(homotopy_degree), + "seed": int(seed), + "exact_proof": bool(exact_proof), + "degree_cap_max": int(max(degree_cap, degree_cap_max)), + "exact_work_cap": float(exact_work_cap), + "input_jet_order": int(input_jet_order), + } diff --git a/src/symident/par.py b/src/symident/par.py index e68b6cb..fee1bf8 100644 --- a/src/symident/par.py +++ b/src/symident/par.py @@ -20,7 +20,7 @@ def thread_map(fn, xs, n): return list(ex.map(fn, xs)) -_JOBS = {} +_JOBS: dict = {} _TOKENS = itertools.count() diff --git a/src/symident/petab.py b/src/symident/petab.py index 5c80203..ffeb28c 100644 --- a/src/symident/petab.py +++ b/src/symident/petab.py @@ -23,8 +23,7 @@ def _need(module): try: return __import__(module) except ImportError as exc: - raise ImportError("reading PEtab needs python-libsbml and PyYAML: " - "pip install 'symident[petab]'") from exc + raise ImportError("reading PEtab needs python-libsbml and PyYAML: pip install 'symident[petab]'") from exc def _near_zero(text, rel=1e-12): @@ -32,6 +31,7 @@ def _near_zero(text, rel=1e-12): from tokenize import TokenError import sympy as spy + try: e = spy.parse_expr(str(text).replace("^", "**"), evaluate=False) except (spy.SympifyError, TypeError, SyntaxError, TokenError): @@ -77,8 +77,9 @@ def _table_ids(tabs): ids = [r.get("parameterId", "") for r in tabs.get("parameters") or []] ids += [r.get("petabEntityId", "") for r in tabs.get("mapping") or []] for r in tabs.get("conditions") or []: - ids += [r.get("targetId", "")] + [k for k in r if k not in ("conditionId", "conditionName", "targetId", - "targetValue")] + ids += [r.get("targetId", "")] + [ + k for k in r if k not in ("conditionId", "conditionName", "targetId", "targetValue") + ] return [i for i in ids if i] @@ -119,8 +120,11 @@ def _formula(libsbml, ast): return "0" ast = ast.deepCopy() stack = [ast] - consts = {libsbml.AST_CONSTANT_PI: "pi", libsbml.AST_CONSTANT_E: "exp(1)", - libsbml.AST_NAME_AVOGADRO: "602214076000000000000000"} + consts = { + libsbml.AST_CONSTANT_PI: "pi", + libsbml.AST_CONSTANT_E: "exp(1)", + libsbml.AST_NAME_AVOGADRO: "602214076000000000000000", + } named = [] while stack: node = stack.pop() @@ -158,8 +162,11 @@ def read_sbml(path, names=()): """The odes, initial values, values, events and rules of an SBML model; unreadable ids, also of `names`, renamed.""" libsbml = _need("libsbml") doc = libsbml.SBMLReader().readSBML(str(path)) - fatal = [doc.getError(i).getMessage() for i in range(doc.getNumErrors()) - if doc.getError(i).getSeverity() >= libsbml.LIBSBML_SEV_ERROR] + fatal = [ + doc.getError(i).getMessage() + for i in range(doc.getNumErrors()) + if doc.getError(i).getSeverity() >= libsbml.LIBSBML_SEV_ERROR + ] if fatal: raise PEtabError("SBML parse failed: " + "; ".join(fatal)) for prop in ("expandFunctionDefinitions", "promoteLocalParameters"): @@ -174,6 +181,7 @@ def read_sbml(path, names=()): def fm(ast): return _formula(libsbml, ast) + init = {a.getSymbol(): fm(a.getMath()) for a in m.getListOfInitialAssignments()} assign, rate = {}, {} for r in m.getListOfRules(): @@ -268,12 +276,24 @@ def fm(ast): if bad: raise PEtabError(f"event {e.getId()} assigns {', '.join(bad)}, which is not a state") events += [dict(when, var=x, value=v, method="replace") for x, v in rescaled(new, conc)] - moving = [s.getId() for s in species if s.getId() in odes and s.getId() not in rate - and not (s.getBoundaryCondition() or s.getConstant())] - return {"odes": odes, "initial": initial, "values": values, "events": events, "assignments": assign, - "variable": sorted(dvol), "conc": conc, "renamed": renames, - "network": network, "moving": moving, "volume": {x: (None if x in amount else c) - for x, c in volume.items()}} + moving = [ + s.getId() + for s in species + if s.getId() in odes and s.getId() not in rate and not (s.getBoundaryCondition() or s.getConstant()) + ] + return { + "odes": odes, + "initial": initial, + "values": values, + "events": events, + "assignments": assign, + "variable": sorted(dvol), + "conc": conc, + "renamed": renames, + "network": network, + "moving": moving, + "volume": {x: (None if x in amount else c) for x, c in volume.items()}, + } def rescaled(new, conc): @@ -290,6 +310,7 @@ def _time_derivative(expr): import sympy as spy from .sym.parse import model_sympify + e = model_sympify(expr) return str(spy.diff(e, spy.Symbol("time"))).replace("**", "^") @@ -297,6 +318,7 @@ def _time_derivative(expr): def _network(sb, rates, value): """Species, stoichiometry, rates and volumes of the moving species, or None for a non-numeric volume ratio.""" import sympy as spy + sp = sb["moving"] if not sp: return None @@ -308,6 +330,7 @@ def per_volume(x): c = sb["volume"][x] vols[x] = spy.Integer(1) if c is None else 1 / spy.sympify(value.get(c, c)) return vols[x] + rows, out = [], [] for (_, net), v in zip(sb["network"], rates): hit = sorted((x for x in net if net[x] and x in at), key=at.get) @@ -348,6 +371,7 @@ def _calls(text, name): def _piecewise_value(args, table): """The value of piecewise(v1, c1, ..., otherwise) at the numbers `table`, or None.""" from .sym.parse import model_sympify + pairs = list(zip(args[0::2], args[1::2])) for v, c in pairs + ([(args[-1], "1 > 0")] if len(args) % 2 else []): try: @@ -367,8 +391,11 @@ def _parameter_switches(exprs, states, trafos): found, found_vals, out = {}, {}, dict(exprs) for k in list(out): while True: - calls = [c for c in _calls(out[k], "piecewise") - if not set(get_symbols([" ".join(c[2])])) & (set(states) | {"time"})] + calls = [ + c + for c in _calls(out[k], "piecewise") + if not set(get_symbols([" ".join(c[2])])) & (set(states) | {"time"}) + ] vals = [] for a, b, args in calls: v = [_piecewise_value(args, {s: f"({t})" for s, t in tr.items()}) for tr in trafos] @@ -388,6 +415,7 @@ def _time_switches(odes, states, values): import sympy as spy from .sym.parse import model_sympify + steps, out, seen, texts = {}, dict(odes), {}, {} for k in list(out): for a, b, args in sorted(_calls(out[k], "piecewise"), reverse=True): @@ -401,8 +429,7 @@ def _time_switches(odes, states, values): slope, rest = g.coeff(t), g.subs(t, 0) at = [] for tr in values: - num = {spy.Symbol(x): model_sympify(v) for x, v in tr.items() - if spy.Symbol(x) in g.free_symbols} + num = {spy.Symbol(x): model_sympify(v) for x, v in tr.items() if spy.Symbol(x) in g.free_symbols} sl, T = slope.xreplace(num), (-rest / slope).xreplace(num) if not (sl.is_number and sl != 0 and T.is_Rational): raise ValueError @@ -427,6 +454,7 @@ def _zero(expr): if expr.strip("() ") == "0": return True from .sym.parse import model_sympify + try: return model_sympify(expr) == 0 except SYMPY_FAILS as exc: @@ -455,18 +483,28 @@ def _problem(path): if len(y.get("problems") or []) != 1: raise PEtabError("a PEtab v1 problem with more than one subproblem is not supported") p = y["problems"][0] - files = {"model": (p.get("sbml_files") or [None])[0], "conditions": p.get("condition_files"), - "measurements": p.get("measurement_files"), "observables": p.get("observable_files"), - "parameters": [y["parameter_file"]] if isinstance(y.get("parameter_file"), str) - else y.get("parameter_file")} + files = { + "model": (p.get("sbml_files") or [None])[0], + "conditions": p.get("condition_files"), + "measurements": p.get("measurement_files"), + "observables": p.get("observable_files"), + "parameters": [y["parameter_file"]] + if isinstance(y.get("parameter_file"), str) + else y.get("parameter_file"), + } elif version == "2": models = list((y.get("model_files") or {}).values()) if len(models) != 1 or str(models[0].get("language", "sbml")).lower() != "sbml": raise PEtabError("a PEtab v2 problem needs exactly one SBML model") - files = {"model": models[0]["location"], "conditions": y.get("condition_files"), - "experiments": y.get("experiment_files"), "measurements": y.get("measurement_files"), - "observables": y.get("observable_files"), "parameters": y.get("parameter_files"), - "mapping": y.get("mapping_files")} + files = { + "model": models[0]["location"], + "conditions": y.get("condition_files"), + "experiments": y.get("experiment_files"), + "measurements": y.get("measurement_files"), + "observables": y.get("observable_files"), + "parameters": y.get("parameter_files"), + "mapping": y.get("mapping_files"), + } else: raise PEtabError(f"PEtab format version {y.get('format_version')} is not supported") if not files["model"]: @@ -477,8 +515,10 @@ def _problem(path): def _periods_v1(tabs): """Experiments as {name: [(start, {target: value}), ...]} from the v1 condition table.""" - cond = {r["conditionId"]: {k: v for k, v in r.items() if k not in ("conditionId", "conditionName")} - for r in tabs["conditions"]} + cond = { + r["conditionId"]: {k: v for k, v in r.items() if k not in ("conditionId", "conditionName")} + for r in tabs["conditions"] + } exps, of_row = {}, [] for r in tabs["measurements"]: pre, sim = r.get("preequilibrationConditionId", ""), r["simulationConditionId"] @@ -506,15 +546,21 @@ def _resting(exps, of_row, rows, is_state): times = {} for r, e in zip(rows, of_row): times.setdefault(e, []).append(r.get("time", "")) - rest = [e for e, per in exps.items() if len(per) == 1 and _start(per[0][0]) > -math.inf - and all(_at_inf(t) for t in times.get(e, ["0"]))] + rest = [ + e + for e, per in exps.items() + if len(per) == 1 and _start(per[0][0]) > -math.inf and all(_at_inf(t) for t in times.get(e, ["0"])) + ] if not rest: return exps, [] other = [e for e, per in exps.items() if e not in set(rest) and _start(per[0][0]) > -math.inf] if other: - warnings.warn(f"{len(rest)} experiment(s) measured only at t = inf are read as a trajectory, since " - f"{len(other)} other(s) start without a preequilibration and symident starts all conditions " - "alike", stacklevel=3) + warnings.warn( + f"{len(rest)} experiment(s) measured only at t = inf are read as a trajectory, since " + f"{len(other)} other(s) start without a preequilibration and symident starts all conditions " + "alike", + stacklevel=3, + ) return exps, [] out = dict(exps) for e in rest: @@ -545,14 +591,18 @@ def _periods_v2(tabs): def _drop_species(net, values): """The network `net` without the species of `values`, their values substituted in the rates.""" cols = [j for j, x in enumerate(net["species"]) if x not in values] - return dict(net, species=[net["species"][j] for j in cols], - stoichiometry=[[r[j] for j in cols] for r in net["stoichiometry"]], - rates=[_sub(r, values) for r in net["rates"]]) + return dict( + net, + species=[net["species"][j] for j in cols], + stoichiometry=[[r[j] for j in cols] for r in net["stoichiometry"]], + rates=[_sub(r, values) for r in net["rates"]], + ) def _retotal(net, trafos, starts): """The conserved totals of `net`, with the value of each total at the start entered in the trafos.""" from .detection.cq import conserved_totals + totals = conserved_totals(net["stoichiometry"], net["species"]) or None for tr, x0 in zip(trafos, starts): tr.update({k: _sub(t, x0) for k, t in (totals or {}).items()}) @@ -628,32 +678,46 @@ def read_petab(path): that no event sets and whose rates vanish where all of them are 0 leave the model. """ from .api import Model + version, sbml, tabs = _problem(path) sb = read_sbml(sbml, _table_ids(tabs)) - tabs = {k: [{_renamed(a, sb["renamed"]): _renamed(b, sb["renamed"]) for a, b in r.items()} for r in rows] - for k, rows in tabs.items()} - alias = {r["petabEntityId"]: r["modelEntityId"] for r in tabs.get("mapping") or [] - if r.get("petabEntityId") and r.get("modelEntityId") and r["petabEntityId"] != r["modelEntityId"]} + tabs = { + k: [{_renamed(a, sb["renamed"]): _renamed(b, sb["renamed"]) for a, b in r.items()} for r in rows] + for k, rows in tabs.items() + } + alias = { + r["petabEntityId"]: r["modelEntityId"] + for r in tabs.get("mapping") or [] + if r.get("petabEntityId") and r.get("modelEntityId") and r["petabEntityId"] != r["modelEntityId"] + } par = {r["parameterId"]: r for r in tabs["parameters"]} estimated = [p for p, r in par.items() if _true(r.get("estimate", "1"))] value = dict(sb["values"]) - value.update({p: _number(r.get("nominalValue", "")) or r.get("nominalValue", "") - for p, r in par.items() if p not in estimated}) + value.update( + { + p: _number(r.get("nominalValue", "")) or r.get("nominalValue", "") + for p, r in par.items() + if p not in estimated + } + ) value.update({p: p for p in estimated}) if any(v in ("", None) for v in value.values()): - raise PEtabError("a fixed parameter has no nominal value: " - + ", ".join(k for k, v in value.items() if v in ("", None))) + raise PEtabError( + "a fixed parameter has no nominal value: " + ", ".join(k for k, v in value.items() if v in ("", None)) + ) states = list(sb["odes"]) odes = _inline(sb["odes"], sb["assignments"]) initial = _inline(sb["initial"], sb["assignments"]) exps, of_row = (_periods_v1 if version == "1" else _periods_v2)(tabs) - exps = {e: [(t, {alias.get(k, k): v for k, v in c.items()}) for t, c in per] for e, per in exps.items() - if e in set(of_row)} + exps = { + e: [(t, {alias.get(k, k): v for k, v in c.items()}) for t, c in per] + for e, per in exps.items() + if e in set(of_row) + } names = list(exps) # a constant volume that a later period resets is a state at rest between the periods vols = set(sb["conc"].values()) - resized = sorted({k for per in exps.values() for _, c in per[1:] for k in c - if k in vols and k not in states}) + resized = sorted({k for per in exps.values() for _, c in per[1:] for k in c if k in vols and k not in states}) for k in resized: odes[k], initial[k] = "0", value.pop(k) states.append(k) @@ -661,8 +725,9 @@ def read_petab(path): exps, at_rest = _resting(exps, of_row, tabs["measurements"], is_state) pre = [per[0][0].strip().lower() == "-inf" for per in exps.values()] if any(pre) and not all(pre): - raise PEtabError("some experiments start with a preequilibration and others do not; " - "symident starts all conditions alike") + raise PEtabError( + "some experiments start with a preequilibration and others do not; symident starts all conditions alike" + ) targets = {k for per in exps.values() for _, c in per for k in c} unknown = targets - is_state - set(value) if unknown: @@ -671,12 +736,13 @@ def read_petab(path): def val(expr): # a condition or override value in the estimated parameters return _number(expr) or _sub(expr, {k: v for k, v in value.items() if k != v}) + main = [per[1] if p else per[0] for per, p in zip(exps.values(), pre)] - odes, steps, stepped = _time_switches(odes, states, [{k: val(c[k]) if k in c else value[k] for k in value} - for _, c in main]) + odes, steps, stepped = _time_switches( + odes, states, [{k: val(c[k]) if k in c else value[k] for k in value} for _, c in main] + ) in_odes = set(get_symbols(list(odes.values()))) - changed = sorted({k for per in exps.values() for _, c in per[1:] for k in c - if k not in is_state and k in in_odes}) + changed = sorted({k for per in exps.values() for _, c in per[1:] for k in c if k not in is_state and k in in_odes}) inputs = [f"{k}_si_input" for k in changed] + (list(steps) if all(pre) else []) shift = {k: f"{k} + {u}" for k, u in zip(changed, inputs)} rates = [_inline({"v": v}, sb["assignments"])["v"] for v, _ in sb["network"]] @@ -715,25 +781,34 @@ def val(expr): on = Fraction(at[i]) <= Fraction(main[i][0]) tr[h] = "1" if on and not pre[0] else "0" if not on or pre[0]: - events.append({"time": main[i][0] if on else at[i], "var": h, "value": "1", - "method": "replace", "cond": [i]}) + events.append( + {"time": main[i][0] if on else at[i], "var": h, "value": "1", "method": "replace", "cond": [i]} + ) trafos.append(tr) start = {k: tr[k] for k in changed} for t, c in per[1:]: ev = {"time": t, "method": "replace", "cond": [i]} new = {k: val(v) for k, v in c.items() if k in is_state} events += [dict(ev, var=k, value=v) for k, v in rescaled(new, sb["conc"])] - events += [dict(ev, var=inputs[changed.index(k)], value=f"({val(v)}) - ({start[k]})") - for k, v in c.items() if k in changed] + events += [ + dict(ev, var=inputs[changed.index(k)], value=f"({val(v)}) - ({start[k]})") + for k, v in c.items() + if k in changed + ] params = {k: v for k, v in tr.items() if k not in is_state} fixed = {k: v for k, v in params.items() if k != v} - events += [dict(ev, cond=[i], value=_sub(_inline({"v": ev["value"]}, sb["assignments"])["v"], params), - **{k: _sub(ev[k], fixed if k == "time" else params) for k in ("time", "root") if k in ev}) - for ev in sb["events"]] + events += [ + dict( + ev, + cond=[i], + value=_sub(_inline({"v": ev["value"]}, sb["assignments"])["v"], params), + **{k: _sub(ev[k], fixed if k == "time" else params) for k in ("time", "root") if k in ev}, + ) + for ev in sb["events"] + ] # a parameter that a later period sets to the value it already has in every experiment never changes: the # input of that parameter stays 0 and leaves the model with every term of it - still_in = [u for u, k in zip(inputs, changed) - if all(_zero(str(e["value"])) for e in events if e["var"] == u)] + still_in = [u for u, k in zip(inputs, changed) if all(_zero(str(e["value"])) for e in events if e["var"] == u)] if still_in: zero = {u: "0" for u in still_in} for u, k in zip(inputs, changed): @@ -757,12 +832,15 @@ def val(expr): o = obs[r["observableId"]] holders = [h.strip() for h in (o.get("observablePlaceholders") or "").split(";") if h.strip()] if not holders: - holders = sorted(set(re.findall(rf"\bobservableParameter\d+_{re.escape(r['observableId'])}\b", - o["observableFormula"])), key=lambda h: int(re.findall(r"\d+", h)[0])) + holders = sorted( + set(re.findall(rf"\bobservableParameter\d+_{re.escape(r['observableId'])}\b", o["observableFormula"])), + key=lambda h: int(re.findall(r"\d+", h)[0]), + ) over = [v.strip() for v in (r.get("observableParameters") or "").split(";") if v.strip()] if len(over) != len(holders): - raise PEtabError(f"observable {r['observableId']}: {len(holders)} placeholders, " - f"{len(over)} overrides in a measurement") + raise PEtabError( + f"observable {r['observableId']}: {len(holders)} placeholders, {len(over)} overrides in a measurement" + ) key = (r["observableId"], tuple(over)) if key in seen[i]: continue @@ -774,9 +852,12 @@ def val(expr): if i not in outer_of: outer_of[i] = {k: v for k, v in trafos[i].items() if k not in is_state and k != v} observables[i][name] = _sub(f, outer_of[i]) - positive = [p for p in estimated if par[p].get("parameterScale", "lin") in ("log", "log10") - or (_number(par[p].get("lowerBound", "")) is not None - and Fraction(par[p]["lowerBound"]) > 0)] + positive = [ + p + for p in estimated + if par[p].get("parameterScale", "lin") in ("log", "log10") + or (_number(par[p].get("lowerBound", "")) is not None and Fraction(par[p]["lowerBound"]) > 0) + ] odes, switch, texts = _parameter_switches(odes, states, trafos) for i, tr in enumerate(trafos): tr.update({k: v[i] for k, v in switch.items()}) @@ -784,13 +865,23 @@ def val(expr): for t, k in texts.items(): net["rates"] = [r.replace(t, k) for r in net["rates"]] # a number that every experiment shares enters the equations, so that a vanishing rate drops out - const = {k: v for k, v in trafos[0].items() if k not in odes and not get_symbols([v]) - and all(tr.get(k) == v for tr in trafos)} + const = { + k: v + for k, v in trafos[0].items() + if k not in odes and not get_symbols([v]) and all(tr.get(k) == v for tr in trafos) + } odes = {x: "0" if _zero(_sub(f, const)) else _sub(f, const) for x, f in odes.items()} if net is not None: keep = [j for j, r in enumerate(net["rates"]) if not _zero(_sub(r, const))] - net = dict(net, rates=[_sub(net["rates"][j], const) for j in keep], - stoichiometry=[net["stoichiometry"][j] for j in keep]) if keep else None + net = ( + dict( + net, + rates=[_sub(net["rates"][j], const) for j in keep], + stoichiometry=[net["stoichiometry"][j] for j in keep], + ) + if keep + else None + ) if net is not None and all(pre): totals = _retotal(net, trafos, starts) # states that start at 0 in every experiment, that no event sets and whose rates vanish where all of them are 0 @@ -819,8 +910,11 @@ def val(expr): states = [x for x in states if x not in nil] # a species without dynamics, events or inputs that starts at one value everywhere is that value moved = {e["var"] for e in events} | set(inputs) | set(steps) - still = {x: starts[0][x] for x in states if odes.get(x) == "0" and x not in moved and x in starts[0] - and all(st.get(x) == starts[0][x] for st in starts)} + still = { + x: starts[0][x] + for x in states + if odes.get(x) == "0" and x not in moved and x in starts[0] and all(st.get(x) == starts[0][x] for st in starts) + } if still: odes = {x: _sub(f, still) for x, f in odes.items() if x not in still} observables = [{k: _sub(f, still) for k, f in o.items()} for o in observables] @@ -840,25 +934,44 @@ def val(expr): tr[k] = "0" used = set(get_symbols(list(odes.values()))) | set(odes) | set(totals or {}) trafos = [{k: v for k, v in tr.items() if k in used} for tr in trafos] - outer = set(get_symbols([v for tr in trafos for v in tr.values()] + - [f for o in observables for f in o.values()] + list(odes.values()))) + outer = set( + get_symbols( + [v for tr in trafos for v in tr.values()] + + [f for o in observables for f in o.values()] + + list(odes.values()) + ) + ) positive = [p for p in positive if p in outer] one = len(names) == 1 if net is not None: net = dict(net, stoichiometry=[[float(c) for c in r] for r in net["stoichiometry"]]) if totals: from .detection.cq import exact_totals + totals = exact_totals(totals, odes) - m = Model(odes, observables[0] if one else observables, trafo=trafos[0] if one else trafos, - conditions=None if one else {"rows": names, "cols": {}}, events=events or None, - inputs=inputs, totals=totals, reactions=net, equilibrate=all(pre), positive=positive, - reduce_cq=bool(totals)) + m = Model( + odes, + observables[0] if one else observables, + trafo=trafos[0] if one else trafos, + conditions=None if one else {"rows": names, "cols": {}}, + events=events or None, + inputs=inputs, + totals=totals, + reactions=net, + equilibrate=all(pre), + positive=positive, + reduce_cq=bool(totals), + ) # an estimated parameter that only terms vanishing in every experiment hold has no effect on the output; an # identity entry k = k of a trafo holds no term - texts = list(dict.fromkeys( - list(odes.values()) + [v for tr in trafos for k, v in tr.items() if k != v] - + [f for o in observables for f in o.values()] - + [str(e.get(k, "")) for e in events or [] for k in ("value", "time", "root")])) + texts = list( + dict.fromkeys( + list(odes.values()) + + [v for tr in trafos for k, v in tr.items() if k != v] + + [f for o in observables for f in o.values()] + + [str(e.get(k, "")) for e in events or [] for k in ("value", "time", "root")] + ) + ) syms_of = [set(get_symbols([t])) for t in texts] est = set(estimated) # a parameter in an expression without a substituted 0 is held; one that appears only next to a substituted 0 @@ -869,6 +982,7 @@ def val(expr): unsure -= held if unsure: from .sym.parse import model_sympify + for t, sy in zip(texts, syms_of): if sy & unsure: try: @@ -878,10 +992,18 @@ def val(expr): held |= sy & unsure without = [p for p in estimated if p not in held] if without: - warnings.warn(f"estimated parameters without effect on the model as fitted: {', '.join(without)} (every term " - "that holds them vanishes in every experiment); they are not identifiable and are not " - "coordinates of the detection; m.petab['without_effect'] lists them", stacklevel=2) - m.petab = {"experiments": names, "estimated": estimated, - "fixed": {k: v for k, v in value.items() if k != v}, "renamed": sb["renamed"], - "without_effect": without, "at_rest": at_rest} + warnings.warn( + f"estimated parameters without effect on the model as fitted: {', '.join(without)} (every term " + "that holds them vanishes in every experiment); they are not identifiable and are not " + "coordinates of the detection; m.petab['without_effect'] lists them", + stacklevel=2, + ) + m.petab = { + "experiments": names, + "estimated": estimated, + "fixed": {k: v for k, v in value.items() if k != v}, + "renamed": sb["renamed"], + "without_effect": without, + "at_rest": at_rest, + } return m diff --git a/src/symident/reduction/absorb.py b/src/symident/reduction/absorb.py index b5a2533..e50532d 100644 --- a/src/symident/reduction/absorb.py +++ b/src/symident/reduction/absorb.py @@ -16,8 +16,13 @@ def _model(model, settings): proofs do not apply: the right-hand sides and observables over symbols positive where declared, the unknown and known inputs, per state the initial value (None for a free one), the symbols and the parser onto them.""" obs = model.observables - if isinstance(obs, (list, tuple)) or isinstance(model.trafo, (list, tuple)) or model.conditions or \ - model.events or settings.get("equilibrate"): + if ( + isinstance(obs, (list, tuple)) + or isinstance(model.trafo, (list, tuple)) + or model.conditions + or model.events + or settings.get("equilibrate") + ): return None pos = settings.get("positive", True) texts = [str(v) for v in model.odes.values()] + [str(v) for v in dict(obs).values()] @@ -29,6 +34,7 @@ def _model(model, settings): def parse(t): return model_sympify(str(t)).xreplace({spy.Symbol(n): s for n, s in sym.items()}) + f = {sym[x]: parse(v) for x, v in model.odes.items()} h = {k: parse(v) for k, v in dict(obs).items()} inputs = [sym.get(w, spy.Symbol(w)) for w in model.unknown_inputs] @@ -64,8 +70,12 @@ def inversion(m): observables as inputs, none reading an input, and the matrix of the derivatives of their time derivatives in the inputs of a determinant that is not zero.""" w, h = m["inputs"], list(m["h"].values()) - if len(h) != len(w) or any(e.has(*w) for e in h) or any("time" in {str(s) for s in e.free_symbols} for e in h) \ - or any(e.has(*m["known"]) for e in h): + if ( + len(h) != len(w) + or any(e.has(*w) for e in h) + or any("time" in {str(s) for s in e.free_symbols} for e in h) + or any(e.has(*m["known"]) for e in h) + ): return None try: M = spy.Matrix([[spy.diff(_total(e, m), wj) for wj in w] for e in h]) @@ -125,6 +135,7 @@ def lift(gen, m, coords): def act(e): return sum((spy.diff(e, s) * c for s, c in V.items() if c != 0), spy.Integer(0)) + try: eqs = [_total(xi_x[x], m) - act(m["f"][x]) for x in X] + [act(e) for e in m["h"].values()] eqs = [spy.together(e) for e in eqs] @@ -151,9 +162,12 @@ def act(e): def txt(e): return str(spy.cancel(e)).replace("**", "^") - return {"params": {str(p): txt(v) for p, v in xi_p.items() if v != 0}, - "states": {str(x): txt(v) for x, v in xi_x.items() if v != 0}, - "inputs": {str(w): txt(sub.get(d, 0)) for w, d in zip(m["inputs"], Xi)}} + + return { + "params": {str(p): txt(v) for p, v in xi_p.items() if v != 0}, + "states": {str(x): txt(v) for x, v in xi_x.items() if v != 0}, + "inputs": {str(w): txt(sub.get(d, 0)) for w, d in zip(m["inputs"], Xi)}, + } def _reads(gen, names): @@ -174,6 +188,7 @@ def prepare(raw, model): parameters; a direction without either proof is marked with the reason. `notes` maps the index of a direction to the proof.""" from ..detection.classify import orbit_kind + info = raw.get("info") or {} ui = info.get("unknown_inputs") or {} if not ui.get("names") or not raw.get("symmetries"): @@ -222,8 +237,14 @@ def prepare(raw, model): d["support"] = sym_sort(list(lf["params"])) if d.get("type") == "scaling": w = {k: v for k, v in (d.get("weights") or {}).items() if k in lf["params"]} - if w and all(spy.cancel(model_sympify(lf["params"][k]) - model_sympify(f"({v})*{k}")) == 0 - for k, v in w.items()) and set(w) == set(lf["params"]): + if ( + w + and all( + spy.cancel(model_sympify(lf["params"][k]) - model_sympify(f"({v})*{k}")) == 0 + for k, v in w.items() + ) + and set(w) == set(lf["params"]) + ): d["weights"] = w else: d["type"], d["weights"] = "general", None @@ -239,22 +260,29 @@ def condition(note, inputs, positive): else: dom = ", ".join(f"{w} positive" for w in inputs if w in set(positive or [])) or "real values" if note["proof"] == "inversion": - return (f"every point with the output at the start gives the output of the data with the inputs solved from " - f"the first derivatives of the observables, where these inputs stay in their domain ({dom}) and the " - f"states exist on the time interval of the data; near every point they do") - return (f"the flow of the parameters gives the output of the data with the inputs changed along the lift, where " - f"the changed inputs stay in their domain ({dom}) on the time interval of the data; near every point " - f"they do") + return ( + f"every point with the output at the start gives the output of the data with the inputs solved from " + f"the first derivatives of the observables, where these inputs stay in their domain ({dom}) and the " + f"states exist on the time interval of the data; near every point they do" + ) + return ( + f"the flow of the parameters gives the output of the data with the inputs changed along the lift, where " + f"the changed inputs stay in their domain ({dom}) on the time interval of the data; near every point " + f"they do" + ) def annotate(red, raw, notes): """The proofs `notes` of the directions of `raw` on the blocks of the reduction `red`.""" from ..detection.classify import direction_order + if not isinstance(red, dict) or not notes: return sub = "₀₁₂₃₄₅₆₇₈₉" - labels = {i: "X" + "".join(sub[int(c)] for c in str(k + 1)) - for k, i in enumerate(direction_order(raw.get("symmetries") or []))} + labels = { + i: "X" + "".join(sub[int(c)] for c in str(k + 1)) + for k, i in enumerate(direction_order(raw.get("symmetries") or [])) + } info = raw.get("info") or {} inputs = list((info.get("unknown_inputs") or {}).get("names") or []) pos = (info.get("settings") or {}).get("positive", True) @@ -264,18 +292,25 @@ def annotate(red, raw, notes): if not mine: continue proofs = sorted({n["proof"] for n in mine}) - b["inputs"] = {"absorb": inputs, "proof": proofs[0] if len(proofs) == 1 else proofs, - "condition": "; ".join(dict.fromkeys(condition(n, inputs, pos) for n in mine)), - "lift": {l: of[l]["lift"] for l in b["labels"] if l in of and of[l]["proof"] == "lift"}, - "determinant": next((n["determinant"] for n in mine if n["proof"] == "inversion"), None)} + b["inputs"] = { + "absorb": inputs, + "proof": proofs[0] if len(proofs) == 1 else proofs, + "condition": "; ".join(dict.fromkeys(condition(n, inputs, pos) for n in mine)), + "lift": {l: of[l]["lift"] for l in b["labels"] if l in of and of[l]["proof"] == "lift"}, + "determinant": next((n["determinant"] for n in mine if n["proof"] == "inversion"), None), + } if b.get("status") == "reduced": certs = [] if "inversion" in proofs: inv = next(n for n in mine if n["proof"] == "inversion") - certs.append(f"inputs solved from the derivatives of the observables: the matrix of these derivatives " - f"in the inputs has the determinant {inv['determinant']}, " - + ("of one sign on the domain" if inv["signed"] else "not identically zero")) + certs.append( + f"inputs solved from the derivatives of the observables: the matrix of these derivatives " + f"in the inputs has the determinant {inv['determinant']}, " + + ("of one sign on the domain" if inv["signed"] else "not identically zero") + ) if "lift" in proofs: - certs.append("pointwise lift: the parameter field with state and input components that keeps the " - "right-hand sides and the observables, as identities over Q") + certs.append( + "pointwise lift: the parameter field with state and input components that keeps the " + "right-hand sides and the observables, as identities over Q" + ) b["certificates"] = list(b.get("certificates") or []) + certs diff --git a/src/symident/reduction/blocks.py b/src/symident/reduction/blocks.py index 3fd4d4b..5ebe13a 100644 --- a/src/symident/reduction/blocks.py +++ b/src/symident/reduction/blocks.py @@ -36,9 +36,16 @@ def block_corank(preps): _IV_PREC = 200 # the functions mpmath has in interval arithmetic; an invariant with another one is evaluated exactly -_IV_MODULE = {"exp": mpmath.iv.exp, "log": mpmath.iv.log, "sqrt": mpmath.iv.sqrt, - "sin": mpmath.iv.sin, "cos": mpmath.iv.cos, "tan": mpmath.iv.tan, - "pi": mpmath.iv.pi, "E": mpmath.iv.e} +_IV_MODULE = { + "exp": mpmath.iv.exp, + "log": mpmath.iv.log, + "sqrt": mpmath.iv.sqrt, + "sin": mpmath.iv.sin, + "cos": mpmath.iv.cos, + "tan": mpmath.iv.tan, + "pi": mpmath.iv.pi, + "E": mpmath.iv.e, +} @contextmanager @@ -147,8 +154,7 @@ def grad(iv): with _ivprec(): ivx = [mpmath.iv.mpf(str(spy.N(x, 80, strict=True))) for x in ex] # a point value from 80 digits is widened to an interval of that accuracy - ivx = [x + mpmath.iv.mpf([-1, 1]) * (abs(x).b * mpmath.mpf(10) ** -70 + mpmath.mpf(10) ** -70) - for x in ivx] + ivx = [x + mpmath.iv.mpf([-1, 1]) * (abs(x).b * mpmath.mpf(10) ** -70 + mpmath.mpf(10) ** -70) for x in ivx] return ivx, np.array([float(x.mid) for x in ivx]) except spy.core.evalf.PrecisionExhausted: return None @@ -159,10 +165,12 @@ def grad(iv): def certified(rows, fl): # a nonzero maximal minor: columns chosen by pivoted QR, the interval of the minor free of zero from scipy.linalg import qr - cols = sorted(qr(fl, pivoting=True)[2][:len(rows)]) + + cols = sorted(qr(fl, pivoting=True)[2][: len(rows)]) with _ivprec(): det = _iv_det([[r[c] for c in cols] for r in rows]) return det is not None and not (det.a <= 0 <= det.b) + cand = list(dict.fromkeys(invs)) def select(exact): @@ -189,6 +197,7 @@ def select(exact): Jn.append(gr[0]) sel.append(iv) return sel + out = select(True) return out if out is not None else select(False) @@ -198,10 +207,15 @@ def solve_block(preps, d_poly, d_darboux, d_exp, sep=True): moved, vars_ = _moved_vars(preps) target, count_exact = block_corank(preps) certs, found, stage_ = [], [], "monomial" - certs.append(f"invariant count {target}: " + ("exact, the directions are independent at a point" if count_exact - else "an upper bound, from a rank at one point")) - moved_re = re.compile(r"(? len(found) or (len(got) == len(found) and - sum(map(definite, got)) > sum(map(definite, found))) + return len(got) > len(found) or (len(got) == len(found) and sum(map(definite, got)) > sum(map(definite, found))) + mono = monomial_invariants(preps) certs.append(mono["cert"]) if mono["ok"]: @@ -290,12 +304,22 @@ def better(got): stage_ = "intfactor" else: certs.append("exp stage skipped (d_exp = 0)") - reason = None if len(found) >= target else ( - f"found {len(found)} of {target} independent invariants (poly/rational degree <= {d_poly}, " - f"Darboux degree <= {d_darboux}, exp numerator degree <= {d_exp}); gauge pinning needs the full set") - return {"stage": stage_, "invariants": found, "target": target, "certificates": certs, - "count": "exact" if count_exact else "upper bound", - "reason": reason} + reason = ( + None + if len(found) >= target + else ( + f"found {len(found)} of {target} independent invariants (poly/rational degree <= {d_poly}, " + f"Darboux degree <= {d_darboux}, exp numerator degree <= {d_exp}); gauge pinning needs the full set" + ) + ) + return { + "stage": stage_, + "invariants": found, + "target": target, + "certificates": certs, + "count": "exact" if count_exact else "upper bound", + "reason": reason, + } def fixed_reduce(preps, fixed): @@ -333,8 +357,13 @@ def fixed_reduce(preps, fixed): continue out_p.append(pr) out_s.append(sources[j]) - return {"preps": out_p, "sources": out_s, "removed": sum(used_pivot), - "removed_idx": [i for i in range(k) if used_pivot[i]], "fixed_cols": fixed_cols} + return { + "preps": out_p, + "sources": out_s, + "removed": sum(used_pivot), + "removed_idx": [i for i in range(k) if used_pivot[i]], + "fixed_cols": fixed_cols, + } def _axis_signed(v, reduced, originals): @@ -369,18 +398,24 @@ def _input_absorbed(d, prefer): p = ", ".join(params) or "the moved parameters" verb = "is" if len(params) == 1 else "are" if d.get("input_refusal") == "setting": - return (f"the direction changes the trajectory of {w} together with {p}; the proofs that unknown inputs absorb " - "a direction cover models with one condition, without events and equilibrate, so the reduction has " - f"no section for it; {p} {verb} non-identifiable") + return ( + f"the direction changes the trajectory of {w} together with {p}; the proofs that unknown inputs absorb " + "a direction cover models with one condition, without events and equilibrate, so the reduction has " + f"no section for it; {p} {verb} non-identifiable" + ) if d.get("input_refusal"): - return (f"the direction changes the trajectory of {w} together with {p}; neither the inversion of the inputs " - f"from the observables nor a pointwise lift of the parameter field proves that {w} " - f"{'absorbs' if len(inputs) == 1 else 'absorb'} it, so the reduction has no section for it; {p} {verb} " - "non-identifiable") - return (f"the direction changes the trajectory of {w} together with {p}, with components that depend on " - f"{', '.join(hit)}, which vary in time: it is no vector field on the parameters, so the reduction " - f"has no chart for it; {p} {verb} non-identifiable because {w} " - f"{'absorbs' if len(inputs) == 1 else 'absorb'} the change") + return ( + f"the direction changes the trajectory of {w} together with {p}; neither the inversion of the inputs " + f"from the observables nor a pointwise lift of the parameter field proves that {w} " + f"{'absorbs' if len(inputs) == 1 else 'absorb'} it, so the reduction has no section for it; {p} {verb} " + "non-identifiable" + ) + return ( + f"the direction changes the trajectory of {w} together with {p}, with components that depend on " + f"{', '.join(hit)}, which vary in time: it is no vector field on the parameters, so the reduction " + f"has no chart for it; {p} {verb} non-identifiable because {w} " + f"{'absorbs' if len(inputs) == 1 else 'absorb'} the change" + ) def curved(syms, idx, labels, fixed, d_poly, d_darboux, d_exp, sep=True, pins=None, prefer=None): @@ -391,19 +426,34 @@ def curved(syms, idx, labels, fixed, d_poly, d_darboux, d_exp, sep=True, pins=No blocks = [] def unresolved(labs, support, reason): - return {"labels": labs, "type": "curved", "support": support, "stage": "none", - "status": "unresolved", "invariants": [], "certificates": [], "reason": reason, - "module_combos": None, "transversal": None, "new_parameters": None, "pins": None} + return { + "labels": labs, + "type": "curved", + "support": support, + "stage": "none", + "status": "unresolved", + "invariants": [], + "certificates": [], + "reason": reason, + "module_combos": None, + "transversal": None, + "new_parameters": None, + "pins": None, + } + scal_labs = {labels[i] for i, d in enumerate(syms) if d.get("type") == "scaling"} def kind_of(labs): return "scaling" if labs and all(l in scal_labs for l in labs) else "curved" + has_gen = [] for i in idx: if syms[i].get("generator") is None: - why = ("no closed-form generator: the reconstruction of the detection found none (level open)" - if (prefer or {}).get("reconstructed") else - "no closed-form generator; re-run the detection with reconstruct=True") + why = ( + "no closed-form generator: the reconstruction of the detection found none (level open)" + if (prefer or {}).get("reconstructed") + else "no closed-form generator; re-run the detection with reconstruct=True" + ) blocks.append(unresolved([labels[i]], coords_of(syms[i]), why)) continue why = _input_absorbed(syms[i], prefer) @@ -426,33 +476,55 @@ def kind_of(labs): for grp in group_by([pr["support"] for pr in preps]): glab = [labels[gi[g]] for g in grp] fx = fixed_reduce([preps[g] for g in grp], fixed) - fix_cert = [f"fixed-coordinate elimination: {fx['removed']} of {len(grp)} direction(s) cannot " - f"combine away from {{{', '.join(fx['fixed_cols'])}}}"] if fx["removed"] > 0 else [] + fix_cert = ( + [ + f"fixed-coordinate elimination: {fx['removed']} of {len(grp)} direction(s) cannot " + f"combine away from {{{', '.join(fx['fixed_cols'])}}}" + ] + if fx["removed"] > 0 + else [] + ) fixed_labs = [] if fx["removed"] > 0: used = {s for src in fx["sources"] for s in src} fixed_labs = [glab[i] for i in fx["removed_idx"] if i not in used] if fixed_labs or not fx["preps"]: fl = fixed_labs if fx["preps"] else glab - blocks.append({"labels": fl, "type": "curved", "kind": kind_of(fl), - "support": sym_sort(list(dict.fromkeys(c for g in grp for c in preps[g]["support"]))), - "stage": "fixed", "status": "fixed", "removed_by_fixed": fx["removed"], - "invariants": [], "certificates": fix_cert, "reason": None, - "module_combos": None, "transversal": None, "new_parameters": None, - "pins": None, "gauge_note": "removed entirely by the user's fixed coordinates"}) + blocks.append( + { + "labels": fl, + "type": "curved", + "kind": kind_of(fl), + "support": sym_sort(list(dict.fromkeys(c for g in grp for c in preps[g]["support"]))), + "stage": "fixed", + "status": "fixed", + "removed_by_fixed": fx["removed"], + "invariants": [], + "certificates": fix_cert, + "reason": None, + "module_combos": None, + "transversal": None, + "new_parameters": None, + "pins": None, + "gauge_note": "removed entirely by the user's fixed coordinates", + } + ) if not fx["preps"]: continue # the generators as detected, for the exact check of the invariants; those that move a # fixed coordinate act only through the combinations that do not originals = [preps[g] for g in grp if not set(preps[g]["support"]) & set(fixed or [])] - glab_k = [glab[s[0]] if len(s) == 1 else "(" + "+".join(glab[i] for i in s) + ")" - for s in fx["sources"]] + glab_k = [glab[s[0]] if len(s) == 1 else "(" + "+".join(glab[i] for i in s) + ")" for s in fx["sources"]] # a block that translates linear and logarithmic coordinates needs no invariant search lf = linear_flow(fx["preps"], fixed, prefer) if lf is not None: - own = sym_sort([l for l in glab if l not in set(fixed_labs)])[:len(fx["preps"])] - lf.update(labels=own, kind=kind_of(own), originals=originals, - removed_by_fixed=fx["removed"] if fx["removed"] > 0 and not fixed_labs else None) + own = sym_sort([l for l in glab if l not in set(fixed_labs)])[: len(fx["preps"])] + lf.update( + labels=own, + kind=kind_of(own), + originals=originals, + removed_by_fixed=fx["removed"] if fx["removed"] > 0 and not fixed_labs else None, + ) lf["certificates"] = fix_cert + lf["certificates"] blocks.append(lf) continue @@ -480,6 +552,7 @@ def decomp(pr): if tc is not None: pr = tc["back_prep"](pr) return pr + mr = module_reduce(p2, glab_k) subs = group_by([pr["support"] for pr in mr["preps"]]) # the sub-blocks share the group's labels: each label goes to one sub-block, the @@ -487,7 +560,7 @@ def decomp(pr): src_of = [{s for j in sub for li in mr["labels_of"][j] for s in fx["sources"][li]} for sub in subs] taken = set() for k in sorted(range(len(subs)), key=lambda k: len(src_of[k])): - own = sym_sort([glab[s] for s in src_of[k] if glab[s] not in taken])[:len(subs[k])] + own = sym_sort([glab[s] for s in src_of[k] if glab[s] not in taken])[: len(subs[k])] taken.update(own) src_of[k] = own for sub, sub_labs in zip(subs, src_of): @@ -495,11 +568,15 @@ def decomp(pr): if len(supp) == 1: # a direction along one coordinate: the orbit is the axis where the component keeps one sign blk = scaling_block(np.array([[1]], dtype=np.int64), supp, sub_labs, fixed) - if blk.get("pins") and not _axis_signed(supp[0], [decomp(mr["preps"][j]) for j in sub], - [preps[g] for g in grp]): - blk.update(reach=False, coverage="partial", - gauge_note=f"the component on {supp[0]} is not proven of one sign on the domain; " - f"the orbits between the zeros miss the pin") + if blk.get("pins") and not _axis_signed( + supp[0], [decomp(mr["preps"][j]) for j in sub], [preps[g] for g in grp] + ): + blk.update( + reach=False, + coverage="partial", + gauge_note=f"the component on {supp[0]} is not proven of one sign on the domain; " + f"the orbits between the zeros miss the pin", + ) blocks.append(blk) continue sol = solve_block([mr["preps"][j] for j in sub], d_poly, d_darboux, d_exp, sep) @@ -508,49 +585,74 @@ def decomp(pr): if uc is not None: face_inv = sol["invariants"] if tc is None else tc["back"](sol["invariants"]) sol["invariants"] = uc["back"](sol["invariants"]) - sol["certificates"].append("searched in the unmoved monomial(s) " + - "; ".join(uc["note"]) + - " (constants along every orbit), invariants substituted back") + sol["certificates"].append( + "searched in the unmoved monomial(s) " + + "; ".join(uc["note"]) + + " (constants along every orbit), invariants substituted back" + ) if tc is not None: sol["invariants"] = tc["back"](sol["invariants"]) - sol["certificates"].append("searched in the translation-group sum(s) " + - "; ".join(tc["note"]) + ", invariants substituted back") + sol["certificates"].append( + "searched in the translation-group sum(s) " + + "; ".join(tc["note"]) + + ", invariants substituted back" + ) preps_orig = [mr["preps"][j] for j in sub] if uc is not None or tc is not None: preps_orig = [decomp(pr) for pr in preps_orig] - blocks.append({"labels": sub_labs, "type": "curved", "kind": kind_of(sub_labs), - "support": sym_sort(list(dict.fromkeys(c for pr in preps_orig for c in pr["support"]))), - "stage": sol["stage"], "target": sol["target"], "count": sol.get("count"), - "status": "invariant_only" if sol["invariants"] else "unresolved", - "removed_by_fixed": fx["removed"] if fx["removed"] > 0 and not fixed_labs else None, - "invariants": sol["invariants"], - "certificates": fix_cert + sol["certificates"], "reason": sol["reason"], - "module_combos": mr["combos"], "transversal": None, - "new_parameters": None, "pins": None, "preps": preps_orig, - "originals": originals, "face_invariants": face_inv, - "face_back": uc["back"] if uc is not None else None}) + blocks.append( + { + "labels": sub_labs, + "type": "curved", + "kind": kind_of(sub_labs), + "support": sym_sort(list(dict.fromkeys(c for pr in preps_orig for c in pr["support"]))), + "stage": sol["stage"], + "target": sol["target"], + "count": sol.get("count"), + "status": "invariant_only" if sol["invariants"] else "unresolved", + "removed_by_fixed": fx["removed"] if fx["removed"] > 0 and not fixed_labs else None, + "invariants": sol["invariants"], + "certificates": fix_cert + sol["certificates"], + "reason": sol["reason"], + "module_combos": mr["combos"], + "transversal": None, + "new_parameters": None, + "pins": None, + "preps": preps_orig, + "originals": originals, + "face_invariants": face_inv, + "face_back": uc["back"] if uc is not None else None, + } + ) return blocks def verify_blocks(blocks): """X(I) = 0 for every invariant and every generator, exactly.""" + def chk(inv, preps): try: - return [bool(x) for x in verify_invariants([s.replace("^", "**") for s in inv], - [dict(pr["comps"]) for pr in preps])] + return [ + bool(x) + for x in verify_invariants([s.replace("^", "**") for s in inv], [dict(pr["comps"]) for pr in preps]) + ] except Exception as exc: swallow(exc, "invariant verification") return [False] * len(inv) + ident = re.compile(r"[A-Za-z._][A-Za-z0-9._]*") for bi, b in enumerate(blocks): if b["type"] == "scaling": - if b.get("Wres") is not None and b.get("inv_exps") is not None and \ - b["inv_exps"].shape[1] and b["Wres"].shape[0]: + if ( + b.get("Wres") is not None + and b.get("inv_exps") is not None + and b["inv_exps"].shape[1] + and b["Wres"].shape[0] + ): cols = b["Wcols"] sel = [cols.index(c) for c in b["support"]] if np.any(b["Wres"][:, sel] @ b["inv_exps"] != 0): - raise RuntimeError("internal error: scaling invariant not " - "in the weight kernel.") + raise RuntimeError("internal error: scaling invariant not in the weight kernel.") b["certificates"].append("verified: integer weight annihilation, exact") continue if not b.get("invariants") or b.get("preps") is None: @@ -566,8 +668,10 @@ def chk(inv, preps): if b.get("originals") and b["invariants"]: keep = chk(b["invariants"], b["originals"]) if not all(keep): - b["certificates"].append(f"verification DROPPED {sum(not k for k in keep)} invariant(s): " - "X(I) != 0 for a generator as detected") + b["certificates"].append( + f"verification DROPPED {sum(not k for k in keep)} invariant(s): " + "X(I) != 0 for a generator as detected" + ) b["invariants"] = [i for i, k in zip(b["invariants"], keep) if k] if not any(keep): b["status"] = "unresolved" @@ -580,13 +684,17 @@ def chk(inv, preps): continue other = [pr for pr in other if set(pr["support"]) & inv_syms] if not other: - b["certificates"].append("verified: X(I) = 0 for every direction of every other block too, " - "none of which moves a symbol of these invariants") + b["certificates"].append( + "verified: X(I) = 0 for every direction of every other block too, " + "none of which moves a symbol of these invariants" + ) continue keep = chk(inv, other) if not all(keep): - b["certificates"].append(f"verification DROPPED {sum(not k for k in keep)} invariant(s): " - "X(I) != 0 for a direction of another block") + b["certificates"].append( + f"verification DROPPED {sum(not k for k in keep)} invariant(s): " + "X(I) != 0 for a direction of another block" + ) b["invariants"] = [i for i, k in zip(inv, keep) if k] if not any(keep): b["status"] = "unresolved" diff --git a/src/symident/reduction/branches.py b/src/symident/reduction/branches.py index 3c25f4a..703927c 100644 --- a/src/symident/reduction/branches.py +++ b/src/symident/reduction/branches.py @@ -34,8 +34,10 @@ def branch_charts(discrete, trafo, coords, positive): if not maps: return {"branches": []} if len(maps) > 1: - return {"why": "branch charts cover one discrete symmetry; the fiber has " - f"{len(maps) + 1} points with the output of a generic one"} + return { + "why": "branch charts cover one discrete symmetry; the fiber has " + f"{len(maps) + 1} points with the output of a generic one" + } sig = maps[0] dcoords = list(discrete.get("coordinates") or coords) syms = {c: spy.Symbol(c) for c in dcoords} @@ -88,9 +90,19 @@ def branch_charts(discrete, trafo, coords, positive): unproven.append(f"injective: the coefficient {a} of {x} in {q} has one sign") if not reach: unproven.append(f"reach: {x} = {xe} is positive for positive {delta}") - out.append({"branch": _side_text(s * q), "trafo": chart, "new_parameters": {str(delta): str(s * q)}, - "solved": {str(x): str(xe).replace("**", "^")}, "boundary": [f"{q} = 0"], - "injective": bool(inj), "reach": bool(reach), "unproven": unproven, "map": sig["map"]}) + out.append( + { + "branch": _side_text(s * q), + "trafo": chart, + "new_parameters": {str(delta): str(s * q)}, + "solved": {str(x): str(xe).replace("**", "^")}, + "boundary": [f"{q} = 0"], + "injective": bool(inj), + "reach": bool(reach), + "unproven": unproven, + "map": sig["map"], + } + ) return {"branches": out} diff --git a/src/symident/reduction/core.py b/src/symident/reduction/core.py index e18b99f..0f3f19a 100644 --- a/src/symident/reduction/core.py +++ b/src/symident/reduction/core.py @@ -54,8 +54,10 @@ def assemble_trafo(blocks, coords): def log_chart(obj, coords): """The result in the coordinates X = b^theta, with the name maps.""" - gens = [None if d.get("generator") is None else - {k: str(v).replace("^", "**") for k, v in d["generator"].items()} for d in obj["symmetries"]] + gens = [ + None if d.get("generator") is None else {k: str(v).replace("^", "**") for k, v in d["generator"].items()} + for d in obj["symmetries"] + ] if not gens or all(g is None for g in gens): return None try: @@ -74,6 +76,7 @@ def ren(v): if v is None: return v return [X[th.index(x)] if x in th else x for x in v] + o = dict(obj, symmetries=[dict(d) for d in obj["symmetries"]], info=dict(obj["info"])) for i, d in enumerate(o["symmetries"]): g = ch["gens"][i] @@ -87,9 +90,14 @@ def ren(v): if w and d.get("type") != "scaling" and set(w) <= moved: # translations of the log coordinates: a scaling in X, with integer weights after a common factor q = math.lcm(*[spy.Rational(v).q for v in w.values()]) - d.update(type="scaling", weights={k: str(spy.Rational(v) * q) for k, v in w.items()}, - generator={k: str(spy.cancel(spy.sympify(str(v).replace("^", "**")) * q)).replace("**", "^") - for k, v in d["generator"].items()}) + d.update( + type="scaling", + weights={k: str(spy.Rational(v) * q) for k, v in w.items()}, + generator={ + k: str(spy.cancel(spy.sympify(str(v).replace("^", "**")) * q)).replace("**", "^") + for k, v in d["generator"].items() + }, + ) o["info"]["coordinates"] = ren(list(coords)) o["info"]["recast_coordinates"] = True o["info"]["chart_names"] = dict((o["info"].get("chart_names") or {}), **dict(zip(X, th))) @@ -98,8 +106,10 @@ def ren(v): def exp_chart(obj, coords, positive): """The detection result in the coordinates L = log(v) with the name maps, or None without them.""" - gens = [None if d.get("generator") is None else - {k: str(v).replace("^", "**") for k, v in d["generator"].items()} for d in obj["symmetries"]] + gens = [ + None if d.get("generator") is None else {k: str(v).replace("^", "**") for k, v in d["generator"].items()} + for d in obj["symmetries"] + ] if not gens or all(g is None for g in gens): return None pos = True if positive is True else ([] if positive is False else list(positive)) @@ -117,6 +127,7 @@ def ren(x): if x is None or isinstance(x, bool): return x return [L[v.index(y)] if y in v else y for y in x] + o = dict(obj, symmetries=[dict(d) for d in obj["symmetries"]], info=dict(obj["info"])) for i, d in enumerate(o["symmetries"]): g = ch["gens"][i] @@ -143,6 +154,7 @@ def entries(x): if not x: return x return {unren([k])[0]: back(v, k if k in names_from else None) for k, v in x.items()} + res = dict(res) res["coordinates"] = unren(res.get("coordinates")) res["fixed"] = unren(res.get("fixed")) @@ -158,11 +170,14 @@ def entries(x): if b.get("invariants"): b["invariants"] = [back(x) for x in b["invariants"]] if b.get("new_parameters"): - b["new_parameters"] = {unren([k])[0]: back(v, k if k in names_from else None) - for k, v in b["new_parameters"].items()} + b["new_parameters"] = { + unren([k])[0]: back(v, k if k in names_from else None) for k, v in b["new_parameters"].items() + } if b.get("solved_domain"): - b["solved_domain"] = {unren([k])[0]: (domain_to if domain_to and k in names_from else v) - for k, v in b["solved_domain"].items()} + b["solved_domain"] = { + unren([k])[0]: (domain_to if domain_to and k in names_from else v) + for k, v in b["solved_domain"].items() + } blocks.append(b) res["blocks"] = blocks return res @@ -170,16 +185,21 @@ def entries(x): def exp_back(res, ec): """The reduction result `res` mapped back from the exp coordinates `ec`.""" + def back(x, solve_for=None): return str(exp_chart_back(str(x).replace("^", "**"), ec["v"], ec["L"], solve_for)).replace("**", "^") + return _chart_back(res, ec["L"], ec["v"], back, "positive") def log_back(res, lc): """The reduction result `res` mapped back from the log coordinates `lc`.""" + def back(x, solve_for=None): - return str(log_chart_back(str(x).replace("^", "**"), lc["X"], lc["theta"], lc["base"], - solve_for)).replace("**", "^") + return str(log_chart_back(str(x).replace("^", "**"), lc["X"], lc["theta"], lc["base"], solve_for)).replace( + "**", "^" + ) + return _chart_back(res, lc["X"], lc["theta"], back) @@ -196,6 +216,7 @@ def model_structure(obj, coords): """The structure of the model behind `obj` that the choice of pins uses: the coordinates that enter only the observables, the states, and the unknown inputs with their jets.""" from .scaling import _ID + info = obj.get("info") or {} unknown = (info.get("unknown_inputs") or {}).get("jets") or {} jets = {j for js in unknown.values() for j in js} @@ -205,13 +226,18 @@ def model_structure(obj, coords): obs = [c for c in coords if orig.get(c, c) not in dyn] if rhs else [] states = [c for c in coords if orig.get(c, c) in rhs] reconstructed = bool((info.get("settings") or {}).get("reconstruct")) - return {"observation_only": obs, "states": list(dict.fromkeys(list(rhs) + states)), "unknown_inputs": unknown, - "reconstructed": reconstructed} + return { + "observation_only": obs, + "states": list(dict.fromkeys(list(rhs) + states)), + "unknown_inputs": unknown, + "reconstructed": reconstructed, + } def ordered(obj): """Directions grouped by orbit geometry with labels X1, X2, ..., as in the report of the detection.""" from ..detection.classify import direction_order + syms = obj.get("symmetries") or [] if not syms: return {"syms": [], "labels": []} @@ -225,13 +251,19 @@ def red_result(obj, blocks, trafo, coords, fixed, settings): status = [b["status"] for b in blocks] van = [] for b in blocks: - for r in (b.get("zero_compatibility") or []): + for r in b.get("zero_compatibility") or []: van.append(dict(r, block=", ".join(b["labels"]))) - family = [{"labels": b["labels"], "choices": b.get("choices"), "matroid": b.get("matroid"), - "gauge_note": b.get("gauge_note")} - for b in blocks if b["status"] == "reduced" and - (b.get("choices") is not None or b.get("matroid") is not None or - b.get("gauge_note") is not None)] + family = [ + { + "labels": b["labels"], + "choices": b.get("choices"), + "matroid": b.get("matroid"), + "gauge_note": b.get("gauge_note"), + } + for b in blocks + if b["status"] == "reduced" + and (b.get("choices") is not None or b.get("matroid") is not None or b.get("gauge_note") is not None) + ] removed = [l for b, s in zip(blocks, status) if s in ("fixed", "reduced") for l in b["labels"]] remaining = [l for b, s in zip(blocks, status) if s not in ("fixed", "reduced") for l in b["labels"]] # a listed direction that no block contains depends on the others @@ -241,13 +273,26 @@ def red_result(obj, blocks, trafo, coords, fixed, settings): for b in blocks: b["unproven"] = unproven_of(b) b["generator_level"] = lowest_level(of.get(l, "exact") for l in b["labels"]) - b["level"] = lowest_level([b["generator_level"]] + (["open"] if b["unproven"] else []) + - (["checked"] if b.get("face") and b.get("face_level") == "checked" else [])) + b["level"] = lowest_level( + [b["generator_level"]] + + (["open"] if b["unproven"] else []) + + (["checked"] if b.get("face") and b.get("face_level") == "checked" else []) + ) done = [b for b in blocks if b["status"] in ("reduced", "fixed")] - return {"method": obj.get("method"), "coordinates": coords, "fixed": fixed, "blocks": blocks, - "trafo": trafo, "family": family, "removed": removed, "remaining": remaining, - "dependent": dependent, "zero_compatibility": van or None, "settings": settings, - "level": lowest_level(b["level"] for b in done)} + return { + "method": obj.get("method"), + "coordinates": coords, + "fixed": fixed, + "blocks": blocks, + "trafo": trafo, + "family": family, + "removed": removed, + "remaining": remaining, + "dependent": dependent, + "zero_compatibility": van or None, + "settings": settings, + "level": lowest_level(b["level"] for b in done), + } LEVELS = ("exact", "verified", "checked", "open") @@ -258,15 +303,20 @@ def unproven_of(b): if b.get("status") != "reduced": return [] if b.get("type") == "scaling": - return [] if b.get("reach", True) else [f"each orbit along {k} meets {k} = {v}" - for k, v in (b.get("pins") or {}).items()] + return ( + [] + if b.get("reach", True) + else [f"each orbit along {k} meets {k} = {v}" for k, v in (b.get("pins") or {}).items()] + ) out = [] if b.get("reach") else ["every level set of the invariants is one orbit"] sec = b.get("section") or [] pins = b.get("pins") or {} if b.get("face"): if b.get("face_why") is not None or not b.get("reach"): - out.append(f"the section {', '.join(sec)} lies on a face and gives the output of every orbit " - f"in the limit" + (f" ({b['face_why']})" if b.get("face_why") else "")) + out.append( + f"the section {', '.join(sec)} lies on a face and gives the output of every orbit " + f"in the limit" + (f" ({b['face_why']})" if b.get("face_why") else "") + ) elif b.get("injective"): pass elif sec: @@ -282,6 +332,7 @@ def unproven_of(b): out += [f"{e} positive inside the declared bounds" for e in b.get("unproven_entries") or []] return out + def detection_positive(obj): """The coordinates the detection `obj` declared positive; states and fixed names of the declaration drop out.""" info = obj.get("info") or {} @@ -302,8 +353,7 @@ def finish_reduction(obj, red): ax.setdefault("error_bound", None) red["assumptions"] = ax if any(b.get("unproven") and b.get("status") in ("reduced", "fixed") for b in red.get("blocks") or []): - warnings.warn("a claim of a section is not proven; Reduction.blocks names it under 'unproven'", - stacklevel=3) + warnings.warn("a claim of a section is not proven; Reduction.blocks names it under 'unproven'", stacklevel=3) def check_levels(obj, allow_open=True, allow_checked=True): @@ -312,14 +362,20 @@ def check_levels(obj, allow_open=True, allow_checked=True): levels = [d.get("level") for d in obj.get("symmetries") or []] if "open" in levels: if not allow_open: - raise ValueError("a direction has no closed form (level 'open'); detect with reconstruct=True, " - "or pass allow_open=True to reduce the others") - warnings.warn("a direction has no closed form (level 'open') and stays in the reduced model " - "(Reduction.remaining)", stacklevel=3) + raise ValueError( + "a direction has no closed form (level 'open'); detect with reconstruct=True, " + "or pass allow_open=True to reduce the others" + ) + warnings.warn( + "a direction has no closed form (level 'open') and stays in the reduced model (Reduction.remaining)", + stacklevel=3, + ) ver = (obj.get("info") or {}).get("verification") or {} if ver.get("ok") is False: - why = ("the rank still grows past the Lie order used, so the directions may be over-reported " - f"({ver.get('reason')})") + why = ( + "the rank still grows past the Lie order used, so the directions may be over-reported " + f"({ver.get('reason')})" + ) if not allow_checked: raise ValueError(why + "; pass allow_checked=True to reduce them anyway") warnings.warn(why + "; the reduction rests on them (Reduction.level)", stacklevel=3) @@ -328,19 +384,29 @@ def check_levels(obj, allow_open=True, allow_checked=True): b = info.get("bound") # a direction verified on every entry is checked where the error bound does not apply verified = [p.get("support") for p in info.get("proof") or []] - if isinstance(b, dict) and b.get("probability") is None and all( - d.get("support") in verified for d in obj.get("symmetries") or [] if d.get("level") == "checked"): + if ( + isinstance(b, dict) + and b.get("probability") is None + and all(d.get("support") in verified for d in obj.get("symmetries") or [] if d.get("level") == "checked") + ): why = f"only, since {b.get('why') or 'no error bound applies'}" else: why = "on part of the entries only" if not allow_checked: - raise ValueError(f"a direction is checked at random points {why} (level 'checked'); " - "pass allow_checked=True to reduce on the closed form anyway") - warnings.warn(f"a direction is checked at random points {why}, without an error bound; the " - "reduction rests on the closed form (Reduction.level)", stacklevel=3) + raise ValueError( + f"a direction is checked at random points {why} (level 'checked'); " + "pass allow_checked=True to reduce on the closed form anyway" + ) + warnings.warn( + f"a direction is checked at random points {why}, without an error bound; the " + "reduction rests on the closed form (Reduction.level)", + stacklevel=3, + ) elif "verified" in levels: - warnings.warn("a direction is verified, not proven; the reduction rests on the closed form " - "(Reduction.level)", stacklevel=3) + warnings.warn( + "a direction is verified, not proven; the reduction rests on the closed form (Reduction.level)", + stacklevel=3, + ) def monotone_pins(b, gens): @@ -349,6 +415,7 @@ def monotone_pins(b, gens): return [] from .expr import red_locals, red_sympify from .sign import sgn + gen = gens[0].get("generator") or {} out = [] for k, v in (b.get("pins") or {}).items(): @@ -370,8 +437,9 @@ def _face_proof(obj, b, pins, sol, gen_of, coords, degrees): if info.get("recast_coordinates"): return False, "the model is not checked at the face in log or exponential coordinates", None gens = block_generators(b["labels"], gen_of) - reach = gens is not None and not set(pins) & set(b["support"]) and \ - face_reach(b, pins, sol["gauge"], gens) is not None + reach = ( + gens is not None and not set(pins) & set(b["support"]) and face_reach(b, pins, sol["gauge"], gens) is not None + ) if not info.get("model_exprs"): return reach, "the model expressions are not known", None eq = (info.get("settings") or {}).get("equilibrate") @@ -383,8 +451,16 @@ def _face_proof(obj, b, pins, sol, gen_of, coords, degrees): if lifted is not None: rest = face_state_limit(b, pins, sol["gauge"], lifted[0], list(rhs), degrees) lift_level = lifted[1] - why, level = face_regular(sol["gauge"], info["model_exprs"], rhs, eq, coords, b["support"], rest=rest, - inputs=info.get("model_inputs") or ()) + why, level = face_regular( + sol["gauge"], + info["model_exprs"], + rhs, + eq, + coords, + b["support"], + rest=rest, + inputs=info.get("model_inputs") or (), + ) if why is None and rest and lift_level == "checked": if not rest_checked(rhs, (), info.get("model_inputs") or ()): return reach, "the Jacobian of the resting state is not found regular at random points", None @@ -404,10 +480,14 @@ def lifted_generators(labels, gen_of, rhs, inputs=()): from .expr import red_locals, red_sympify from .sign import sgn + states = [x for x, f in rhs.items() if str(f).strip() not in ("0", "0.0")] - loc = red_locals(list(rhs) + [str(v) for v in rhs.values()] + - [str(v) for l in labels for v in ((gen_of.get(l) or {}).get("generator") or {}).values()] + - [str(v) for l in labels for v in ((gen_of.get(l) or {}).get("state_components") or {}).values()]) + loc = red_locals( + list(rhs) + + [str(v) for v in rhs.values()] + + [str(v) for l in labels for v in ((gen_of.get(l) or {}).get("generator") or {}).values()] + + [str(v) for l in labels for v in ((gen_of.get(l) or {}).get("state_components") or {}).values()] + ) X = [spy.Symbol(x) for x in states] level, J = "exact", None rest = {spy.Symbol(str(u)): spy.Integer(0) for u in inputs} @@ -420,8 +500,12 @@ def lifted_generators(labels, gen_of, rhs, inputs=()): return None xi = {spy.Symbol(k): red_sympify(str(v).replace("^", "**"), loc) for k, v in d["generator"].items()} if d.get("state_components") is not None: - xi.update({spy.Symbol(k): red_sympify(str(v).replace("^", "**"), loc) - for k, v in d["state_components"].items()}) + xi.update( + { + spy.Symbol(k): red_sympify(str(v).replace("^", "**"), loc) + for k, v in d["state_components"].items() + } + ) for x in rhs: lhs = sum(c * spy.diff(F[x], k) for k, c in xi.items()) rhs_ = sum(F[y] * spy.diff(xi.get(spy.Symbol(x), 0), spy.Symbol(y)) for y in rhs) @@ -488,14 +572,20 @@ def composed_check(res): import sympy as spy from ..sym.parse import _make_local_parse + tr = res.get("trafo") or {} out = {"pins": True, "invariants": True, "failed": []} pos_names = _positive_symbols(res) def zero(e): - e = e.xreplace({x: spy.Symbol(str(x), positive=True) if str(x) in pos_names else - spy.Symbol(str(x), real=True) for x in e.free_symbols}) + e = e.xreplace( + { + x: spy.Symbol(str(x), positive=True) if str(x) in pos_names else spy.Symbol(str(x), real=True) + for x in e.free_symbols + } + ) return spy.simplify(spy.expand_log(e)) == 0 + try: _, parse = _make_local_parse([str(v) for v in tr.values()] + list(tr)) for b in res.get("blocks") or []: @@ -525,13 +615,14 @@ def _tidy_root(x, positive=None): import sympy as spy from ..sym.parse import _make_local_parse + try: _, parse = _make_local_parse([str(x)]) e = parse(str(x).replace("^", "**")) - pos = {s: spy.Symbol(str(s), positive=True) for s in e.free_symbols - if positive is None or str(s) in positive} - y = e.xreplace(pos).replace(lambda a: a.is_Pow and a.exp == spy.Rational(1, 2), - lambda a: spy.sqrt(spy.factor(a.base))) + pos = {s: spy.Symbol(str(s), positive=True) for s in e.free_symbols if positive is None or str(s) in positive} + y = e.xreplace(pos).replace( + lambda a: a.is_Pow and a.exp == spy.Rational(1, 2), lambda a: spy.sqrt(spy.factor(a.base)) + ) y = y.xreplace({v: k for k, v in pos.items()}) except SYMPY_FAILS as exc: sympy_fail(exc) @@ -567,8 +658,13 @@ def _chart_rank(res): """Sort key of a reduction: level, directions removed, no sign conditions, total coverage, rational trafo; ties keep build order.""" lv = res.get("level") - return (LEVELS.index(lv) if lv in LEVELS else len(LEVELS), -len(res.get("removed") or []), - _signed(res), _partial(res), not _rational_chart(res)) + return ( + LEVELS.index(lv) if lv in LEVELS else len(LEVELS), + -len(res.get("removed") or []), + _signed(res), + _partial(res), + not _rational_chart(res), + ) def _outside_coordinates(sol, b, coords, states): @@ -592,6 +688,7 @@ def symmetry_reduction(obj, *args, alternatives=False, **kw): def _reduction_charts(obj, *args, alternatives=False, **kw): """Reparametrization removing the non-identifiable directions, the best trafo first when `alternatives` asks.""" + def run(**opts): with state.options(**opts): res = _symmetry_reduction(obj, *args, **kw) @@ -600,13 +697,16 @@ def run(**opts): res["trafo"] = {k: _tidy_root(v, pos) for k, v in res["trafo"].items()} res["checks"] = composed_check(res) return res + res = run() if not isinstance(res, dict) or not res.get("blocks"): return res # a root only in a section under sign conditions asks for no alternative: none replaces such a section weak = {k for b in res["blocks"] if b.get("sign_conditions") for k in (b.get("pins") or {})} - if _rational_chart(dict(res, trafo={k: v for k, v in (res.get("trafo") or {}).items() if k not in weak})) \ - and not alternatives: + if ( + _rational_chart(dict(res, trafo={k: v for k, v in (res.get("trafo") or {}).items() if k not in weak})) + and not alternatives + ): res["alternatives"] = [] return res found = [res] @@ -619,15 +719,25 @@ def run(**opts): except Exception as exc: swallow(exc, "alternative chart") alt = None - if isinstance(alt, dict) and alt.get("trafo") and _chart_valid(alt, obj.get("dim")) and \ - all(alt["trafo"] != f.get("trafo") for f in found): + if ( + isinstance(alt, dict) + and alt.get("trafo") + and _chart_valid(alt, obj.get("dim")) + and all(alt["trafo"] != f.get("trafo") for f in found) + ): found.append(alt) found.sort(key=_chart_rank) best = found[0] - best["alternatives"] = [{"trafo": f["trafo"], "removed": f["removed"], "remaining": f["remaining"], - "rational": _rational_chart(f), - "pins": {k: v for b in f["blocks"] for k, v in (b.get("pins") or {}).items()}} - for f in found[1:]] + best["alternatives"] = [ + { + "trafo": f["trafo"], + "removed": f["removed"], + "remaining": f["remaining"], + "rational": _rational_chart(f), + "pins": {k: v for b in f["blocks"] for k, v in (b.get("pins") or {}).items()}, + } + for f in found[1:] + ] return best @@ -637,6 +747,7 @@ def _rebased(syms, idx, blocks): The combination spans the same distribution where the scalings move the pins; a common polynomial factor of the components is divided out, so the direction vanishes nowhere it did not before.""" from .expr import red_locals, red_sympify + out = list(syms) scal = [b for b in blocks if b["type"] == "scaling" and b.get("pins") and b.get("Wres") is not None] for i in idx: @@ -679,27 +790,43 @@ def _rebased(syms, idx, blocks): return out -def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d_exp=2, separable_=True, - zero_compatibility=False, work_cap=WORK_CAP): - settings = {"d_poly": int(d_poly), "d_darboux": int(d_darboux), "d_exp": int(d_exp), - "separable": bool(separable_), "primes": list(PRIMES)} +def _symmetry_reduction( + obj, + fixed=None, + positive=True, + d_poly=3, + d_darboux=2, + d_exp=2, + separable_=True, + zero_compatibility=False, + work_cap=WORK_CAP, +): + settings = { + "d_poly": int(d_poly), + "d_darboux": int(d_darboux), + "d_exp": int(d_exp), + "separable": bool(separable_), + "primes": list(PRIMES), + } coords = red_coordinates(obj) if fixed is None: fixed = obj.get("gauge") or [] fixed = list(dict.fromkeys(str(f) for f in fixed)) unknown = [f for f in fixed if f not in set(coords)] if unknown: - warnings.warn(f"no effect: {', '.join(unknown)}: not a coordinate of the analysis.", - stacklevel=2) + warnings.warn(f"no effect: {', '.join(unknown)}: not a coordinate of the analysis.", stacklevel=2) pos_set = positive_set_of(positive, coords) settings["positive"] = True if pos_set is None else (False if not pos_set else pos_set) old_pos = set_positive(pos_set) old_work = DOMAIN.get("work"), DOMAIN.get("work_cap") try: if pos_set is not None and zero_compatibility: - warnings.warn("zero limits are the faces of the positive orthant; " - "for a coordinate that is not declared positive, zero is an interior point " - "and the verdict does not apply.", stacklevel=2) + warnings.warn( + "zero limits are the faces of the positive orthant; " + "for a coordinate that is not declared positive, zero is an interior point " + "and the verdict does not apply.", + stacklevel=2, + ) if obj.get("identifiable") or not obj.get("symmetries"): return red_result(obj, [], None, coords, fixed, settings) lc = log_chart(obj, coords) @@ -713,11 +840,17 @@ def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d old_nr = DOMAIN["no_roots"] DOMAIN["no_roots"] = True try: - res = symmetry_reduction(lc["object"], fixed=lc["ren"](fixed), positive=pos2, - d_poly=d_poly, d_darboux=d_darboux, d_exp=d_exp, - separable_=separable_, - zero_compatibility=zero_compatibility, - work_cap=work_cap) + res = symmetry_reduction( + lc["object"], + fixed=lc["ren"](fixed), + positive=pos2, + d_poly=d_poly, + d_darboux=d_darboux, + d_exp=d_exp, + separable_=separable_, + zero_compatibility=zero_compatibility, + work_cap=work_cap, + ) finally: DOMAIN["no_roots"] = old_nr return log_back(res, lc) @@ -731,11 +864,17 @@ def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d old_nr = DOMAIN["no_roots"] DOMAIN["no_roots"] = True try: - res = symmetry_reduction(ec["object"], fixed=ec["ren"](fixed), - positive=pos2 if pos2 else False, d_poly=d_poly, - d_darboux=d_darboux, d_exp=d_exp, separable_=separable_, - zero_compatibility=zero_compatibility, - work_cap=work_cap) + res = symmetry_reduction( + ec["object"], + fixed=ec["ren"](fixed), + positive=pos2 if pos2 else False, + d_poly=d_poly, + d_darboux=d_darboux, + d_exp=d_exp, + separable_=separable_, + zero_compatibility=zero_compatibility, + work_cap=work_cap, + ) finally: DOMAIN["no_roots"] = old_nr return exp_back(res, ec) @@ -781,8 +920,13 @@ def demote(outside_ok): curved_supp = list(dict.fromkeys(curved_supp + [Wc[j] for r in down for j in np.nonzero(W[r])[0]])) scal_rows = [r for r in scal_rows if r not in down] allowed = [c for c in Wc if c not in set(curved_supp)] if curved_supp else None - return {"scal_rows": scal_rows, "demoted": demoted, "curved_supp": curved_supp, - "allowed": allowed, "kept": kept} + return { + "scal_rows": scal_rows, + "demoted": demoted, + "curved_supp": curved_supp, + "allowed": allowed, + "kept": kept, + } def scaling_blocks(dm): blocks = [] @@ -792,14 +936,22 @@ def scaling_blocks(dm): rows = [dm["scal_rows"][c] for c in cp] nzc = [j for j in range(W.shape[1]) if np.any(W[rows][:, j] != 0)] Wb = W[rows][:, nzc] - blocks.append(scaling_block(Wb, [Wc[j] for j in nzc], - [o["labels"][wr["rows"][r]] for r in rows], fixed, - dm["allowed"])) + blocks.append( + scaling_block( + Wb, [Wc[j] for j in nzc], [o["labels"][wr["rows"][r]] for r in rows], fixed, dm["allowed"] + ) + ) return blocks + if state.get("reduce_pin_inside"): # an alternative trafo: the scalings may pin coordinates of the curved directions - dm = {"scal_rows": list(range(W.shape[0])), "demoted": [], "curved_supp": curved_supp0, - "allowed": None, "kept": []} + dm = { + "scal_rows": list(range(W.shape[0])), + "demoted": [], + "curved_supp": curved_supp0, + "allowed": None, + "kept": [], + } blocks = scaling_blocks(dm) else: dm = demote(True) @@ -811,8 +963,13 @@ def scaling_blocks(dm): if not state.get("reduce_pin_inside") and any(b.get("coverage") == "partial" for b in blocks): # a pin on a signed coordinate misses orbits: a positive pin inside the curved support instead, # the curved directions combined with the scalings to leave it unmoved - dm_in = {"scal_rows": list(range(W.shape[0])), "demoted": [], "curved_supp": curved_supp0, - "allowed": None, "kept": []} + dm_in = { + "scal_rows": list(range(W.shape[0])), + "demoted": [], + "curved_supp": curved_supp0, + "allowed": None, + "kept": [], + } best = None for skip in range(REBASE_CHOICES): with state.options(transversal_skip=skip or None): @@ -838,14 +995,31 @@ def scaling_blocks(dm): if b["type"] == "scaling" and b.get("pins"): scal_pins.update(b["pins"]) if curved_idx: - blocks += curved(syms, curved_idx, o["labels"], fixed, d_poly, d_darboux, d_exp, - separable_, scal_pins, model_structure(obj, coords)) + blocks += curved( + syms, + curved_idx, + o["labels"], + fixed, + d_poly, + d_darboux, + d_exp, + separable_, + scal_pins, + model_structure(obj, coords), + ) blocks = verify_blocks(blocks) for b in blocks: # a linear-flow section requires every invariant to pass the exact check if b.get("stage") == "linear flow" and any("DROPPED" in c for c in b.get("certificates") or []): - b.update(status="invariant_only", pins=None, transversal=None, new_parameters=None, - injective=None, reach=None, reason="an invariant of the linear flow failed the exact check") + b.update( + status="invariant_only", + pins=None, + transversal=None, + new_parameters=None, + injective=None, + reach=None, + reason="an invariant of the linear flow failed the exact check", + ) for b in blocks: short = b.get("target") is not None and len(b.get("invariants") or []) < b["target"] for c in (b.get("certificates") or []) if b["type"] == "curved" and short else []: @@ -871,8 +1045,9 @@ def scaling_blocks(dm): swallow(exc, "face section") sol = {"solved": False} if work_cap is not None and DOMAIN["work"] > work_cap and not sol.get("solved"): - session.note("limits", f"face section search of {', '.join(b['labels'])}: " - f"reduce(work_cap={work_cap}) reached") + session.note( + "limits", f"face section search of {', '.join(b['labels'])}: reduce(work_cap={work_cap}) reached" + ) # the gauge section search has a separate budget DOMAIN["work"] = 0 if sol.get("solved"): @@ -882,32 +1057,49 @@ def scaling_blocks(dm): if split is not None: split_pair = [re.sub(r" = 0$", "", x) for x in split["positive"] + split["negative"]] if not sol.get("solved"): - sol = solve_invariants(b, scal_pins, coords, inv_start, split_pair=split_pair, - gens=block_generators(b["labels"], gen_of)) + sol = solve_invariants( + b, scal_pins, coords, inv_start, split_pair=split_pair, gens=block_generators(b["labels"], gen_of) + ) if not sol.get("solved") and split is not None: - sol["reason"] = (f"the orbits leave the {domain_name()} through " - f"{', '.join(split['positive'])} where {split['invariant']} > 0 and through " - f"{', '.join(split['negative'])} where it is < 0; no face covers both, and " - f"no section was certified. An assumption on the sign of {split['invariant']} " - "selects the face") + sol["reason"] = ( + f"the orbits leave the {domain_name()} through " + f"{', '.join(split['positive'])} where {split['invariant']} > 0 and through " + f"{', '.join(split['negative'])} where it is < 0; no face covers both, and " + f"no section was certified. An assumption on the sign of {split['invariant']} " + "selects the face" + ) rooted = sol.get("solved") and sol.get("root_note") is not None pos = positive_set() weak = sol.get("solved") and bool(sol.get("sign_conditions")) if (not sol.get("solved") or rooted or weak) and pos is not None and set(b["support"]) - set(pos): - sol_r = solve_invariants(b, scal_pins, coords, inv_start, prefer_real=True, split_pair=split_pair, - gens=block_generators(b["labels"], gen_of)) + sol_r = solve_invariants( + b, + scal_pins, + coords, + inv_start, + prefer_real=True, + split_pair=split_pair, + gens=block_generators(b["labels"], gen_of), + ) # a section under sign conditions, on part of the orbits only, replaces no solved one - if sol_r.get("solved") and (not rooted or sol_r.get("root_note") is None) and \ - not (sol.get("solved") and sol_r.get("sign_conditions")): + if ( + sol_r.get("solved") + and (not rooted or sol_r.get("root_note") is None) + and not (sol.get("solved") and sol_r.get("sign_conditions")) + ): sol = sol_r if work_cap is not None and DOMAIN["work"] > work_cap: - session.note("limits", f"section search of {', '.join(b['labels'])}: reduce(work_cap={work_cap}) " - "reached") + session.note( + "limits", f"section search of {', '.join(b['labels'])}: reduce(work_cap={work_cap}) reached" + ) if sol.get("solved"): foreign = _outside_coordinates(sol, b, coords, (obj.get("info") or {}).get("model_rhs") or {}) if foreign: - sol = {"solved": False, "reason": f"the invariants involve {', '.join(foreign)}, a resting " - "state that no parameter expression gives"} + sol = { + "solved": False, + "reason": f"the invariants involve {', '.join(foreign)}, a resting " + "state that no parameter expression gives", + } if sol.get("solved"): nums = [] for q in sol.get("inv_names") or []: @@ -924,67 +1116,99 @@ def scaling_blocks(dm): b["section_monotone"] = bool(sol.get("monotone")) and not b["face"] b["reach"] = bool(sol.get("reach")) and not b["face"] if b["face"]: - b["reach"], b["face_why"], b["face_level"] = _face_proof(obj, b, scal_pins, sol, gen_of, - coords, (d_poly, d_darboux, d_exp)) + b["reach"], b["face_why"], b["face_level"] = _face_proof( + obj, b, scal_pins, sol, gen_of, coords, (d_poly, d_darboux, d_exp) + ) gauge_val = list(dict.fromkeys(sol["pins"][g] for g in sol.get("gauge") or [])) b["coverage"] = sol.get("coverage") b["unproven_entries"] = list(sol.get("unproven_entries") or []) b["sign_conditions"] = list(sol.get("sign_conditions") or []) b["solved_domain"] = sol.get("solved_domain") - notes = [(", ".join(sol["section"])) if sol.get("section") is not None - else f"{', '.join(sol.get('gauge') or [])} = {', '.join(gauge_val)}"] + notes = [ + (", ".join(sol["section"])) + if sol.get("section") is not None + else f"{', '.join(sol.get('gauge') or [])} = {', '.join(gauge_val)}" + ] witness = ", ".join(f"{k} = {v}" for k, v in (sol.get("sign_witness") or {}).items()) - notes.append(f"entries {', '.join(b['unproven_entries'])} without a positivity certificate, kept " - "inside the declared bounds" if b["unproven_entries"] else - f"entries without a positivity certificate: the trafo covers the orbits where " - f"{', '.join(b['sign_conditions'])}, a sampled orbit among them ({witness})" - if b["sign_conditions"] else - f"entries certified positive for positive values of the new parameters only; one that " - f"takes both signs leaves part of the {domain_name()} outside the trafo" - if sol.get("coverage") == "partial" else - "entries certified positive for every value of the invariants") + notes.append( + f"entries {', '.join(b['unproven_entries'])} without a positivity certificate, kept " + "inside the declared bounds" + if b["unproven_entries"] + else f"entries without a positivity certificate: the trafo covers the orbits where " + f"{', '.join(b['sign_conditions'])}, a sampled orbit among them ({witness})" + if b["sign_conditions"] + else f"entries certified positive for positive values of the new parameters only; one that " + f"takes both signs leaves part of the {domain_name()} outside the trafo" + if sol.get("coverage") == "partial" + else "entries certified positive for every value of the invariants" + ) if sol.get("root_note"): notes.append(sol["root_note"]) b["gauge_note"] = "; ".join(notes) b["new_parameters"] = sol.get("meaning") b["status"] = "reduced" - certs = ["solved exactly: each invariant becomes a fresh q_ parameter"] if not sol.get( - "section_chart") else ["section chart: the balances solve rationally on the section; the new " - "parameters are the free coordinates of the point where the orbit meets " - "it, met once by every orbit"] + certs = ( + ["solved exactly: each invariant becomes a fresh q_ parameter"] + if not sol.get("section_chart") + else [ + "section chart: the balances solve rationally on the section; the new " + "parameters are the free coordinates of the point where the orbit meets " + "it, met once by every orbit" + ] + ) if sol.get("face"): - certs.append(f"face section certified: every orbit reaches {', '.join(sol['section'])} " - f"with each other coordinate positive (the face point, solved from the " - f"invariants, is positive on the whole {domain_name()})") + certs.append( + f"face section certified: every orbit reaches {', '.join(sol['section'])} " + f"with each other coordinate positive (the face point, solved from the " + f"invariants, is positive on the whole {domain_name()})" + ) elif b["section_monotone"]: certs.append("section: each balance ratio has a derivative of one sign along each generator") elif sol.get("jacobian"): certs.append("section: the Jacobian of the balance ratios along the generators has one sign") if b["injective"]: - certs.append("section met at most once: the solved entries give back every point of " - "the section from the invariants, so two points of one orbit on it coincide") + certs.append( + "section met at most once: the solved entries give back every point of " + "the section from the invariants, so two points of one orbit on it coincide" + ) if b["face"] and b["reach"] and b.get("face_why") is None: - certs.append("face reached in the limit: every orbit closes on the face point, where " - "the model is continuous, so the face point gives the output of the orbit" + - ("; the resting state there is checked at random points of the face, without " - "an error bound" if b.get("face_level") == "checked" else "")) + certs.append( + "face reached in the limit: every orbit closes on the face point, where " + "the model is continuous, so the face point gives the output of the orbit" + + ( + "; the resting state there is checked at random points of the face, without an error bound" + if b.get("face_level") == "checked" + else "" + ) + ) if b["reach"]: - certs.append("every level set of the invariants is one orbit: it is the graph of the " - "solved coordinates over a connected set of gauge values, and the generators are " - "independent on the gauge everywhere") + certs.append( + "every level set of the invariants is one orbit: it is the graph of the " + "solved coordinates over a connected set of gauge values, and the generators are " + "independent on the gauge everywhere" + ) if b["sign_conditions"]: - certs.append(f"trafo certified where {', '.join(b['sign_conditions'])}, the other entries " - f"positive for positive values of the new parameters; the orbits outside are not " - f"covered") + certs.append( + f"trafo certified where {', '.join(b['sign_conditions'])}, the other entries " + f"positive for positive values of the new parameters; the orbits outside are not " + f"covered" + ) elif sol.get("coverage") == "partial": - certs.append(f"trafo certified for positive values of the new parameters only: one that takes " - f"both signs leaves part of the {domain_name()} uncovered") + certs.append( + f"trafo certified for positive values of the new parameters only: one that takes " + f"both signs leaves part of the {domain_name()} uncovered" + ) else: - certs.append("trafo certified: every solved entry positive on the domains of the new parameters (" + - ", ".join(f"{k} {v}" for k, v in (sol.get("solved_domain") or {}).items()) + ")") + certs.append( + "trafo certified: every solved entry positive on the domains of the new parameters (" + + ", ".join(f"{k} {v}" for k, v in (sol.get("solved_domain") or {}).items()) + + ")" + ) if sol.get("shifted"): - certs.append(f"offsets of the new parameters certified for {', '.join(sol['shifted'])}: the " - f"shifted invariant exceeds the offset on the whole {domain_name()}") + certs.append( + f"offsets of the new parameters certified for {', '.join(sol['shifted'])}: the " + f"shifted invariant exceeds the offset on the whole {domain_name()}" + ) b["certificates"] = b["certificates"] + certs else: b["reason"] = sol.get("reason") or b.get("reason") diff --git a/src/symident/reduction/darboux.py b/src/symident/reduction/darboux.py index 0af1401..4a985e5 100644 --- a/src/symident/reduction/darboux.py +++ b/src/symident/reduction/darboux.py @@ -43,8 +43,9 @@ def cofactor_rows(cols, vars_, n_gen, n_mon): rows, per_gen = [], [0] * n_gen for g in range(n_gen): exprs = [str(cl[g]) for cl in cols] - pts = [[int(x) for x in Pool()(np.arange(1, len(vars_) + 1) + 2 * t + 7 * (g + 1))] - for t in range(1, n_mon + 1)] + pts = [ + [int(x) for x in Pool()(np.arange(1, len(vars_) + 1) + 2 * t + 7 * (g + 1))] for t in range(1, n_mon + 1) + ] try: v = eval_rational_batch(exprs, list(vars_), pts) except SYMPY_FAILS as exc: @@ -62,7 +63,7 @@ def cofactor_rows(cols, vars_, n_gen, n_mon): for d in set(den): L = L * d // math.gcd(L, d) row = [n * (L // d) for n, d in zip(num, den)] - if max(abs(x) for x in row) < 2 ** 53: + if max(abs(x) for x in row) < 2**53: rows.append(row) per_gen[g] += 1 if any(x == 0 for x in per_gen): @@ -77,6 +78,7 @@ def _paren(s): def darboux(preps, d_darboux, extactic_ok=True): """Rational invariants from Darboux polynomials (extactic route).""" from ..gfp import mono_table + moved = sym_sort(list(dict.fromkeys(v for pr in preps for v in pr["support"]))) vars_ = sym_sort(list(dict.fromkeys(moved + [v for pr in preps for v in pr["vars"]]))) loc = red_locals([x for pr in preps for x in pr["comps"].values()] + vars_) @@ -129,13 +131,15 @@ def darboux(preps, d_darboux, extactic_ok=True): elif not extactic_ok: coverage = "extactic skipped (invariant count already met): coordinate and xi factors only" else: - coverage = (f"extactic skipped (moved-coordinate basis {Nbasis}, projected entry degree " - f"{entry_deg}, cap {EXTACTIC_CAP}): coordinate and xi factors only") + coverage = ( + f"extactic skipped (moved-coordinate basis {Nbasis}, projected entry degree " + f"{entry_deg}, cap {EXTACTIC_CAP}): coordinate and xi factors only" + ) cert_base = f"Darboux stage ({len(Ps)} candidate factors; {coverage})" def fail(cert): - return {"ok": False, "invariants": [], "cert": cert, "Ps": Ps, "lams": lams, - "coverage": coverage} + return {"ok": False, "invariants": [], "cert": cert, "Ps": Ps, "lams": lams, "coverage": coverage} + if len(Ps) < 2: return fail(f"no rational invariant from Darboux factors; {cert_base}") n_mon = math.comb(len(vars_) + max(1, d_darboux), len(vars_)) + 3 @@ -153,8 +157,7 @@ def fail(cert): base = _paren(Pstr[l]) parts.append(base if K[l, j] == 1 else f"{base}^{int(K[l, j])}") inv.append("*".join(parts)) - return {"ok": True, "invariants": inv, "cert": cert_base, "Ps": Ps, "lams": lams, - "coverage": coverage} + return {"ok": True, "invariants": inv, "cert": cert_base, "Ps": Ps, "lams": lams, "coverage": coverage} EXP_WORK_CAP = 3250 @@ -172,6 +175,7 @@ def _moved_vars(preps): def exp_factors(preps, darb, d_exp): """Exponential factors exp(g/h) and invariants combining them with Darboux factors.""" from ..gfp import mono_table + moved, vars_ = _moved_vars(preps) K = len(preps) D = max([1] + [1 if pr["degree"] is None else int(pr["degree"]) for pr in preps]) @@ -189,8 +193,7 @@ def exp_factors(preps, darb, d_exp): if dj is None or dj < 1: continue h_c.append({"h": P, "cof": darb["lams"][j], "deg": dj}) - h_c2.append({"h": spy.expand(P * P), "cof": [spy.Integer(2) * l for l in darb["lams"][j]], - "deg": 2 * dj}) + h_c2.append({"h": spy.expand(P * P), "cof": [spy.Integer(2) * l for l in darb["lams"][j]], "deg": 2 * dj}) h_c = h_c + h_c2 m_idx = [vars_.index(m) for m in moved] expts_gs = [] @@ -236,9 +239,10 @@ def rows_at(pt, p, expts_g=expts_g, expts_mu=expts_mu, Nmu=Nmu, h_str=h_str, lam gcols = (mulmod(mv_g, inner[:, g], p) - mulmod(mv_g, hl[1 + g], p)) % p mucols = np.zeros(K * Nmu, dtype=np.int64) if Nmu: - mucols[g * Nmu:(g + 1) * Nmu] = mu_neg + mucols[g * Nmu : (g + 1) * Nmu] = mu_neg out.append(np.concatenate([gcols, mucols])) return np.stack(out) + ns = modular_nullspace(rows_at, n, vars_) if ns["basis"] is None or ns["basis"].shape[1] == 0: continue @@ -262,7 +266,7 @@ def rows_at(pt, p, expts_g=expts_g, expts_mu=expts_mu, Nmu=Nmu, h_str=h_str, lam if not Nmu: mu.append(zero) continue - mv = ns["basis"][Ng + g * Nmu:Ng + (g + 1) * Nmu, jc] + mv = ns["basis"][Ng + g * Nmu : Ng + (g + 1) * Nmu, jc] mu.append(zero if not np.any(mv) else red_sympify(poly_string(mv, expts_mu, vars_), loc)) ok_all = True for g in range(K): @@ -277,25 +281,39 @@ def rows_at(pt, p, expts_g=expts_g, expts_mu=expts_mu, Nmu=Nmu, h_str=h_str, lam continue seen.add(key) factors.append({"g": g_expr, "h": hc["h"], "mu": mu}) - cert_base = (f"exp stage (numerator degree <= {d_exp} over {len(h_c)} denominator candidate(s)" - + (f", capped at {EXP_WORK_CAP} unknowns" if capped else "") - + (f", {size_skipped} skipped over the {EXP_SIZE_CAP}-unknown budget" if size_skipped else "") - + f"): {len(factors)} exponential factor(s)") + cert_base = ( + f"exp stage (numerator degree <= {d_exp} over {len(h_c)} denominator candidate(s)" + + (f", capped at {EXP_WORK_CAP} unknowns" if capped else "") + + (f", {size_skipped} skipped over the {EXP_SIZE_CAP}-unknown budget" if size_skipped else "") + + f"): {len(factors)} exponential factor(s)" + ) if not factors: - return {"ok": False, "invariants": [], "factors": [], - "cert": f"no exponential factor with numerator degree <= {d_exp}; {cert_base}"} + return { + "ok": False, + "invariants": [], + "factors": [], + "cert": f"no exponential factor with numerator degree <= {d_exp}; {cert_base}", + } J = len(darb["Ps"]) cols = list(darb["lams"]) + [f["mu"] for f in factors] n_mon = math.comb(len(vars_) + max(1, d_exp + D - 1), len(vars_)) + 3 rows = cofactor_rows(cols, vars_, K, n_mon) if not rows: - return {"ok": False, "invariants": [], "factors": factors, - "cert": f"cofactor sampling failed (inconclusive); {cert_base}"} + return { + "ok": False, + "invariants": [], + "factors": factors, + "cert": f"cofactor sampling failed (inconclusive); {cert_base}", + } Kk = int_kernel(np.array(rows, dtype=object)) - use_col = [j for j in range(Kk.shape[1]) if np.any(Kk[J:J + len(factors), j] != 0)] + use_col = [j for j in range(Kk.shape[1]) if np.any(Kk[J : J + len(factors), j] != 0)] if not use_col: - return {"ok": False, "invariants": [], "factors": factors, - "cert": f"no invariant combining the exponential factors; {cert_base}"} + return { + "ok": False, + "invariants": [], + "factors": factors, + "cert": f"no invariant combining the exponential factors; {cert_base}", + } Pstr = [str(P).replace("**", "^") for P in darb["Ps"]] pos = positive_set() inv = [] @@ -306,7 +324,7 @@ def rows_at(pt, p, expts_g=expts_g, expts_mu=expts_mu, Nmu=Nmu, h_str=h_str, lam base = _paren(Pstr[l]) parts.append(base if w[l] == 1 else f"{base}^{int(w[l])}") arg = spy.Integer(0) - for e2 in np.nonzero(w[J:J + len(factors)])[0]: + for e2 in np.nonzero(w[J : J + len(factors)])[0]: arg = arg + spy.Integer(int(w[J + e2])) * factors[e2]["g"] / factors[e2]["h"] arg = spy.cancel(spy.together(arg)) arg_str = str(arg).replace("**", "^") @@ -346,15 +364,16 @@ def int_factor(preps, darb, ex_factors): w_l = int(w[last]) parts = [f"{_paren(Pstr[l])}^({int(w[l])}/{w_l})" for l in np.nonzero(w[:J])[0]] exp_part = [] - if E and np.any(w[J:J + E] != 0): + if E and np.any(w[J : J + E] != 0): arg = spy.Integer(0) - for e2 in np.nonzero(w[J:J + E])[0]: + for e2 in np.nonzero(w[J : J + E])[0]: arg = arg + spy.Rational(int(w[J + e2]), w_l) * ex_factors[e2]["g"] / ex_factors[e2]["h"] exp_part = [f"exp({spy.cancel(spy.together(arg))})"] Mstr = "*".join(parts + exp_part) or "1" try: - Iv = integrating_factor_integral(Mstr.replace("^", "**"), str(xi[moved[0]]), - str(xi[moved[1]]), moved[0], moved[1]) + Iv = integrating_factor_integral( + Mstr.replace("^", "**"), str(xi[moved[0]]), str(xi[moved[1]]), moved[0], moved[1] + ) except SYMPY_FAILS as exc: sympy_fail(exc) Iv = None @@ -401,18 +420,24 @@ def separable(preps): sympy_fail(exc) pass cand = list(dict.fromkeys(c for c in cand if c and c != "1")) - cert = (f"separable-characteristics stage ({len(sep_idx)} of {len(preps)} generator(s) separable, " - f"{len(cand)} quadrature candidate(s))") + cert = ( + f"separable-characteristics stage ({len(sep_idx)} of {len(preps)} generator(s) separable, " + f"{len(cand)} quadrature candidate(s))" + ) if not cand: return {"ok": False, "invariants": [], "cert": f"no closed-form quadrature; {cert}"} try: - keep = [bool(x) for x in verify_invariants([c.replace("^", "**") for c in cand], - [dict(pr["comps"]) for pr in preps])] + keep = [ + bool(x) + for x in verify_invariants([c.replace("^", "**") for c in cand], [dict(pr["comps"]) for pr in preps]) + ] except Exception as exc: swallow(exc, "invariant verification") keep = None if keep is None or not any(keep): - return {"ok": False, "invariants": [], - "cert": f"quadrature integrals are not invariants of every generator; {cert}"} - return {"ok": True, "invariants": [c for c, k in zip(cand, keep) if k], - "cert": f"{cert}: {sum(keep)} verified"} + return { + "ok": False, + "invariants": [], + "cert": f"quadrature integrals are not invariants of every generator; {cert}", + } + return {"ok": True, "invariants": [c for c, k in zip(cand, keep) if k], "cert": f"{cert}: {sum(keep)} verified"} diff --git a/src/symident/reduction/expr.py b/src/symident/reduction/expr.py index f55f624..a7da74a 100644 --- a/src/symident/reduction/expr.py +++ b/src/symident/reduction/expr.py @@ -18,7 +18,7 @@ def red_locals(strings): return {x: spy.Symbol(x) for s in strings for x in _ID.findall(str(s)) if x} -_SYMP = {} +_SYMP: dict = {} def red_sympify(x, locals_): @@ -43,8 +43,7 @@ def gen_prep(d, pins=None): """A curved generator with denominators cleared, as polynomial components.""" out = {"ok": False, "comps": None, "support": None, "vars": None, "degree": None} comp0 = {k: str(v).replace("^", "**") for k, v in d["generator"].items()} - pins = {k: v for k, v in (pins or {}).items() - if not (k in comp0 and comp0[k] != "0")} + pins = {k: v for k, v in (pins or {}).items() if not (k in comp0 and comp0[k] != "0")} loc = red_locals(list(comp0.values()) + list(pins.values())) try: exprs = {k: red_sympify(x, loc) for k, x in comp0.items()} @@ -102,6 +101,7 @@ def find(i): while parent[i] != i: i = parent[i] return i + for i in range(k - 1): for j in range(i + 1, k): if set(sets[i]) & set(sets[j]): @@ -153,8 +153,7 @@ def eval_batch(exprs, pt, p): if not exprs: return [] try: - v = eval_rational_mod_batch([str(e) for e in exprs], list(pt.keys()), - [[int(x) for x in pt.values()]], int(p)) + v = eval_rational_mod_batch([str(e) for e in exprs], list(pt.keys()), [[int(x) for x in pt.values()]], int(p)) except SYMPY_FAILS as exc: sympy_fail(exc) return [None] * len(exprs) @@ -185,8 +184,9 @@ def module_reduce(preps, labels): off += 1 scheds.append(reduce_schedule(V, p)) sched = min(scheds, key=lambda s: s["fill"])["sched"] - rr = module_reduce_replay([dict(pr["comps"]) for pr in preps], list(cols), - [[int(r) + 1, int(c) + 1] for r, c in sched]) + rr = module_reduce_replay( + [dict(pr["comps"]) for pr in preps], list(cols), [[int(r) + 1, int(c) + 1] for r, c in sched] + ) cand = [{"pr": preps[j], "src_idx": [j], "combo": None} for j in range(k)] for j in range(k): comps = {kk: v for kk, v in (rr["rows"][j] or {}).items()} @@ -213,6 +213,7 @@ def vrow(pr): for j, x in zip(hs, v): out[j] = 0 if x is None else x return out + order = sorted(range(len(cand)), key=lambda j: len(cand[j]["pr"]["support"])) acc = np.zeros((0, len(cols)), dtype=np.int64) out_preps, labels_of, combos = [], [], [] @@ -346,6 +347,7 @@ def tri_solve(sys_, vars_, info=None): Stops, with the branches incomplete, once the work cap of the section search is spent.""" from .sign import budget_spent + if not vars_: return [{}] if budget_spent(): diff --git a/src/symident/reduction/invariants.py b/src/symident/reduction/invariants.py index d6c854e..401f077 100644 --- a/src/symident/reduction/invariants.py +++ b/src/symident/reduction/invariants.py @@ -38,6 +38,7 @@ def exact_rank(rows): def certified_rank(rows): """A lower bound of the rank of a matrix of exact numbers, modulo a prime or by a certified nonzero minor.""" import scipy.linalg + r = exact_rank(rows) if r is not None: return r @@ -51,11 +52,11 @@ def certified_rank(rows): if not np.all(np.isfinite(f)): continue cand = sel + [row] - cols = sorted(scipy.linalg.qr(np.array(fl + [f]), pivoting=True)[2][:len(cand)]) + cols = sorted(scipy.linalg.qr(np.array(fl + [f]), pivoting=True)[2][: len(cand)]) try: det = spy.Matrix([[r_[c] for c in cols] for r_ in cand]).det(method="berkowitz") ok = det.evalf(30, strict=True) != 0 - except (SYMPY_FAILS + (spy.core.evalf.PrecisionExhausted,)) as exc: + except SYMPY_FAILS + (spy.core.evalf.PrecisionExhausted,) as exc: sympy_fail(exc) ok = False if ok: @@ -107,7 +108,7 @@ def modular_nullspace(rows_at, n, eval_vars, min_rows=0): if pend.shape[0] < chunk and rows.shape[0] <= 4 * n + 20: continue rr = rref_modp(np.vstack([red, pend]) % p, p) - red = rr["R"][:rr["rank"]] + red = rr["R"][: rr["rank"]] pend = np.zeros((0, n), dtype=np.int64) r = rr["rank"] if r == n: @@ -144,11 +145,11 @@ def modular_nullspace(rows_at, n, eval_vars, min_rows=0): return {"basis": None, "rows": n_rows} num = [int(x) for x in rec["num"]] den = [int(x) for x in rec["den"]] - if any(abs(x) > 2 ** 40 for x in num) or any(x > 2 ** 40 for x in den): + if any(abs(x) > 2**40 for x in num) or any(x > 2**40 for x in den): return {"basis": None, "rows": n_rows} B = np.zeros((n, nf), dtype=object) for j in range(nf): - dj = den[j * n:(j + 1) * n] + dj = den[j * n : (j + 1) * n] L = 1 for d in set(dj): L = L * d // math.gcd(L, d) @@ -166,11 +167,9 @@ def monomial_invariants(preps): ns = modular_nullspace(lambda pt, p: eta_rows(preps, vars_, pt, p), n, eval_vars) cert = f"monomial stage: exact modular nullspace over {len(PRIMES)} primes, {ns['rows']} sampling rows" if ns["basis"] is None: - return {"ok": False, "invariants": [], "exps": None, - "cert": cert + "; reconstruction failed (inconclusive)"} + return {"ok": False, "invariants": [], "exps": None, "cert": cert + "; reconstruction failed (inconclusive)"} if ns["basis"].shape[1] == 0: - return {"ok": False, "invariants": [], "exps": None, - "cert": f"no Laurent-monomial invariant ({cert})"} + return {"ok": False, "invariants": [], "exps": None, "cert": f"no Laurent-monomial invariant ({cert})"} inv = [mono_string(ns["basis"][:, j], vars_) for j in range(ns["basis"].shape[1])] return {"ok": True, "invariants": inv, "exps": ns["basis"], "vars": vars_, "cert": cert} @@ -203,12 +202,14 @@ def rows_at(pt, p): mv = np.asarray(_core.sym_mono_residues(expts, [int(pt[v]) % p for v in vars_], p), dtype=np.int64) inner = (expts @ eta.T) % p return np.stack([mulmod(mv, inner[:, g], p) for g in range(eta.shape[0])]) + return rows_at def _direction_rank(preps, moved, vars_, ipt): """A certified lower bound of the rank of the block directions on the moved coordinates at the point `ipt`.""" from ..sym.modp import eval_rational_mod + P = PRIMES[0] rows = [] try: @@ -226,8 +227,15 @@ def _direction_rank(preps, moved, vars_, ipt): sub = {spy.Symbol(v): spy.Integer(int(x)) for v, x in zip(vars_, ipt)} loc = red_locals([str(x) for pr in preps for x in pr["comps"].values()]) try: - M = [[red_sympify(str(pr["comps"][v]).replace("^", "**"), loc).xreplace(sub) if v in pr["comps"] - else spy.Integer(0) for v in moved] for pr in preps] + M = [ + [ + red_sympify(str(pr["comps"][v]).replace("^", "**"), loc).xreplace(sub) + if v in pr["comps"] + else spy.Integer(0) + for v in moved + ] + for pr in preps + ] except SYMPY_FAILS as exc: sympy_fail(exc) return 0 @@ -242,8 +250,7 @@ def independent_poly(B, expts, vars_, moved, preps): deg = expts.sum(axis=1) key = [float(np.max(deg[B[:, j] != 0])) * 1e4 + float(np.sum(B[:, j] != 0)) for j in range(B.shape[1])] cfs = [[spy.Rational(x) for x in B[:, j]] for j in range(B.shape[1])] - P = next((q for q in PRIMES if all(int(c.q) % q for col in cfs for c in col) - and all(x % q for x in ip)), None) + P = next((q for q in PRIMES if all(int(c.q) % q for col in cfs for c in col) and all(x % q for x in ip)), None) if P is None: return list(range(min(1, B.shape[1]))) mvp = [int(np.prod([pow(ip[k], int(e), P) for k, e in enumerate(row)], dtype=object) % P) for row in expts] @@ -251,8 +258,10 @@ def independent_poly(B, expts, vars_, moved, preps): def grad_p(cf): # the gradient of sum_i cf_i m_i at the integer point, exactly modulo P c = [int(x.p) % P * invmod(int(x.q) % P, P) % P for x in cf] - return [sum(c[i] * int(expts[i, k]) * mvp[i] for i in range(len(c))) % P * invmod(ip[k] % P, P) % P - for k in m_idx] + return [ + sum(c[i] * int(expts[i, k]) * mvp[i] for i in range(len(c))) % P * invmod(ip[k] % P, P) % P for k in m_idx + ] + Jp, sel = [], [] for j in sorted(range(B.shape[1]), key=lambda j: key[j]): if len(sel) >= target and target > 0: @@ -269,6 +278,7 @@ def grad_p(cf): def poly_invariants(preps, d_poly): """Polynomial invariants of total degree <= d_poly.""" from ..gfp import mono_table + moved = sym_sort(list(dict.fromkeys(v for pr in preps for v in pr["support"]))) vars_ = sym_sort(list(dict.fromkeys(moved + [v for pr in preps for v in pr["vars"]]))) expts = mono_table(len(vars_), int(d_poly)) @@ -278,19 +288,29 @@ def poly_invariants(preps, d_poly): if not N: return {"ok": False, "invariants": [], "cert": "polynomial stage skipped: empty ansatz"} ns = _checked_nullspace(preps, vars_, expts, N) - cert = (f"polynomial stage (degree <= {d_poly}, {N} monomials): exact modular nullspace over " - f"{len(PRIMES)} primes, {ns['rows']} sampling rows" + ns["note"]) + cert = ( + f"polynomial stage (degree <= {d_poly}, {N} monomials): exact modular nullspace over " + f"{len(PRIMES)} primes, {ns['rows']} sampling rows" + ns["note"] + ) if ns["basis"] is None: return {"ok": False, "invariants": [], "cert": cert + "; reconstruction failed (inconclusive)"} if ns["basis"].shape[1] == 0: - return {"ok": False, "invariants": [], - "cert": f"no polynomial invariant of total degree <= {d_poly} beyond functions of " - f"the unmoved coordinates ({cert})"} + return { + "ok": False, + "invariants": [], + "cert": f"no polynomial invariant of total degree <= {d_poly} beyond functions of " + f"the unmoved coordinates ({cert})", + } sel = independent_poly(ns["basis"], expts, vars_, moved, preps) inv = [poly_string(ns["basis"][:, j], expts, vars_) for j in sel] - return {"ok": True, "invariants": inv, "coefs": ns["basis"][:, sel], "expts": expts, - "vars": vars_, - "cert": cert + f"; {len(sel)} functionally independent of {ns['basis'].shape[1]}"} + return { + "ok": True, + "invariants": inv, + "coefs": ns["basis"][:, sel], + "expts": expts, + "vars": vars_, + "cert": cert + f"; {len(sel)} functionally independent of {ns['basis'].shape[1]}", + } def _checked_nullspace(preps, vars_, expts, N): @@ -303,8 +323,9 @@ def _checked_nullspace(preps, vars_, expts, N): return ns gens = [dict(pr["comps"]) for pr in preps] try: - ok = verify_invariants([poly_string(B[:, j], expts, vars_).replace("^", "**") - for j in range(B.shape[1])], gens) + ok = verify_invariants( + [poly_string(B[:, j], expts, vars_).replace("^", "**") for j in range(B.shape[1])], gens + ) except SYMPY_FAILS as exc: sympy_fail(exc) ns["basis"] = None @@ -328,11 +349,13 @@ def _checked_nullspace(preps, vars_, expts, N): def rational_invariants(preps, d_poly): """Rational invariants with a single-coordinate denominator (Laurent ansatz).""" from ..gfp import mono_table + moved = sym_sort(list(dict.fromkeys(v for pr in preps for v in pr["support"]))) vars_ = sym_sort(list(dict.fromkeys(moved + [v for pr in preps for v in pr["vars"]]))) def skip(cert): return {"ok": False, "invariants": [], "cert": cert} + if d_poly < 1: return skip("rational stage skipped (d_poly = 0)") pool = Pool() @@ -353,8 +376,10 @@ def skip(cert): divisible.append(ok) den_c = [m for m, d in zip(moved, divisible) if d] if not den_c: - return skip("rational stage skipped: no moved coordinate divides the generator component " - "component (no usable denominator)") + return skip( + "rational stage skipped: no moved coordinate divides the generator component " + "component (no usable denominator)" + ) moved_idx = [vars_.index(m) for m in moved] T0 = mono_table(len(vars_), int(d_poly)) keep0 = T0[:, moved_idx].sum(axis=1) > 0 @@ -369,14 +394,17 @@ def skip(cert): if N > RATIONAL_CAP: return skip(f"rational stage skipped ({N} Laurent monomials over the {RATIONAL_CAP}-unknown budget)") ns = _checked_nullspace(preps, vars_, expts, N) - cert = (f"rational stage (numerator degree <= {d_poly}, denominator one of {{{', '.join(den_c)}}}; " - f"{N} Laurent monomials): exact modular nullspace over {len(PRIMES)} primes, " - f"{ns['rows']} sampling rows" + ns["note"]) + cert = ( + f"rational stage (numerator degree <= {d_poly}, denominator one of {{{', '.join(den_c)}}}; " + f"{N} Laurent monomials): exact modular nullspace over {len(PRIMES)} primes, " + f"{ns['rows']} sampling rows" + ns["note"] + ) if ns["basis"] is None: return skip(cert + "; reconstruction failed (inconclusive)") if ns["basis"].shape[1] == 0: - return skip(f"no rational invariant with a single-coordinate denominator and numerator " - f"degree <= {d_poly} ({cert})") + return skip( + f"no rational invariant with a single-coordinate denominator and numerator degree <= {d_poly} ({cert})" + ) sel = independent_poly(ns["basis"], expts, vars_, moved, preps) inv = [poly_string(ns["basis"][:, j], expts, vars_) for j in sel] loc = red_locals(inv) @@ -388,5 +416,8 @@ def skip(cert): except SYMPY_FAILS as exc: sympy_fail(exc) out.append(s) - return {"ok": True, "invariants": out, - "cert": cert + f"; {len(sel)} functionally independent of {ns['basis'].shape[1]}"} + return { + "ok": True, + "invariants": out, + "cert": cert + f"; {len(sel)} functionally independent of {ns['basis'].shape[1]}", + } diff --git a/src/symident/reduction/linear.py b/src/symident/reduction/linear.py index 3208945..d74ca8a 100644 --- a/src/symident/reduction/linear.py +++ b/src/symident/reduction/linear.py @@ -63,6 +63,7 @@ def linear_flow(preps, fixed=(), prefer=None): def size(c): return sum(int(spy.count_ops(col[c])) + len(col[c].free_symbols) for col in cols) + # by structure: observation-only coordinates first, initial values last, then linear before logarithmic, # then the smaller components; the name breaks remaining ties only cand = [c for c in moved if any(col[c] != 0 for col in cols)] @@ -117,16 +118,37 @@ def size(c): f"s in R^{r}, with every moved coordinate on the whole line", f"section {pin_txt}: the minor of the components on {', '.join(P)} is {_model(det)}, of one sign on " f"the domain, so x_P + Xi_P(u) s = 0 has exactly one solution s on every orbit", - "section met at most once: two points of one orbit on the section have equal pinned coordinates, so " - "equal s", + "section met at most once: two points of one orbit on the section have equal pinned coordinates, so equal s", "every level set of the invariants is one orbit: the invariants and u fix the point of the orbit on " "the section, and every orbit meets it", ] - note = (f"{pin_txt} meets every orbit once; the other moved coordinates become the invariants listed " - f"under the same names") - return {"type": "curved", "support": moved, "stage": "linear flow", "status": "reduced", - "target": len(moved) - r, "count": "exact", "invariants": list(meaning.values()), - "certificates": certs, "reason": None, "module_combos": None, "transversal": P, "section": None, - "pins": pins, "new_parameters": meaning, "solved_domain": solved_domain, "face": False, - "injective": True, "reach": True, "section_monotone": False, "coverage": "total", - "unproven_entries": [], "sign_conditions": [], "gauge_note": note, "preps": preps} + note = ( + f"{pin_txt} meets every orbit once; the other moved coordinates become the invariants listed " + f"under the same names" + ) + return { + "type": "curved", + "support": moved, + "stage": "linear flow", + "status": "reduced", + "target": len(moved) - r, + "count": "exact", + "invariants": list(meaning.values()), + "certificates": certs, + "reason": None, + "module_combos": None, + "transversal": P, + "section": None, + "pins": pins, + "new_parameters": meaning, + "solved_domain": solved_domain, + "face": False, + "injective": True, + "reach": True, + "section_monotone": False, + "coverage": "total", + "unproven_entries": [], + "sign_conditions": [], + "gauge_note": note, + "preps": preps, + } diff --git a/src/symident/reduction/scaling.py b/src/symident/reduction/scaling.py index 4ce0808..0465905 100644 --- a/src/symident/reduction/scaling.py +++ b/src/symident/reduction/scaling.py @@ -19,8 +19,10 @@ def red_coordinates(obj): co = obj["info"].get("coordinates") if co: return [str(c) for c in co] - warnings.warn("this result has no coordinate list; the emitted " - "trafo covers only coordinates appearing in some direction.", stacklevel=2) + warnings.warn( + "this result has no coordinate list; the emitted trafo covers only coordinates appearing in some direction.", + stacklevel=2, + ) return sym_sort(list(dict.fromkeys(c for d in obj["symmetries"] for c in coords_of(d)))) @@ -136,6 +138,7 @@ def certify_transversal(W, cols, T): def _signed_coordinates(names): """The coordinates among `names` outside the declared positive set.""" from .sign import positive_set + pos = positive_set() return set() if pos is None else {c for c in names if c not in set(pos)} @@ -201,33 +204,51 @@ def scaling_block(W, cols, labels, fixed, allowed=None): fx = scaling_fixed(W, cols, fixed) Wres = fx["Wres"] support = [c for j, c in enumerate(cols) if np.any(W[:, j] != 0)] - blk = {"labels": labels, "type": "scaling", "support": support, "stage": "transversal", - "module_combos": None, "removed_by_fixed": fx["removed"], - "redundant_fixed": fx["redundant"], "certificates": [], "reason": None} + blk = { + "labels": labels, + "type": "scaling", + "support": support, + "stage": "transversal", + "module_combos": None, + "removed_by_fixed": fx["removed"], + "redundant_fixed": fx["redundant"], + "certificates": [], + "reason": None, + } if Wres.shape[0] == 0: - blk.update(status="fixed", stage="fixed", invariants=[], transversal=None, - gauge_note="removed entirely by the user's fixed coordinates") + blk.update( + status="fixed", + stage="fixed", + invariants=[], + transversal=None, + gauge_note="removed entirely by the user's fixed coordinates", + ) return blk K = int_kernel(Wres[:, [cols.index(c) for c in support]]) blk["inv_exps"] = K blk["invariants"] = [mono_string(K[:, j], support) for j in range(K.shape[1])] tv = transversal(Wres, cols, fixed, allowed) - blk.update(transversal=tv["T"], choices=tv["choices"], matroid=tv["matroid"], - new_parameters=tv["new_parameters"], Wres=Wres, Wcols=cols) + blk.update( + transversal=tv["T"], + choices=tv["choices"], + matroid=tv["matroid"], + new_parameters=tv["new_parameters"], + Wres=Wres, + Wcols=cols, + ) if tv["T"] is not None: blk["status"] = "reduced" - blk["gauge_note"] = ("each fixed coordinate may take any nonzero value (here 1); " - "any of the listed choices works") + blk["gauge_note"] = "each fixed coordinate may take any nonzero value (here 1); any of the listed choices works" blk["pins"] = {t: "1" for t in tv["T"]} from .sign import positive_set + pos = positive_set() real = [t for t in tv["T"] if pos is not None and t not in set(pos)] if real: # a scaling keeps the sign of a coordinate: orbits where it is negative miss the pin 1 blk["coverage"] = "partial" blk["gauge_note"] += f"; orbits with {', '.join(real)} < 0 do not meet the pin" - blk["certificates"].append("transversal certified exactly: W[,T] invertible with " - "integer W[,T]^-1 W") + blk["certificates"].append("transversal certified exactly: W[,T] invertible with integer W[,T]^-1 W") else: blk["status"] = "invariant_only" blk["reason"] = "no transversal with an integer (Laurent) absorption matrix" @@ -246,6 +267,7 @@ def find(i): while parent[i] != i: i = parent[i] return i + for i in range(k - 1): for j in range(i + 1, k): if np.any((W[i] != 0) & (W[j] != 0)): diff --git a/src/symident/reduction/sections.py b/src/symident/reduction/sections.py index 082af19..85fb4f9 100644 --- a/src/symident/reduction/sections.py +++ b/src/symident/reduction/sections.py @@ -57,6 +57,7 @@ def join(u): nms = sym_sort(list(ex)) mono = mono_string([ex[n] for n in nms], nms) return mono if u["coef"] == 1 else f"{u['coef']}*{mono}" + out = [] for flip in (False, True): l = mul(parts[0], parts[3 if flip else 2]) @@ -96,8 +97,10 @@ def _bound_pins(support): def section_cands(support, extra=()): """Gauge-section candidates of a curved block: pins, summand balances (those in `support` first), monomial pairs.""" + def key(pr): return " = ".join(sym_sort(list(pr))) + head, groups = [], [] for tm in extra: tm = list(dict.fromkeys(tm)) @@ -223,8 +226,12 @@ def section_jacobian(prs, preps, xi_of, loc): ms = [red_sympify(m.replace("^", "**"), loc) for m in pr] if sgn(ms[0] * ms[1]) == 0: return False - rows.append([spy.expand(apply_x(xi_of[g], ms[0], loc) * ms[1] - ms[0] * apply_x(xi_of[g], ms[1], loc)) - for g in range(len(preps))]) + rows.append( + [ + spy.expand(apply_x(xi_of[g], ms[0], loc) * ms[1] - ms[0] * apply_x(xi_of[g], ms[1], loc)) + for g in range(len(preps)) + ] + ) try: det = spy.expand(spy.Matrix(rows).det(method="berkowitz")) except SYMPY_FAILS as exc: @@ -284,14 +291,16 @@ def _owned(extra=()): def sym(name): if name not in cache: - real = name in set(DOMAIN["real_carriers"]) or (pos is not None and name not in set(pos) and - name not in set(extra)) + real = name in set(DOMAIN["real_carriers"]) or ( + pos is not None and name not in set(pos) and name not in set(extra) + ) cache[name] = spy.Symbol(name, real=True) if real else spy.Symbol(name, positive=True) return cache[name] def own(e): e = spy.sympify(e) return e.xreplace({s: sym(str(s)) for s in e.free_symbols}) + return sym, own @@ -299,8 +308,9 @@ def _vanishes(e): if spy.cancel(e) == 0: return True # a radicand factored lets a square under the root leave it, by the signs of the symbols - rads = {a: spy.Pow(spy.factor(a.base), a.exp) for a in e.atoms(spy.Pow) - if a.exp.is_Rational and not a.exp.is_Integer} + rads = { + a: spy.Pow(spy.factor(a.base), a.exp) for a in e.atoms(spy.Pow) if a.exp.is_Rational and not a.exp.is_Integer + } return (bool(rads) and spy.cancel(e.xreplace(rads)) == 0) or spy.simplify(e) == 0 @@ -399,7 +409,7 @@ def _signed_factors(polys): if sf == 0: keep.append((f, m)) else: - rep[0] *= sf ** m + rep[0] *= sf**m changed = True rep[1] = keep return [(s, fs) for s, fs, _ in reps] @@ -421,7 +431,7 @@ def _connected(polys, g): reps = _signed_factors(polys) if any(sg <= 0 and not fs for sg, fs in reps): return True - conds = [sg * spy.Mul(*[f ** m for f, m in fs]) for sg, fs in reps if fs] + conds = [sg * spy.Mul(*[f**m for f, m in fs]) for sg, fs in reps if fs] if not g or all(_convex_kind(c, g) for c in conds): return True facts = [(fs[0][0], sg) for sg, fs in reps if len(fs) == 1 and fs[0][1] % 2 == 1] @@ -437,8 +447,9 @@ def sign_free_of(a, x): if spy.Symbol(str(x)) not in k.free_symbols and r.is_number and r != 0: sf = sk * (1 if r > 0 else -1) break - s *= sf ** m + s *= sf**m return s + best = None for x in g: lower, upper, keep, ok = [], [], [], True @@ -470,15 +481,22 @@ def sign_free_of(a, x): def _rational_gauges(sol, gauge): """`sol` and the gauge after g = c*u^2 or g = u^2/c, for each choice that leaves no root in the gauge.""" real = set(DOMAIN["real_carriers"]) - sym, own = _owned([str(x) for e in sol.values() for x in spy.sympify(e).free_symbols - if str(x).startswith("si_red_c") and str(x) not in real]) + sym, own = _owned( + [ + str(x) + for e in sol.values() + for x in spy.sympify(e).free_symbols + if str(x).startswith("si_red_c") and str(x) not in real + ] + ) outs = [({k: own(e) for k, e in sol.items()}, list(gauge))] for i, v in enumerate(gauge): x = sym(v) nxt = [] for cur, names in outs: - roots = {w for e in cur.values() for w in e.atoms(spy.Pow) - if w.exp.is_Rational and w.exp.q == 2 and w.has(x)} + roots = { + w for e in cur.values() for w in e.atoms(spy.Pow) if w.exp.is_Rational and w.exp.q == 2 and w.has(x) + } if not roots: nxt.append((cur, names)) continue @@ -495,36 +513,47 @@ def _rational_gauges(sol, gauge): continue for to in (c * u**2, u**2 / c): new = {k: spy.simplify(spy.cancel(e.subs(x, to))) for k, e in cur.items()} - if any(w2.has(u) for e in new.values() for w2 in e.atoms(spy.Pow) - if w2.exp.is_Rational and w2.exp.q != 1): + if any( + w2.has(u) + for e in new.values() + for w2 in e.atoms(spy.Pow) + if w2.exp.is_Rational and w2.exp.q != 1 + ): continue - nxt.append((new, names[:i] + [str(u)] + names[i + 1:])) + nxt.append((new, names[:i] + [str(u)] + names[i + 1 :])) if len(nxt) == n0: nxt.append((cur, names)) outs = nxt done = [] for cur, names in outs: # t = s^2, s > 0, maps t > 0 one to one and leaves no root of a single symbol - sq = {w.base for e in cur.values() for w in e.atoms(spy.Pow) - if w.exp.is_Rational and w.exp.q == 2 and w.base.is_Symbol and w.base.is_positive} - cur = {k: spy.factor(spy.cancel(spy.together(e.xreplace( - {t: spy.Symbol(f"si_sq_{t}", positive=True)**2 for t in sq})))) for k, e in cur.items()} - done.append(({k: e.xreplace({y: spy.Symbol(str(y)) for y in e.free_symbols}) for k, e in cur.items()}, - names)) + sq = { + w.base + for e in cur.values() + for w in e.atoms(spy.Pow) + if w.exp.is_Rational and w.exp.q == 2 and w.base.is_Symbol and w.base.is_positive + } + cur = { + k: spy.factor( + spy.cancel(spy.together(e.xreplace({t: spy.Symbol(f"si_sq_{t}", positive=True) ** 2 for t in sq}))) + ) + for k, e in cur.items() + } + done.append(({k: e.xreplace({y: spy.Symbol(str(y)) for y in e.free_symbols}) for k, e in cur.items()}, names)) return done def _convex_set(carriers, sol, gauge): """Whether the gauge values at which every positive carrier is positive form a connected set.""" for sol2, gauge2 in _rational_gauges(sol, gauge): - new = [v for v in gauge2 if v.startswith("si_root_")] + \ - [str(y) for e in sol2.values() for y in e.free_symbols if str(y).startswith("si_sq_")] + new = [v for v in gauge2 if v.startswith("si_root_")] + [ + str(y) for e in sol2.values() for y in e.free_symbols if str(y).startswith("si_sq_") + ] old = positive_set() if new and old is not None: set_positive(list(old) + new) try: - cons = [k for c in carriers if not is_real(c) and _sign_fixed(sol2[c]) != 1 - for k in _constraints(sol2[c])] + cons = [k for c in carriers if not is_real(c) and _sign_fixed(sol2[c]) != 1 for k in _constraints(sol2[c])] if _connected([spy.expand(num * den) for num, den in cons], [spy.Symbol(v) for v in gauge2]): return True except SYMPY_FAILS as exc: @@ -611,8 +640,10 @@ def face_reach(b, pins, Z, gens, limit_only=False): try: sub = [(spy.Symbol(k), red_sympify(str(v).replace("^", "**"), loc)) for k, v in pins.items()] Ies = [red_sympify(iv.replace("^", "**"), loc).subs(sub) for iv in b["invariants"]] - branches = [{str(k): v for k, v in d.items()} for d in - spy.solve([e - spy.Symbol(t) for e, t in zip(Ies, tmp)], [spy.Symbol(u) for u in U], dict=True)] + branches = [ + {str(k): v for k, v in d.items()} + for d in spy.solve([e - spy.Symbol(t) for e, t in zip(Ies, tmp)], [spy.Symbol(u) for u in U], dict=True) + ] except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -620,9 +651,13 @@ def face_reach(b, pins, Z, gens, limit_only=False): DOMAIN["real_carriers"] = [t for t, e in zip(tmp, Ies) if sgn(e) != 1] try: if limit_only: - ok = [{c: br[c] for c in U} for br in branches if all(br.get(c) is not None for c in U) - and section_injective(Ies, {c: br[c] for c in U}, tmp, list(pins.items())) - and _graph(Ies, {c: br[c] for c in U}, tmp, list(pins.items()))] + ok = [ + {c: br[c] for c in U} + for br in branches + if all(br.get(c) is not None for c in U) + and section_injective(Ies, {c: br[c] for c in U}, tmp, list(pins.items())) + and _graph(Ies, {c: br[c] for c in U}, tmp, list(pins.items())) + ] sol = ok[0] if len(ok) == 1 else None else: sol = orbits_reach(Ies, branches, U, Z, tmp, gens, list(pins.items())) @@ -633,8 +668,7 @@ def face_reach(b, pins, Z, gens, limit_only=False): back = [(spy.Symbol(t), e) for t, e in zip(tmp, Ies)] for c, e in at0.items(): th = spy.cancel(spy.together(e.subs(back))) - if _bad(e) or _bad(th) or (sgn(th) != 1 if not is_real(c) else - sgn(spy.fraction(th)[1]) == 0): + if _bad(e) or _bad(th) or (sgn(th) != 1 if not is_real(c) else sgn(spy.fraction(th)[1]) == 0): return None return at0 except SYMPY_FAILS as exc: @@ -691,6 +725,7 @@ def face_state_limit(b, pins, Z, gens, states, degrees): from ..sym.invariants import verify_invariants from .blocks import solve_block from .expr import gen_prep + preps = [gen_prep({"generator": g}) for g in gens] if any(not p_["ok"] for p_ in preps): return False @@ -721,6 +756,7 @@ def rest_checked(rhs, Z, inputs, points=3): # a check without an error bound, with the inputs at 0; a point without a resting state is redrawn from ..gfp import verify_prime from ..sym.steady import solve_steady_state_modular + states = [x for x, f in rhs.items() if str(f).strip() not in ("0", "0.0")] syms = {str(s) for f in rhs.values() for s in spy.sympify(str(f).replace("^", "**")).free_symbols} params = sorted(syms - set(states) | {x for x in rhs if x not in states}) @@ -786,8 +822,11 @@ def face_section(b, pins, dens=()): out = {"solved": False} if not b.get("invariants") or any(re.search(r"exp\(|log\(", s) for s in b["invariants"]): return out - if b.get("face_invariants") is not None and len(b["face_invariants"]) == len(b["invariants"]) \ - and callable(b.get("face_back")): + if ( + b.get("face_invariants") is not None + and len(b["face_invariants"]) == len(b["invariants"]) + and callable(b.get("face_back")) + ): b2 = {k: v for k, v in b.items() if k not in ("invariants", "face_invariants", "face_back")} b2["invariants"] = b["face_invariants"] res = face_section(b2, pins, dens) @@ -804,8 +843,7 @@ def face_section(b, pins, dens=()): z_cand = [s for s in z_cand if s in set(positive_set())] if len(z_cand) < r: return out - loc = red_locals(list(b["invariants"]) + supp + list(pins) + list(pins.values()) + - [f"{s}_si_f" for s in supp]) + loc = red_locals(list(b["invariants"]) + supp + list(pins) + list(pins.values()) + [f"{s}_si_f" for s in supp]) try: Ies = [red_sympify(iv.replace("^", "**"), loc) for iv in b["invariants"]] except SYMPY_FAILS as exc: @@ -825,6 +863,7 @@ def zero_ok(sub): if e.is_zero or _bad(e): return False return True + z_cand = [v for v in z_cand if zero_ok([(spy.Symbol(v), spy.Integer(0))])] if len(z_cand) < r: return out @@ -935,16 +974,27 @@ def zero_ok(sub): if not id_face: continue res = dict(out) - res.update(solved=True, pins={z: "0" for z in Z}, gauge=Z, section=[f"{z} = 0" for z in Z], - face=True, coverage="total", solved_domain={}, inv_names=[], shifted=[], - meaning={v: str(spy.factor(e)).replace("**", "^") for v, e in zip(U, good)}) + res.update( + solved=True, + pins={z: "0" for z in Z}, + gauge=Z, + section=[f"{z} = 0" for z in Z], + face=True, + coverage="total", + solved_domain={}, + inv_names=[], + shifted=[], + meaning={v: str(spy.factor(e)).replace("**", "^") for v, e in zip(U, good)}, + ) return res for a in conditional: for c2 in conditional: if a["inv"] == c2["inv"] and a["sign"] == 1 and c2["sign"] == -1: - out["split"] = {"invariant": str(Ies[a["inv"]]).replace("**", "^"), - "positive": [f"{z} = 0" for z in a["face"]], - "negative": [f"{z} = 0" for z in c2["face"]]} + out["split"] = { + "invariant": str(Ies[a["inv"]]).replace("**", "^"), + "positive": [f"{z} = 0" for z in a["face"]], + "negative": [f"{z} = 0" for z in c2["face"]], + } return out return out @@ -1000,12 +1050,12 @@ def dz(e, a, b): def seen(v): return any(v in free_syms(e) for ex in E for e in ex.values()) + groups, used = {}, set() for v in supp: if not seen(v): continue - mem = [w for w in unmoved if w not in used and - all(dz(e, v, w) for ex in E for e in ex.values())] + mem = [w for w in unmoved if w not in used and all(dz(e, v, w) for ex in E for e in ex.values())] if mem: groups[v] = mem used |= set(mem) @@ -1028,8 +1078,13 @@ def seen(v): raise RouteError("translation group did not separate") keys = [U.get(k, k) for k in pr["comps"]] comps = dict(zip(keys, [str(e) for e in ex.values()])) - pr = dict(pr, comps=comps, support=keys, vars=sym_sort(list(dict.fromkeys(keys + list(left)))), - degree=prep_degree(comps)) + pr = dict( + pr, + comps=comps, + support=keys, + vars=sym_sort(list(dict.fromkeys(keys + list(left)))), + degree=prep_degree(comps), + ) new_preps.append(pr) bwd = [(spy.Symbol(U[v]), sum((spy.Symbol(x) for x in [v] + groups[v]), spy.Integer(0))) for v in groups] extra_names = list(U.values()) + list(groups) + [w for m in groups.values() for w in m] @@ -1041,18 +1096,31 @@ def back(invs): e = spy.sympify(iv.replace("^", "**"), locals=l2).subs(bwd) out.append(str(spy.factor(spy.together(e))).replace("**", "^")) return out + key_back = {u: v for v, u in U.items()} def back_prep(pr): l2 = red_locals(list(pr["comps"].values()) + extra_names) - comps = {key_back.get(k, k): str(spy.expand(spy.sympify(str(x).replace("^", "**"), locals=l2).subs(bwd))) - for k, x in pr["comps"].items()} + comps = { + key_back.get(k, k): str(spy.expand(spy.sympify(str(x).replace("^", "**"), locals=l2).subs(bwd))) + for k, x in pr["comps"].items() + } keys = list(comps) vs = {s for x in comps.values() for s in free_syms(spy.sympify(x, locals=l2))} - return dict(pr, comps=comps, support=keys, vars=sym_sort(list(dict.fromkeys(keys + list(vs)))), - degree=prep_degree(comps)) - return {"preps": new_preps, "back": back, "back_prep": back_prep, - "note": [" + ".join([v] + groups[v]) for v in groups]} + return dict( + pr, + comps=comps, + support=keys, + vars=sym_sort(list(dict.fromkeys(keys + list(vs)))), + degree=prep_degree(comps), + ) + + return { + "preps": new_preps, + "back": back, + "back_prep": back_prep, + "note": [" + ".join([v] + groups[v]) for v in groups], + } def unmoved_compress(preps): @@ -1086,6 +1154,7 @@ def gcdv(v): for x in v: g = math.gcd(g, abs(int(x))) return g + prim = [] for row in E: p_ = list(row // gcdv(row)) @@ -1105,6 +1174,7 @@ def coef_of(v, B): if par.shape[0] or any(not (x.is_Integer and x >= 0) for x in sol): return None return [int(x) for x in sol] + for p_ in prim: if coef_of(p_, B) is None: B.append(p_) @@ -1155,14 +1225,16 @@ def back(invs): def back_prep(pr): l2 = red_locals(list(pr["comps"].values()) + W + unmoved) - comps = {k: str(spy.expand(spy.sympify(str(x).replace("^", "**"), locals=l2).subs(bwd))) - for k, x in pr["comps"].items()} + comps = { + k: str(spy.expand(spy.sympify(str(x).replace("^", "**"), locals=l2).subs(bwd))) + for k, x in pr["comps"].items() + } vs = set(pr["support"]) | {s for x in comps.values() for s in free_syms(spy.sympify(x, locals=l2))} return dict(pr, comps=comps, vars=sym_sort(list(vs)), degree=prep_degree(comps)) + note = [] for k in range(len(B)): - parts = [unmoved[j] if Bm[k, j] == 1 else f"{unmoved[j]}^{int(Bm[k, j])}" - for j in np.nonzero(Bm[k] > 0)[0]] + parts = [unmoved[j] if Bm[k, j] == 1 else f"{unmoved[j]}^{int(Bm[k, j])}" for j in np.nonzero(Bm[k] > 0)[0]] note.append("*".join(parts)) return {"preps": new_preps, "back": back, "back_prep": back_prep, "note": note} @@ -1182,4 +1254,5 @@ def go(l, used): if go(l + 1, used | {v}): return True return False + return pick if go(0, frozenset()) else None diff --git a/src/symident/reduction/sign.py b/src/symident/reduction/sign.py index f9c1dbc..38c88be 100644 --- a/src/symident/reduction/sign.py +++ b/src/symident/reduction/sign.py @@ -34,15 +34,19 @@ def entry_class(e): def outside_bounds(entries, real=()): """Whether the coordinate values `entries` break a declared bound at a random point; a preference, not a proof.""" import random + if not DOMAIN.get("bounds"): return False from ..sym.parse import model_sympify + vals = {k: model_sympify(str(v)) for k, v in entries.items()} syms = sorted({x for v in vals.values() for x in v.free_symbols}, key=str) rng = random.Random(len(syms)) for _ in range(5): - pt = {x: spy.Rational(rng.randint(1, 50), rng.randint(1, 50)) * (rng.choice((1, -1)) if str(x) in real else 1) - for x in syms} + pt = { + x: spy.Rational(rng.randint(1, 50), rng.randint(1, 50)) * (rng.choice((1, -1)) if str(x) in real else 1) + for x in syms + } at = {spy.Symbol(k): v.xreplace(pt) for k, v in vals.items()} for h in DOMAIN["bounds"]: try: @@ -60,6 +64,7 @@ def inside_bounds(entries, invariants, names, support, tries=40): import random from ..sym.parse import model_sympify + bounds = [model_sympify(str(h)) for h in DOMAIN.get("bounds") or []] vals = {k: model_sympify(str(v)) for k, v in entries.items()} rng = random.Random(len(support)) @@ -90,6 +95,7 @@ def _numeric(Is, vals, names): def fn(e): xs = sorted(e.free_symbols, key=str) return spy.lambdify(xs, e, "math"), [str(x) for x in xs] + try: fI, fE = [fn(I) for I in Is], {k: fn(e) for k, e in vals.items()} except (SyntaxError, TypeError, NameError, *SYMPY_FAILS): @@ -108,6 +114,7 @@ def run(pt, need): return True except (ArithmeticError, ValueError, TypeError, KeyError): return False + return run @@ -116,6 +123,7 @@ def positive_somewhere(entries, invariants, names, support, tries=40): import random from ..sym.parse import model_sympify + vals = {k: model_sympify(str(v)) for k, v in entries.items()} rng = random.Random(len(support) + len(entries)) pos = positive_set() @@ -126,6 +134,7 @@ def positive_somewhere(entries, invariants, names, support, tries=40): def at(e, values): # by name: the symbols of the invariants and of the entries differ in their assumptions return e.xreplace({x: values[str(x)] for x in e.free_symbols if str(x) in values}) + # the orbit through a positive point of the coordinates the invariants read free = sorted(set(support) | {str(x) for e in Is for x in e.free_symbols}) for _ in range(tries): @@ -135,8 +144,10 @@ def at(e, values): continue try: sol = {k: at(v, {**pt, **{n: at(I, pt) for n, I in zip(names, Is)}}) for k, v in vals.items()} - ok = all(x.is_number and x.is_finite and x.is_real and (x > 0 or (pos is not None and k not in set(pos))) - for k, x in sol.items()) + ok = all( + x.is_number and x.is_finite and x.is_real and (x > 0 or (pos is not None and k not in set(pos))) + for k, x in sol.items() + ) except (ZeroDivisionError, TypeError, *SYMPY_FAILS): continue if ok: @@ -159,13 +170,11 @@ def positive_set_of(positive, coords): positive = [p for p in positive if p not in DOMAIN["bounds"]] unknown = [p for p in positive if p not in set(coords)] if unknown: - warnings.warn(f"no effect: {', '.join(unknown)}: not a coordinate of the analysis.", - stacklevel=2) + warnings.warn(f"no effect: {', '.join(unknown)}: not a coordinate of the analysis.", stacklevel=2) return [p for p in positive if p in set(coords)] -DOMAIN = {"positive": None, "real_carriers": [], "no_roots": False, "sgn_cache": None, - "bounds": []} +DOMAIN: dict = {"positive": None, "real_carriers": [], "no_roots": False, "sgn_cache": None, "bounds": []} @contextlib.contextmanager @@ -283,6 +292,7 @@ def sgn_poly(pp, depth=0): def anchored(c): # a real coordinate with even powers only vanishes somewhere: a positive term free of it keeps the sign strict return any(c[i] > 0 and not (fcols and np.any(expts[i, fcols])) for i in range(len(c))) + if np.all(cf > 0): return 1 if anchored(cf) else 0 if np.all(cf < 0): @@ -307,7 +317,7 @@ def _sqrt_below(x): """A rational at most sqrt(x) for a nonnegative Fraction x, within a part in 10^12.""" if x <= 0: return Fraction(0) - k = 10 ** 12 + k = 10**12 return Fraction(math.isqrt(x.numerator * x.denominator * k * k), x.denominator * k) @@ -328,7 +338,7 @@ def _absorb_exact(expts, cf): if take <= 0: continue lo, hi = take / (2 * bv), 2 * bu / take - t = min(hi, max(lo, Fraction(math.sqrt(bu / bv)).limit_denominator(10 ** 6))) + t = min(hi, max(lo, Fraction(math.sqrt(bu / bv)).limit_denominator(10**6))) bud[u], bud[v] = bu - take * t / 2, bv - take / (2 * t) need -= take if need == 0: @@ -397,8 +407,7 @@ def sgn_raw(pp, depth=0): s *= sa return s try: - rads = [w for w in ex.atoms(spy.Pow) if w.exp.is_Rational and not w.exp.is_Integer - and not w.base.is_number] + rads = [w for w in ex.atoms(spy.Pow) if w.exp.is_Rational and not w.exp.is_Integer and not w.base.is_number] except SYMPY_FAILS as exc: sympy_fail(exc) rads = [] @@ -435,7 +444,7 @@ def sgn_raw(pp, depth=0): continue if sa == 0: try: - d2 = spy.expand(cc ** 2 * s.base - a ** 2) + d2 = spy.expand(cc**2 * s.base - a**2) except SYMPY_FAILS as exc: sympy_fail(exc) d2 = None @@ -445,7 +454,7 @@ def sgn_raw(pp, depth=0): if sa == sc: return sa try: - d = spy.expand(a ** 2 - cc ** 2 * s.base) + d = spy.expand(a**2 - cc**2 * s.base) except SYMPY_FAILS as exc: sympy_fail(exc) continue @@ -615,6 +624,7 @@ def push(f): if k not in seen: seen.add(k) out.append(f) + form_seen = set() for e in [e0] + _forms(e0)[1:]: if e is None: @@ -694,6 +704,7 @@ def norm(e): except SYMPY_FAILS as exc: sympy_fail(exc) return e + es = [norm(e) for e in es] for _ in tmp_n: hit = find_one() @@ -743,7 +754,7 @@ def sgn_real(pp, real_syms): if a.is_zero: return sc try: - d2 = spy.expand(cc ** 2 * w.base - a ** 2) + d2 = spy.expand(cc**2 * w.base - a**2) except SYMPY_FAILS as exc: sympy_fail(exc) d2 = None @@ -761,7 +772,7 @@ def sgn_real(pp, real_syms): A = spy.expand(rest.coeff(ts, 2)) B = spy.expand(rest.coeff(ts, 1)) C = spy.expand(rest.coeff(ts, 0)) - chk = str(spy.expand(rest - (A * ts ** 2 + B * ts + C))) + chk = str(spy.expand(rest - (A * ts**2 + B * ts + C))) except SYMPY_FAILS as exc: sympy_fail(exc) return 0 @@ -771,7 +782,7 @@ def sgn_real(pp, real_syms): return 0 if sgn(A) != 1: return 0 - corr = corr + B ** 2 / (4 * A) + corr = corr + B**2 / (4 * A) rest = C try: red = spy.cancel(spy.together(rest - corr)) @@ -831,8 +842,11 @@ def translation_gauge(b, gauge): def translates(b, v, pinned): """Whether a direction of block `b` on real coordinates, free of `pinned` but `v`, translates `v`.""" for pr in b["preps"]: - if v not in pr["comps"] or not all(is_real(s) for s in pr["support"]) or \ - (set(pinned) - {v}) & set(pr["support"]): + if ( + v not in pr["comps"] + or not all(is_real(s) for s in pr["support"]) + or (set(pinned) - {v}) & set(pr["support"]) + ): continue loc = red_locals(list(pr["comps"].values())) try: diff --git a/src/symident/reduction/solve.py b/src/symident/reduction/solve.py index efd5c1d..98b81b0 100644 --- a/src/symident/reduction/solve.py +++ b/src/symident/reduction/solve.py @@ -126,9 +126,24 @@ def _memo_solve(b, pins, coords, inv_start, prefer_real, split_pair, gens, signe return _solve_invariants(*args) # the alternative reparametrizations of one reduction search equal blocks again; the work spent is replayed try: - key = pickle.dumps((b, pins, list(coords), inv_start, prefer_real, split_pair, gens, signed_ok, - DOMAIN["positive"], DOMAIN["bounds"], DOMAIN["no_roots"], DOMAIN["real_carriers"], - DOMAIN.get("work"), DOMAIN.get("work_cap"))) + key = pickle.dumps( + ( + b, + pins, + list(coords), + inv_start, + prefer_real, + split_pair, + gens, + signed_ok, + DOMAIN["positive"], + DOMAIN["bounds"], + DOMAIN["no_roots"], + DOMAIN["real_carriers"], + DOMAIN.get("work"), + DOMAIN.get("work_cap"), + ) + ) except (pickle.PicklingError, TypeError, AttributeError): return _solve_invariants(*args) memo = ses.__dict__.setdefault("solve_memo", {}) @@ -142,8 +157,7 @@ def _memo_solve(b, pins, coords, inv_start, prefer_real, split_pair, gens, signe return copy.deepcopy(res) -def _solve_invariants(b, pins, coords=(), inv_start=0, prefer_real=False, split_pair=None, gens=None, - signed_ok=False): +def _solve_invariants(b, pins, coords=(), inv_start=0, prefer_real=False, split_pair=None, gens=None, signed_ok=False): out = {"pins": None, "meaning": None, "solved": False} if not b.get("invariants"): return out @@ -171,6 +185,7 @@ def degs_in(p, v): except SYMPY_FAILS as exc: sympy_fail(exc) return None + pos = positive_set() adm = [] for Ie in Ies: @@ -194,6 +209,7 @@ def power_ok(frac, v): if dn is None or dd is None: return False return len(set(dn + dd) - {0}) == 1 + frac_g = spy.fraction(spy.cancel(spy.together(G))) if G is not None else None ok = [((v not in r_syms) and power_ok(frac_g, v)) if v in g_syms else power_ok(frac_r, v) for v in cand] a = [v for v, k in zip(cand, ok) if k] @@ -209,13 +225,15 @@ def power_ok(frac, v): DOMAIN["real_carriers"] = real_tmp try: if not signed_ok: - return _solve_invariants_inner(b, pins, coords, Ies, inv_n, carriers, tmp_n, real_tmp, loc, - split_pair, out, gens, signed_ok) + return _solve_invariants_inner( + b, pins, coords, Ies, inv_n, carriers, tmp_n, real_tmp, loc, split_pair, out, gens, signed_ok + ) # the constant pin under sign conditions: every gauge coordinate, the best section kept found = [] for cs in _carrier_choices(adm, b["support"], carriers): - res = _solve_invariants_inner(b, pins, coords, Ies, inv_n, cs, tmp_n, real_tmp, loc, - split_pair, dict(out), gens, signed_ok) + res = _solve_invariants_inner( + b, pins, coords, Ies, inv_n, cs, tmp_n, real_tmp, loc, split_pair, dict(out), gens, signed_ok + ) if res.get("solved"): found.append(res) if _section_rank(res) == (False, False, 0): @@ -234,6 +252,7 @@ def _section_chart(support, unknowns, es, pairs, tmp_n, inv_n, Ies, pins, pinned The new parameters are the free coordinates of the section point: the trafo is rational, and the section point of an orbit, solved from the invariants, gives their meaning. None where the balances do not solve so.""" from .sections import _linear_section + try: param = _linear_section(pairs) except SYMPY_FAILS as exc: @@ -257,9 +276,14 @@ def _section_chart(support, unknowns, es, pairs, tmp_n, inv_n, Ies, pins, pinned ent.update({v: q for v, q in zip(free, inv_n)}) back = {spy.Symbol(t): Ie for t, Ie in zip(tmp_n, Ies)} meaning = {q: str(es[v].xreplace(back)).replace("**", "^") for v, q in zip(free, inv_n)} - return {"pins": dict(ent, **{v: pins[v] for v in pinned}), "meaning": meaning, "shifted": [], - "root_note": None, "section_chart": True, - "solved_domain": {q: ("positive" if pos is None or v in set(pos) else "real") for v, q in zip(free, inv_n)}} + return { + "pins": dict(ent, **{v: pins[v] for v in pinned}), + "meaning": meaning, + "shifted": [], + "root_note": None, + "section_chart": True, + "solved_domain": {q: ("positive" if pos is None or v in set(pos) else "real") for v, q in zip(free, inv_n)}, + } def _split_sets(Ies, b, gauge0, cands, tried, own_of, touches): @@ -271,8 +295,9 @@ def _split_sets(Ies, b, gauge0, cands, tried, own_of, touches): prods = [p for p in split_products(Ies, b["support"]) if own_of(p) and touches(p)] if not prods: return [] - pool = prods if len(gauge0) == 1 else [[p, c] for i, p in enumerate(prods) for c in cands + prods[i + 1:] - if c != p] + pool = ( + prods if len(gauge0) == 1 else [[p, c] for i, p in enumerate(prods) for c in cands + prods[i + 1 :] if c != p] + ) sets = [[p] for p in pool] if len(gauge0) == 1 else pool sets = [st for st in sets if st not in tried][:SPLIT_SETS] loc = red_locals([x for g in preps for x in g["comps"].values()] + [x for st in sets for pr in st for x in pr]) @@ -304,14 +329,18 @@ def _section_rank(res): return (res.get("root_note") is not None, not res.get("injective"), len(res.get("sign_conditions") or [])) -def _solve_invariants_inner(b, pins, coords, Ies, inv_n, carriers, tmp_n, real_tmp, loc, split_pair, out, - gens=None, signed_ok=False): +def _solve_invariants_inner( + b, pins, coords, Ies, inv_n, carriers, tmp_n, real_tmp, loc, split_pair, out, gens=None, signed_ok=False +): best = best_root = signed = None eqs = [Ies[l] - spy.Symbol(tmp_n[l]) for l in range(len(Ies))] bezout = _bezout(eqs, carriers) if bezout > SOLVE_DEGREE_CAP: - session.note("limits", f"section search: the invariants of {', '.join(b['labels'])} give a system of " - f"degree up to {bezout} in the carriers, above {SOLVE_DEGREE_CAP}") + session.note( + "limits", + f"section search: the invariants of {', '.join(b['labels'])} give a system of " + f"degree up to {bezout} in the carriers, above {SOLVE_DEGREE_CAP}", + ) out["reason"] = f"the system of the invariants has degree up to {bezout}, above the cap {SOLVE_DEGREE_CAP}" return out sol_carr = _carrier_branches(eqs, carriers, bezout) @@ -321,9 +350,11 @@ def _solve_invariants_inner(b, pins, coords, Ies, inv_n, carriers, tmp_n, real_t def reaches(): if not reach: ok = gens is not None and sol_carr is not None and not set(pins_in) & set(b["support"]) - reach.append(ok and orbits_reach(Ies, sol_carr, carriers, gauge_all, tmp_n, gens, - list(pins_in.items())) is not None) + reach.append( + ok and orbits_reach(Ies, sol_carr, carriers, gauge_all, tmp_n, gens, list(pins_in.items())) is not None + ) return reach[0] + pos = positive_set() g_pos = gauge_all if pos is None else [v for v in gauge_all if v in set(pos)] keep_sets, cut = [], [] @@ -349,8 +380,8 @@ def keep_ok(k): pr = [v for v in gauge_all if v not in k and is_real(v)] kr = [v for v in k if is_real(v)] rest = [v for v in gauge_all if v not in k] - return (not pr or all(translates(b, v, rest) for v in pr)) and \ - not any(translates(b, v, gauge_all) for v in kr) + return (not pr or all(translates(b, v, rest) for v in pr)) and not any(translates(b, v, gauge_all) for v in kr) + keep_sets = [k for k in keep_sets if keep_ok(k)] pins_in = dict(pins) eqs_in = eqs @@ -359,6 +390,7 @@ def keep_ok(k): def subs_of(vals): return [(spy.Symbol(v), e) for v, e in vals.items()] + # the pass with sign conditions tries the constant pin only for gauge0 in [] if signed_ok else keep_sets: if best_root is not None or work_up(): @@ -372,9 +404,13 @@ def subs_of(vals): scal_pin_pairs = [(spy.Symbol(nm), red_sympify(v, loc)) for nm, v in pins.items()] all_unk = list(carriers) + list(gauge0) inv_syms = list(dict.fromkeys(s for Ie in Ies for s in free_syms(Ie))) - sec_vars = [v for v in sym_sort(list(dict.fromkeys( - b["support"] + ([s for s in inv_syms if s in set(coords)] if coords else inv_syms)))) - if v not in pinned1] + sec_vars = [ + v + for v in sym_sort( + list(dict.fromkeys(b["support"] + ([s for s in inv_syms if s in set(coords)] if coords else inv_syms))) + ) + if v not in pinned1 + ] summands = [inv_summands(Ie) for Ie in Ies] share_sets = [] if len(gauge0) > 2: @@ -391,8 +427,10 @@ def subs_of(vals): def touches(pr): txt = " ".join(pr) - return any(re.search(r"(?= len(gauge0)): + if all(k in ok_keys for k in ks) and ( + rows is None or pt_rank([rows[ok_keys.index(k)] for k in ks]) >= len(gauge0) + ): sets.append(st) elif len(gauge0) == 1: sets = [[c] for c in cands] @@ -449,8 +487,11 @@ def pt_rank(M): n_c = min(len(cands), 10) if rows is None else len(cands) if n_c < len(cands): cut.append(f"pairs of the balances past the first {n_c} are not tried") - sets = [[cands[i], cands[j]] for i, j in itertools.combinations(range(n_c), 2) - if rows is None or pt_rank([rows[i], rows[j]]) >= len(gauge0)] + sets = [ + [cands[i], cands[j]] + for i, j in itertools.combinations(range(n_c), 2) + if rows is None or pt_rank([rows[i], rows[j]]) >= len(gauge0) + ] sets.sort(key=lambda st: not all(own_of(pr) for pr in st)) else: sets = [] @@ -496,6 +537,7 @@ def vanishes(e): except SYMPY_FAILS as exc: sympy_fail(exc) return None + for e in eqs + sec_eqs: try: fr = spy.fraction(spy.together(e)) @@ -509,6 +551,7 @@ def vanishes(e): def sec_positive(st): sy = {m for pr in st for x in pr for m in ident_re.findall(x)} return bool(sy) and (pos is None or sy <= set(pos)) + n_try = 40 + sum(not own_of(st[0]) for st in sets) if len(gauge0) == 1 else 40 if len(sets) > n_try: cut.append(f"{len(sets) - n_try} of {len(sets)} sets of balances are not tried") @@ -592,24 +635,46 @@ def sec_positive(st): cand["section"] = secs + [f"{v} = {pins[v]}" for v in pinned1] cand["monotone"] = b.get("preps") is not None and st not in jac_sets cand["jacobian"] = st in jac_sets - cand["root_note"] = ("a solved entry contains a square root; the branch is the " - "certified positive one") if has_root else None + cand["root_note"] = ( + ("a solved entry contains a square root; the branch is the certified positive one") + if has_root + else None + ) cand["meaning"] = shifted_meaning(b["invariants"], inv_n, tmp_n, sh) cand["shifted"] = [inv_n[tmp_n.index(t)] for t in sh["shift"]] cand["inv_names"] = inv_n cand["solved"] = True cand["coverage"] = "partial" if partial else "total" cand["unproven_entries"] = [f"{v} = {ent[v]}" for v in unproven] - cand["solved_domain"] = {inv_n[l]: ("real" if tmp_n[l] in real_br else "positive") - for l in range(len(tmp_n))} + cand["solved_domain"] = { + inv_n[l]: ("real" if tmp_n[l] in real_br else "positive") for l in range(len(tmp_n)) + } cand["injective"] = section_injective( - Ies, {v: br[v] for v in all_unk}, tmp_n, scal_pin_pairs, - [(red_sympify(pr[0], loc), red_sympify(pr[1], loc)) for pr in st]) + Ies, + {v: br[v] for v in all_unk}, + tmp_n, + scal_pin_pairs, + [(red_sympify(pr[0], loc), red_sympify(pr[1], loc)) for pr in st], + ) cand["reach"] = reaches() if has_root and not partial and cand["injective"] and state.get("section_charts"): - sc = _section_chart(b["support"], all_unk, es, [(red_sympify(pr[0], loc).subs( - scal_pin_pairs), red_sympify(pr[1], loc).subs(scal_pin_pairs)) for pr in st], - tmp_n, inv_n, Ies, pins, pinned1) + sc = _section_chart( + b["support"], + all_unk, + es, + [ + ( + red_sympify(pr[0], loc).subs(scal_pin_pairs), + red_sympify(pr[1], loc).subs(scal_pin_pairs), + ) + for pr in st + ], + tmp_n, + inv_n, + Ies, + pins, + pinned1, + ) if sc is not None: cand.update(sc) return cand @@ -670,8 +735,12 @@ def sec_positive(st): if e is None: with carriers_real([]): e = pos_form(pinned[c]) - if e is None and signed_ok and not is_real(c) \ - and not pinned[c].has(spy.zoo, spy.nan, spy.oo, spy.S.NegativeInfinity): + if ( + e is None + and signed_ok + and not is_real(c) + and not pinned[c].has(spy.zoo, spy.nan, spy.oo, spy.S.NegativeInfinity) + ): e = pinned[c] unsigned.append(c) if e is None: @@ -689,6 +758,7 @@ def sec_positive(st): if unsigned and seen is None: ok_pin = False if ok_pin: + def to_inv(v): out2 = {} for k, x in v.items(): @@ -696,6 +766,7 @@ def to_inv(v): x = re.sub(r"\b" + tmp_n[l] + r"\b", inv_n[l], x) out2[k] = x.replace("**", "^") return out2 + cand = dict(out) cand["pins"] = dict(to_inv(entries), **to_inv(gp)) cand["gauge"] = gauge @@ -703,17 +774,24 @@ def to_inv(v): cand["shifted"] = [inv_n[tmp_n.index(t)] for t in (sh["shift"] if sh else {})] cand["inv_names"] = inv_n cand["solved"] = True - cand["root_note"] = ("a solved entry contains a square root; the branch is the " - "certified positive one") if root else None + cand["root_note"] = ( + ("a solved entry contains a square root; the branch is the certified positive one") + if root + else None + ) cand["coverage"] = "partial" if partial else "total" cand["sign_conditions"] = [f"{to_inv(entries)[c]} > 0" for c in unsigned] cand["sign_witness"] = seen - cand["solved_domain"] = {inv_n[l]: ("real" if tmp_n[l] in real_pin else "positive") - for l in range(len(tmp_n))} + cand["solved_domain"] = { + inv_n[l]: ("real" if tmp_n[l] in real_pin else "positive") for l in range(len(tmp_n)) + } const = all(re.fullmatch(r"[0-9.]+", v) for v in gp.values()) cand["injective"] = section_injective( - Ies, dict(zip(carriers, es)), tmp_n, pin_pairs if const else - [(spy.Symbol(nm), red_sympify(v, pin_loc)) for nm, v in pins.items()]) + Ies, + dict(zip(carriers, es)), + tmp_n, + pin_pairs if const else [(spy.Symbol(nm), red_sympify(v, pin_loc)) for nm, v in pins.items()], + ) cand["reach"] = reaches() if not partial and not root: return cand @@ -741,6 +819,8 @@ def to_inv(v): tried = " (skipped, no gauge coordinate)" elif len(gauge0) > 2: tried = f" with {len(gauge0)} gauge coordinates, the surplus pinned" - out["reason"] = (f"no gauge section with entries certified positive on the whole {domain_name()} " - f"(tried: monomial balances{tried}, then the constant pin)") + out["reason"] = ( + f"no gauge section with entries certified positive on the whole {domain_name()} " + f"(tried: monomial balances{tried}, then the constant pin)" + ) return out diff --git a/src/symident/reduction/zero.py b/src/symident/reduction/zero.py index 07cc300..d9ae420 100644 --- a/src/symident/reduction/zero.py +++ b/src/symident/reduction/zero.py @@ -24,8 +24,11 @@ def ineq_str(e): neg = [t.startswith("-") for t in tm] if all(neg) or not any(neg): return None - return (" + ".join(t for t, n in zip(tm, neg) if not n) + " > " + - " + ".join(re.sub(r"^-", "", t) for t, n in zip(tm, neg) if n)) + return ( + " + ".join(t for t, n in zip(tm, neg) if not n) + + " > " + + " + ".join(re.sub(r"^-", "", t) for t, n in zip(tm, neg) if n) + ) def condition(e): @@ -174,6 +177,7 @@ def vanishes(e): except SYMPY_FAILS as exc: sympy_fail(exc) return False + if not all(vanishes(e) for e in f["eqs"]): continue cnd, dead, opn = [], [], False @@ -198,9 +202,10 @@ def vanishes(e): if opn: unclear = True continue - parts = [f"{z} = 0" for z in Z] + \ - [f"{o} = " + ("(free)" if fr_ else str(vals[u]).replace("**", "^")) - for o, u, fr_ in zip(f["other"], f["unk"], free)] + parts = [f"{z} = 0" for z in Z] + [ + f"{o} = " + ("(free)" if fr_ else str(vals[u]).replace("**", "^")) + for o, u, fr_ in zip(f["other"], f["unk"], free) + ] at = ", ".join(parts) for u, p in pv.items(): at = re.sub(r"\b" + p + r"\b", f"{u}'", at) @@ -208,6 +213,7 @@ def vanishes(e): if grow: return {"verdict": "grow", "grow": grow} return {"verdict": "no" if info["complete"] and not unclear else "unknown"} + rows, seen = [], set() for v0 in supp: Z = [v0] @@ -226,15 +232,29 @@ def vanishes(e): seen.add(key) if b.get("face") and key == ", ".join(sym_sort(b.get("transversal") or [])): continue - rows.append({"coordinates": key, "verdict": a["verdict"], - "limit": _any3(darboux_(z) for z in Z) if a["verdict"] in ("yes", "if") else None, - "certain": certain or a["verdict"] == "no", - "condition": a.get("condition") or "", "at": a.get("at") or ""}) + rows.append( + { + "coordinates": key, + "verdict": a["verdict"], + "limit": _any3(darboux_(z) for z in Z) if a["verdict"] in ("yes", "if") else None, + "certain": certain or a["verdict"] == "no", + "condition": a.get("condition") or "", + "at": a.get("at") or "", + } + ) if b.get("face") and b.get("transversal"): Z = sym_sort(b["transversal"]) sm = b.get("new_parameters") or {} pins_inv = {v: k for k, v in (b.get("pins") or {}).items()} parts = [f"{z} = 0" for z in Z] + [f"{pins_inv.get(cn, cn)} = {m}" for cn, m in sm.items()] - rows = [{"coordinates": ", ".join(Z), "verdict": "yes", "limit": False, "certain": True, - "condition": "", "at": ", ".join(parts)}] + rows + rows = [ + { + "coordinates": ", ".join(Z), + "verdict": "yes", + "limit": False, + "certain": True, + "condition": "", + "at": ", ".join(parts), + } + ] + rows return rows or None diff --git a/src/symident/report.py b/src/symident/report.py index a89f6e2..4a5e114 100644 --- a/src/symident/report.py +++ b/src/symident/report.py @@ -32,8 +32,7 @@ def _split_terms(s): while j >= 0 and s[j] == " ": j -= 1 prev = s[j] if j >= 0 else "" - if re.match(r"^[A-Za-z0-9_.)]$", prev) and not ( - prev in "eE" and j > 0 and re.match(r"^[0-9.]$", s[j - 1])): + if re.match(r"^[A-Za-z0-9_.)]$", prev) and not (prev in "eE" and j > 0 and re.match(r"^[0-9.]$", s[j - 1])): out.append(s[start:i]) start = i out.append(s[start:]) @@ -41,8 +40,7 @@ def _split_terms(s): def _signed_terms(s): - return [("- " if x.startswith("-") else "+ ") + re.sub(r"^[+-]", "", x).strip() - for x in _split_terms(s)] + return [("- " if x.startswith("-") else "+ ") + re.sub(r"^[+-]", "", x).strip() for x in _split_terms(s)] def format_generator(gen, indent, width): @@ -73,10 +71,10 @@ def format_generator(gen, indent, width): def _labels(syms): from .detection.classify import direction_order + sub = "₀₁₂₃₄₅₆₇₈₉" order = direction_order(syms) - return [syms[i] for i in order], ["X" + "".join(sub[int(c)] for c in str(k + 1)) - for k in range(len(syms))] + return [syms[i] for i in order], ["X" + "".join(sub[int(c)] for c in str(k + 1)) for k in range(len(syms))] def generators_lines(res, verbose=False, width=None): @@ -88,13 +86,15 @@ def generators_lines(res, verbose=False, width=None): out = ["Generators X = Σᵢ ξ(i) ∂ᵢ", ""] lw = max(len(l) for l in labels) from .detection.classify import orbit_kind + cur = "" for d, lab in zip(syms, labels): kind = d.get("kind") or orbit_kind(d) or "none" if kind != cur: cur = kind - out.append({"scaling": "Scalings", "translation": "Translations", "curved": "Curved", - "none": "Open"}[cur] + ":") + out.append( + {"scaling": "Scalings", "translation": "Translations", "curved": "Curved", "none": "Open"}[cur] + ":" + ) lead = f" {lab.ljust(lw)} " ind = " " * len(lead) if d.get("generator") is None: @@ -115,21 +115,32 @@ def generators_lines(res, verbose=False, width=None): out += [_wrap("exact = proven over Q.", "", width)] b = (res.get("info") or {}).get("bound") if "verified" in levels: - out += [_wrap("verified = in the kernel at random points modulo a large prime, not proven; a wrong " - f"closed form passes with probability at most {b['probability']:.1e}. info['proof'] " - "says why it is not proven.", "", width)] + out += [ + _wrap( + "verified = in the kernel at random points modulo a large prime, not proven; a wrong " + f"closed form passes with probability at most {b['probability']:.1e}. info['proof'] " + "says why it is not proven.", + "", + width, + ) + ] if "checked" in levels: why = f" ({b['why']})" if isinstance(b, dict) and b.get("why") else "" - out += [_wrap("checked = in the kernel at random points modulo a large prime, with no bound on the " - f"chance that a wrong closed form passes{why}.", "", width)] + out += [ + _wrap( + "checked = in the kernel at random points modulo a large prime, with no bound on the " + f"chance that a wrong closed form passes{why}.", + "", + width, + ) + ] if levels & {"exact", "verified", "checked"}: out.append("") return out def _wrap(text, indent, width): - return textwrap.fill(text, width=max(40, width - 2), initial_indent=indent, - subsequent_indent=indent) + return textwrap.fill(text, width=max(40, width - 2), initial_indent=indent, subsequent_indent=indent) def reduction_hint_lines(res, width=None): @@ -143,15 +154,31 @@ def reduction_hint_lines(res, width=None): sl = [l for l, s in zip(labels, is_scal) if s] gl = [l for l, s in zip(labels, is_scal) if not s] if sl: - out.append(_wrap(", ".join(sl) + (" is a scaling: gauge it by holding any one of the coordinates " - "fixed, at any value." if len(sl) == 1 else - " are scalings: gauge them by holding one coordinate of each " - "fixed, at any value."), " ", width)) + out.append( + _wrap( + ", ".join(sl) + + ( + " is a scaling: gauge it by holding any one of the coordinates fixed, at any value." + if len(sl) == 1 + else " are scalings: gauge them by holding one coordinate of each fixed, at any value." + ), + " ", + width, + ) + ) if gl: - out.append(_wrap(", ".join(gl) + (" is not a scaling: reparametrize onto the invariants with " - "reduce()." if len(gl) == 1 else - " are not scalings: reparametrize onto their invariants with " - "reduce()."), " ", width)) + out.append( + _wrap( + ", ".join(gl) + + ( + " is not a scaling: reparametrize onto the invariants with reduce()." + if len(gl) == 1 + else " are not scalings: reparametrize onto their invariants with reduce()." + ), + " ", + width, + ) + ) return out @@ -162,23 +189,37 @@ def _status_lines(res, width): if not isinstance(rs, dict) or rs.get("status") not in ("verified", "lower bound"): return [] if rs["status"] == "lower bound": - tail = "there may be fewer non-identifiable directions" if res["rank"] < res["dim"] else \ - "the full rank may hold at this point only" + tail = ( + "there may be fewer non-identifiable directions" + if res["rank"] < res["dim"] + else "the full rank may hold at this point only" + ) return [_wrap(f"The rank is a lower bound ({rs['why']}): {tail}.", " ", width)] prob = rs.get("probability") if info.get("rank_fields") is not None: - return [_wrap(f"The rank is verified, not proven: the {rs['why']}" + - (f" (probability of a wrong pass at most {prob:.1e})." if prob is not None else "."), - " ", width)] + return [ + _wrap( + f"The rank is verified, not proven: the {rs['why']}" + + (f" (probability of a wrong pass at most {prob:.1e})." if prob is not None else "."), + " ", + width, + ) + ] pj = info.get("projection") or {} - risks = ["a verified closed form is wrong"] if (rs.get("why") or "").startswith("every direction is closed") \ - else [] + risks = ["a verified closed form is wrong"] if (rs.get("why") or "").startswith("every direction is closed") else [] if pj.get("status") == "verified": - risks.append(f"the columns of {pj.get('of', 'the unknown inputs')} drop rank at the random point that " - "checked them") - return [_wrap("The rank is verified, not proven: it holds unless " + - " or ".join(risks or ["a verified closed form is wrong"]) + - (f" (probability at most {prob:.1e})." if prob is not None else "."), " ", width)] + risks.append( + f"the columns of {pj.get('of', 'the unknown inputs')} drop rank at the random point that checked them" + ) + return [ + _wrap( + "The rank is verified, not proven: it holds unless " + + " or ".join(risks or ["a verified closed form is wrong"]) + + (f" (probability at most {prob:.1e})." if prob is not None else "."), + " ", + width, + ) + ] def result_lines(res, verbose=False, width=None, fixing=False): @@ -187,15 +228,18 @@ def result_lines(res, verbose=False, width=None, fixing=False): is_obs = res["method"] == "observability" n = len(res["symmetries"]) if is_obs and res.get("identifiable"): - return [f"Result: structurally locally identifiable (rank {res['rank']} / {res['dim']})"] + \ - _status_lines(res, width) + return [f"Result: structurally locally identifiable (rank {res['rank']} / {res['dim']})"] + _status_lines( + res, width + ) sw = ((res.get("info") or {}).get("switching") or {}) if is_obs else {} cands, unc = sw.get("candidates") or [], sw.get("uncertified") if is_obs: more = res["dim"] - res["rank"] - n - out = [f"Result: rank {res['rank']} / {res['dim']} | " - f"{plural(n, 'non-identifiable direction', 'non-identifiable directions')}" + - (f", up to {more} more" if more > 0 and (cands or unc) else "")] + out = [ + f"Result: rank {res['rank']} / {res['dim']} | " + f"{plural(n, 'non-identifiable direction', 'non-identifiable directions')}" + + (f", up to {more} more" if more > 0 and (cands or unc) else "") + ] out += _status_lines(res, width) out.append("") else: @@ -221,38 +265,70 @@ def global_lines(res, width=None): k = info.get("count") dom = sorted({c["in_domain"] for c in info.get("counts") or [] if c.get("in_domain") is not None}) route = (info.get("certificate") or {}).get("route") - order = f"{route['experiments']} experiments, order {max(route['orders'])}" if route else \ - f"order {info.get('order')}" - head = (f"{k} over the algebraic closure" if k is not None else "no finite count") + \ - (f", {' or '.join(map(str, dom))} in the domain" if dom else "") + \ - f" ({order}" + (f", gap order {info['gap_order']}" if info.get("gap_order") else "") + \ - (", stable)" if info.get("order_stable") else ")") + order = ( + f"{route['experiments']} experiments, order {max(route['orders'])}" if route else f"order {info.get('order')}" + ) + head = ( + (f"{k} over the algebraic closure" if k is not None else "no finite count") + + (f", {' or '.join(map(str, dom))} in the domain" if dom else "") + + f" ({order}" + + (f", gap order {info['gap_order']}" if info.get("gap_order") else "") + + (", stable)" if info.get("order_stable") else ")") + ) where = " of the reduced model" if info.get("reduced") else "" - out = ["", f"Global: values{where} with the output of a generic one, counted at random points", - _wrap(head, " ", width)] + out = [ + "", + f"Global: values{where} with the output of a generic one, counted at random points", + _wrap(head, " ", width), + ] cert = info.get("certificate") or {} if k is not None: cb = cert.get("count_bound") - text = (f"exactly {k} values at a generic point, proven" if cert.get("complete") == "exact" else - f"at most {k} values at a generic point, error bound {cb:.3g}" if cb is not None else - "the count at a generic point rests on the axiom of the count" + - (f" ({cert['count_bound_why']})" if cert.get("count_bound_why") else "")) + text = ( + f"exactly {k} values at a generic point, proven" + if cert.get("complete") == "exact" + else f"at most {k} values at a generic point, error bound {cb:.3g}" + if cb is not None + else "the count at a generic point rests on the axiom of the count" + + (f" ({cert['count_bound_why']})" if cert.get("count_bound_why") else "") + ) out.append(_wrap(text, " ", width)) if route: - out.append(_wrap("counted on experiments with shared parameters and free starts; no rational first " - "integral, proven at one point of the parameters", " ", width)) + out.append( + _wrap( + "counted on experiments with shared parameters and free starts; no rational first " + "integral, proven at one point of the parameters", + " ", + width, + ) + ) pin = cert.get("pinned") or {} if not route and pin.get("count_bound") is not None: rel = pin.get("relation") or {} some = [f for f in pin["functions"] if f in (rel.get("checks") or {})] if pin.get("relation_bound") else [] - out.append(_wrap(f"counted on {len(pin['functions'])} functions proven in the field of the output " - f"coefficients and the output coefficients up to order {max(pin['orders'].values())}" - + (f"; {len(some)} of the functions are coefficients of a relation of {rel.get('terms')} " - "terms, verified at random points" if some else ""), " ", width)) + out.append( + _wrap( + f"counted on {len(pin['functions'])} functions proven in the field of the output " + f"coefficients and the output coefficients up to order {max(pin['orders'].values())}" + + ( + f"; {len(some)} of the functions are coefficients of a relation of {rel.get('terms')} " + "terms, verified at random points" + if some + else "" + ), + " ", + width, + ) + ) for i, s in enumerate(res.get("discrete_symmetries") or [], 1): pd = s.get("preserves_domain") - side = "maps the domain into itself" if pd is True else "leaves the domain" if pd is False else \ - "in the domain where " + ", ".join(s.get("domain_conditions") or []) + side = ( + "maps the domain into itself" + if pd is True + else "leaves the domain" + if pd is False + else "in the domain where " + ", ".join(s.get("domain_conditions") or []) + ) m = ", ".join(f"{a} -> {b}" for a, b in s["map"].items()) out.append(_wrap(f"sigma{i} ({s['level']}): {m}; {side}", " ", width)) if info.get("fundamental_domain"): @@ -268,8 +344,11 @@ def candidate_lines(cands, width=None): out = ["Candidates, not proven (info['switching']['candidates']):"] for c in cands: gen = c.get("generator") - text = ", ".join(f"ξ({k}) = {v}" for k, v in gen.items()) if gen else \ - "support " + ", ".join(c.get("support") or []) + text = ( + ", ".join(f"ξ({k}) = {v}" for k, v in gen.items()) + if gen + else "support " + ", ".join(c.get("support") or []) + ) out.append(_wrap(text, " ", width)) return out @@ -279,66 +358,106 @@ def summary_lines(res, verbose=False, width=None): info = res["info"] s = info.get("settings") or {} is_obs = res["method"] == "observability" - eng = {"modular": "modular (GF(p) + CRT)", "symbolic": "symbolic (pure sympy)", - "integer-kernel": "integer kernel (exact)"}.get(info.get("engine"), str(info.get("engine"))) + eng = { + "modular": "modular (GF(p) + CRT)", + "symbolic": "symbolic (pure sympy)", + "integer-kernel": "integer kernel (exact)", + }.get(info.get("engine"), str(info.get("engine"))) bar = "-" * 60 out = [bar, f"detect | {'observability' if is_obs else 'scalings only'} engine: {eng}", bar] comp = [] if is_obs and info.get("lie_order_used") is not None: drv = info.get("lie_order_driver") - comp.append(f"Lie order {info['lie_order_used']} (gap order {info.get('gap_order_used') or 0})" + - (f", set by condition {drv + 1}" if drv is not None else "")) + comp.append( + f"Lie order {info['lie_order_used']} (gap order {info.get('gap_order_used') or 0})" + + (f", set by condition {drv + 1}" if drv is not None else "") + ) if is_obs and info.get("rank_proven") is not None: comp.append(f"rank: proven ({info['rank_proven']} directions, {info.get('rank_proof')})") elif is_obs and info.get("rank_fields") is not None: b = info.get("rank_fields_bound") or {} - comp.append((f"rank: verified ({info['rank_fields']} directions, invariant fields at random points, " - f"probability of a wrong pass at most {b['probability']:.1e})") - if b.get("probability") is not None else - f"rank: lower bound ({info['rank_fields']} directions, invariant fields at random points " - "without an error bound)") + comp.append( + ( + f"rank: verified ({info['rank_fields']} directions, invariant fields at random points, " + f"probability of a wrong pass at most {b['probability']:.1e})" + ) + if b.get("probability") is not None + else f"rank: lower bound ({info['rank_fields']} directions, invariant fields at random points " + "without an error bound)" + ) elif is_obs and info.get("lie_plateau") is not None: if info.get("lie_certified"): ob = info.get("order_bound") - comp.append("saturation: certified (every segment at the rank bound of the invariant space" + - ("" if ob == 0 else f"; sufficient except with probability at most {ob:.1e}" if ob is not None - else "; the random points of the certificate have no error bound" + - (f": {info['order_bound_why']}" if info.get("order_bound_why") else "")) + ")") + comp.append( + "saturation: certified (every segment at the rank bound of the invariant space" + + ( + "" + if ob == 0 + else f"; sufficient except with probability at most {ob:.1e}" + if ob is not None + else "; the random points of the certificate have no error bound" + + (f": {info['order_bound_why']}" if info.get("order_bound_why") else "") + ) + + ")" + ) elif info.get("lie_uncertified"): - comp.append("saturation: certified except condition " + - ", ".join(str(c + 1) for c in info["lie_uncertified"]) + " (rank bound not reached)") + comp.append( + "saturation: certified except condition " + + ", ".join(str(c + 1) for c in info["lie_uncertified"]) + + " (rank bound not reached)" + ) else: comp.append(f"saturation: provisional (plateau {info['lie_plateau']}, no rank bound reached)") gs = info.get("gauge_suggestion") if is_obs and res.get("gauge") is None and gs: - comp.append(f"gauge: fixing {', '.join(gs['gauge'])} leaves the general directions on " - f"{', '.join(map(str, gs['sizes']))} coordinates" + - (f" ({', '.join(gs['plain'])}: up to {max(gs['plain_sizes'])})" - if max(gs["plain_sizes"] or [0]) > max(gs["sizes"] or [0]) else "") + - "; gauge=None takes it") + comp.append( + f"gauge: fixing {', '.join(gs['gauge'])} leaves the general directions on " + f"{', '.join(map(str, gs['sizes']))} coordinates" + + ( + f" ({', '.join(gs['plain'])}: up to {max(gs['plain_sizes'])})" + if max(gs["plain_sizes"] or [0]) > max(gs["sizes"] or [0]) + else "" + ) + + "; gauge=None takes it" + ) if info.get("conditions") and info["conditions"] > 1: - comp.append(f"{plural(info['conditions'], 'condition', 'conditions')}, " - f"{plural(info['segments'], 'segment', 'segments')}") + comp.append( + f"{plural(info['conditions'], 'condition', 'conditions')}, " + f"{plural(info['segments'], 'segment', 'segments')}" + ) sel = info.get("selection") if sel: - comp.append(f"selection: {len(sel['kept'])} of {sel['conditions']} conditions analyzed, each direction proven " - "on the others (info['selection'])") + comp.append( + f"selection: {len(sel['kept'])} of {sel['conditions']} conditions analyzed, each direction proven " + "on the others (info['selection'])" + ) sw = info.get("switching") if sw: - comp.append("switches: " + ", ".join( - [plural(len(sw["surfaces"]), "surface", "surfaces"), - plural(len(sw["regimes"]), "regime", "regimes")] + - ([plural(len(sw["excluded"]), "excluded sign pattern", "excluded sign patterns")] - if sw.get("excluded") else [])) + " (info['switching']); a direction is free only where it is " - "free in every allowed regime, from any point of a switching surface") + comp.append( + "switches: " + + ", ".join( + [plural(len(sw["surfaces"]), "surface", "surfaces"), plural(len(sw["regimes"]), "regime", "regimes")] + + ( + [plural(len(sw["excluded"]), "excluded sign pattern", "excluded sign patterns")] + if sw.get("excluded") + else [] + ) + ) + + " (info['switching']); a direction is free only where it is " + "free in every allowed regime, from any point of a switching surface" + ) if info.get("zero_states"): - comp.append(f"states at zero: {', '.join(info['zero_states'])} start at zero and every regime keeps them " - "there, so the analysis runs without them (info['zero_states'])") + comp.append( + f"states at zero: {', '.join(info['zero_states'])} start at zero and every regime keeps them " + "there, so the analysis runs without them (info['zero_states'])" + ) for lim in info.get("limits") or []: comp.append(f"stopped: {lim}") if info.get("errors"): - comp.append(f"errors: {plural(len(info['errors']), 'exception', 'exceptions')} turned into failed " - "routes (info['errors'])") + comp.append( + f"errors: {plural(len(info['errors']), 'exception', 'exceptions')} turned into failed " + "routes (info['errors'])" + ) for b in info.get("branches") or []: comp.append(f"branch: {b}") keys = ["reduce_cq", "equilibrate", "reconstruct"] + (["verify", "sym_engine", "degree_cap"] if verbose else []) @@ -382,15 +501,18 @@ def _pairs(names, vals, width, ind=" "): out = [] for n, v in zip(names, vals): lead = f"{ind}{n.ljust(w)} = " - out.append(textwrap.fill(str(v), width=max(30, width), initial_indent=lead, - subsequent_indent=" " * len(lead))) + out.append(textwrap.fill(str(v), width=max(30, width), initial_indent=lead, subsequent_indent=" " * len(lead))) return out def partial_labels(x): """Labels of the removed directions whose section covers only part of the domain.""" - return [lab for b in x.get("blocks") or [] if b.get("coverage") == "partial" - and b.get("status") == "reduced" for lab in b.get("labels") or []] + return [ + lab + for b in x.get("blocks") or [] + if b.get("coverage") == "partial" and b.get("status") == "reduced" + for lab in b.get("labels") or [] + ] def _domain(x): @@ -404,12 +526,18 @@ def red_verdict(x): n_dir = len(x["removed"]) + len(x["remaining"]) part = partial_labels(x) dep = x.get("dependent") or [] - return (f"Reduced {len(x['removed'])} of {n_dir} direction{'' if n_dir == 1 else 's'}" + - (f" ({', '.join(x['remaining'])} remaining)" if x["remaining"] else "") + - (f"; {', '.join(dep)} {'depends' if len(dep) == 1 else 'depend'} on the others" if dep else "") + - (f"; the section of {', '.join(part)} covers only part of the {domain}" if part else "") + - ("; the closed loop does not confirm it" if ((x.get("checks") or {}).get("loop") or {}).get("ok") is False - else "") + ".") + return ( + f"Reduced {len(x['removed'])} of {n_dir} direction{'' if n_dir == 1 else 's'}" + + (f" ({', '.join(x['remaining'])} remaining)" if x["remaining"] else "") + + (f"; {', '.join(dep)} {'depends' if len(dep) == 1 else 'depend'} on the others" if dep else "") + + (f"; the section of {', '.join(part)} covers only part of the {domain}" if part else "") + + ( + "; the closed loop does not confirm it" + if ((x.get("checks") or {}).get("loop") or {}).get("ok") is False + else "" + ) + + "." + ) def red_chart_lines(x, width): @@ -427,8 +555,9 @@ def red_chart_lines(x, width): dom.update(b.get("solved_domain") or {}) if fresh: real = [dom.get(k) == "real" for k in fresh] - out += ["", "Invariants:"] + _pairs(list(fresh), [v + (" [real-valued]" if r else "") - for v, r in zip(fresh.values(), real)], width) + out += ["", "Invariants:"] + _pairs( + list(fresh), [v + (" [real-valued]" if r else "") for v, r in zip(fresh.values(), real)], width + ) if any(real): out.append(f" [real-valued] takes both signs on the {domain}; fit it linearly, not on a log scale") return out @@ -458,8 +587,10 @@ def _section_reason(b, what, domain): moved = ", ".join(b.get("support") or []) if b["type"] == "scaling": t = ", ".join(b.get("transversal") or []) - return [f"{labs} rescales {moved}: along an orbit each is multiplied by a power of one " - f"factor λ > 0, and {t} by a nonzero power. {what} therefore holds at exactly one λ."] + return [ + f"{labs} rescales {moved}: along an orbit each is multiplied by a power of one " + f"factor λ > 0, and {t} by a nonzero power. {what} therefore holds at exactly one λ." + ] out = [f"{labs} moves {moved}. Constant along each orbit:"] inv = b.get("new_parameters") or {} out += [(" ", k, v) for k, v in inv.items()] @@ -468,66 +599,91 @@ def _section_reason(b, what, domain): logs += [k for k, v in (b.get("pins") or {}).items() if v == "1"] t = ", ".join(b.get("transversal") or []) coords = f", taking the logarithm of {', '.join(logs)}," if logs else "" - out.append(f"In the moved coordinates{coords} every component of {labs} depends only on coordinates " - f"that {labs} does not move, so each orbit is an affine subspace on which every moved " - f"coordinate takes every real value. The components on {t} form a minor of one sign on the " - f"{domain}, so {what} holds at exactly one point of every orbit.") + out.append( + f"In the moved coordinates{coords} every component of {labs} depends only on coordinates " + f"that {labs} does not move, so each orbit is an affine subspace on which every moved " + f"coordinate takes every real value. The components on {t} form a minor of one sign on the " + f"{domain}, so {what} holds at exactly one point of every orbit." + ) return out sec = set(b.get("section") or []) pins = b.get("pins") or {} pt = {k: v for k, v in pins.items() if f"{k} = {v}" not in sec} real = [k for k, v in (b.get("solved_domain") or {}).items() if v == "real"] if b.get("face"): - out.append(f"A section that sets coordinates to 0 is preferred: each other coordinate then " - f"becomes one of the invariants. With {what} the invariants give") + out.append( + f"A section that sets coordinates to 0 is preferred: each other coordinate then " + f"becomes one of the invariants. With {what} the invariants give" + ) elif b.get("section") and b.get("injective") and len(b.get("transversal") or []) > 1: - out.append(f"Setting coordinates to 0 gives no point with all others positive on every orbit. " - f"The invariants determine each point with {what}, and two points of one orbit " - f"have the same invariants, so the orbit meets {what} at most once. With {what} " - f"the invariants give") + out.append( + f"Setting coordinates to 0 gives no point with all others positive on every orbit. " + f"The invariants determine each point with {what}, and two points of one orbit " + f"have the same invariants, so the orbit meets {what} at most once. With {what} " + f"the invariants give" + ) elif b.get("section") and (len(b.get("transversal") or []) > 1 or not b.get("section_monotone")): - out.append(f"Setting coordinates to 0 gives no point with all others positive on every orbit. " - f"That each orbit meets {what} at most once is not proven. With {what} the invariants " - f"give") + out.append( + f"Setting coordinates to 0 gives no point with all others positive on every orbit. " + f"That each orbit meets {what} at most once is not proven. With {what} the invariants " + f"give" + ) elif b.get("section"): - out.append(f"Setting coordinates to 0 gives no point with all others positive on every orbit. " - f"The ratio of the two sides of {what} changes in one direction only along " - f"each orbit ({labs} applied to the logarithm has a fixed sign), so the orbit meets " - f"{what} at most once. With {what} the invariants give") + out.append( + f"Setting coordinates to 0 gives no point with all others positive on every orbit. " + f"The ratio of the two sides of {what} changes in one direction only along " + f"each orbit ({labs} applied to the logarithm has a fixed sign), so the orbit meets " + f"{what} at most once. With {what} the invariants give" + ) else: - out.append(f"Neither setting coordinates to 0 nor a ratio of them gives a section. With {what} " - f"the invariants give") + out.append( + f"Neither setting coordinates to 0 nor a ratio of them gives a section. With {what} the invariants give" + ) out += [(" ", k, v) for k, v in pt.items()] if b.get("reach"): indep = f"{labs} vanishes nowhere" if len(b["labels"]) == 1 else f"{labs} are independent at every point" - out.append("The points with given invariants are one orbit: they are the graph of these values " - f"over a connected set of {', '.join(b.get('transversal') or [])}, and {indep}.") + out.append( + "The points with given invariants are one orbit: they are the graph of these values " + f"over a connected set of {', '.join(b.get('transversal') or [])}, and {indep}." + ) if b.get("coverage") == "partial" and b.get("sign_conditions"): - out.append(f"These values are positive where {', '.join(b['sign_conditions'])}; an orbit on which " - f"they are not may not reach {what} inside the {domain}, and the trafo does not " - f"represent it.") + out.append( + f"These values are positive where {', '.join(b['sign_conditions'])}; an orbit on which " + f"they are not may not reach {what} inside the {domain}, and the trafo does not " + f"represent it." + ) elif b.get("coverage") == "partial" and real: - out.append(f"These values are certified positive where {', '.join(real)} > 0; an orbit with other " - f"values of {', '.join(real)} may not reach {what} inside the {domain}, and the trafo " - f"does not represent it.") + out.append( + f"These values are certified positive where {', '.join(real)} > 0; an orbit with other " + f"values of {', '.join(real)} may not reach {what} inside the {domain}, and the trafo " + f"does not represent it." + ) elif b.get("coverage") == "partial": - out.append(f"These values are not certified positive for all values of the invariants; an orbit " - f"may not reach {what} inside the {domain}, and the trafo does not represent it.") + out.append( + f"These values are not certified positive for all values of the invariants; an orbit " + f"may not reach {what} inside the {domain}, and the trafo does not represent it." + ) elif b.get("unproven"): - out.append(f"The invariants determine these values uniquely, and they are positive for all " - f"values of the invariants. That every orbit in the {domain} has exactly one such " - f"point rests on the claims listed as unproven.") + out.append( + f"The invariants determine these values uniquely, and they are positive for all " + f"values of the invariants. That every orbit in the {domain} has exactly one such " + f"point rests on the claims listed as unproven." + ) elif b.get("face"): - out.append(f"The invariants determine these values uniquely, and they are positive for all " - f"values of the invariants. So every orbit in the {domain} approaches exactly one " - f"point with {what}, where the model is continuous, and that point gives the output " - f"of the orbit.") + out.append( + f"The invariants determine these values uniquely, and they are positive for all " + f"values of the invariants. So every orbit in the {domain} approaches exactly one " + f"point with {what}, where the model is continuous, and that point gives the output " + f"of the orbit." + ) if b.get("face_level") == "checked": out.append("The resting state there is checked at random points, without an error bound.") else: - out.append(f"The invariants determine these values uniquely, and they are positive for all " - f"values of the invariants. So every orbit in the {domain} contains " - f"exactly one point with {what}.") + out.append( + f"The invariants determine these values uniquely, and they are positive for all " + f"values of the invariants. So every orbit in the {domain} contains " + f"exactly one point with {what}." + ) if "square root" in (b.get("gauge_note") or ""): out.append("Of the two roots, the positive one is taken.") return out @@ -546,10 +702,18 @@ def red_section_lines(x, width, detailed=False, detail_call=DETAIL_CALL): out.append(f" {detail_call} explains each section.") return out ind = " " - out = ["", "Sections", textwrap.fill( - "A direction is removed by choosing one point on each orbit. The invariants are " - "constant along an orbit and become the new parameters; the section is the equation that " - "picks the point.", width=max(40, width), initial_indent=" ", subsequent_indent=" ")] + out = [ + "", + "Sections", + textwrap.fill( + "A direction is removed by choosing one point on each orbit. The invariants are " + "constant along an orbit and become the new parameters; the section is the equation that " + "picks the point.", + width=max(40, width), + initial_indent=" ", + subsequent_indent=" ", + ), + ] for lab, what, b in rows: out += ["", f" {lab} {what}"] pend = [] @@ -561,8 +725,7 @@ def red_section_lines(x, width, detailed=False, detail_call=DETAIL_CALL): out += _pairs([p[1] for p in pend], [p[2] for p in pend], width, ind + " ") pend = [] if item is not None: - out.append(textwrap.fill(item, width=max(40, width), initial_indent=ind, - subsequent_indent=ind)) + out.append(textwrap.fill(item, width=max(40, width), initial_indent=ind, subsequent_indent=ind)) return out @@ -576,6 +739,7 @@ def red_zero_lines(x, width): def parts(ix): return {p for i in ix for p in v[i]["coordinates"].split(", ")} + undecided = parts([i for i, r in enumerate(v) if open_f[i] or r["verdict"] == "unknown"]) - parts(hit) if not hit and not undecided: return [] @@ -583,8 +747,9 @@ def parts(ix): w = max([len(v[i]["coordinates"]) for i in hit] + [0]) for i in hit: r = v[i] - txt = ("everywhere" if r["verdict"] == "yes" else f"where {r['condition']}") + \ - (", in the limit" if r.get("limit") else "") + txt = ("everywhere" if r["verdict"] == "yes" else f"where {r['condition']}") + ( + ", in the limit" if r.get("limit") else "" + ) out.append(f" {r['coordinates'].ljust(w)} = 0 {txt}") if undecided: out.append(" undecided: " + ", ".join(sorted(undecided))) @@ -594,17 +759,23 @@ def parts(ix): def _level_lines(x, width): """Lines on the removed directions that rest on a verified closed form and on failed checks.""" out = [] - for lev, what in (("verified", "a verified closed form, checked modulo a prime with an error bound, " - "not proven"), - ("checked", "a closed form checked modulo a prime without an error bound")): - labs = [l for b in x.get("blocks") or [] if b.get("generator_level", b.get("level")) == lev - and b["status"] in ("reduced", "fixed") for l in b["labels"]] + for lev, what in ( + ("verified", "a verified closed form, checked modulo a prime with an error bound, not proven"), + ("checked", "a closed form checked modulo a prime without an error bound"), + ): + labs = [ + l + for b in x.get("blocks") or [] + if b.get("generator_level", b.get("level")) == lev and b["status"] in ("reduced", "fixed") + for l in b["labels"] + ] if labs: out.append(_wrap(f"The section of {', '.join(labs)} rests on {what}.", "", width)) for b in x.get("blocks") or []: if b.get("unproven") and b["status"] in ("reduced", "fixed"): - out.append(_wrap(f"{{{', '.join(b['labels'])}}} leaves unproven: " + "; ".join(b["unproven"]) + ".", - "", width)) + out.append( + _wrap(f"{{{', '.join(b['labels'])}}} leaves unproven: " + "; ".join(b["unproven"]) + ".", "", width) + ) ck = x.get("checks") or {} if ck.get("failed"): out.append(_wrap("Check failed over Q: " + "; ".join(ck["failed"]) + ".", "", width)) @@ -612,9 +783,16 @@ def _level_lines(x, width): if isinstance(lp, dict) and lp.get("directions") is None and lp.get("reason"): out.append(_wrap(f"Closed loop: {lp.get('reason')}.", "", width)) elif isinstance(lp, dict) and not lp.get("ok"): - out.append(_wrap(f"Closed loop: the reduced model has {plural(lp['directions'], 'direction', 'directions')}, " - f"{lp['expected']} expected (rank {lp['rank']} / {lp['dim']}, {lp['rank_status']})" + - (f"; {lp['reason']}" if lp.get("reason") else "") + ".", "", width)) + out.append( + _wrap( + f"Closed loop: the reduced model has {plural(lp['directions'], 'direction', 'directions')}, " + f"{lp['expected']} expected (rank {lp['rank']} / {lp['dim']}, {lp['rank_status']})" + + (f"; {lp['reason']}" if lp.get("reason") else "") + + ".", + "", + width, + ) + ) return out @@ -623,21 +801,32 @@ def reduction_lines(x, width=None, detail_call=DETAIL_CALL): width = _width(width) if not x["removed"] and not x["remaining"]: return ["Nothing to reduce."] + branch_lines(x, width) - out = [red_verdict(x)] + _level_lines(x, width) + red_chart_lines(x, width) + \ - red_section_lines(x, width, detail_call=detail_call) + red_input_lines(x, width) + red_zero_lines(x, width) + \ - branch_lines(x, width) + out = ( + [red_verdict(x)] + + _level_lines(x, width) + + red_chart_lines(x, width) + + red_section_lines(x, width, detail_call=detail_call) + + red_input_lines(x, width) + + red_zero_lines(x, width) + + branch_lines(x, width) + ) for b in x["blocks"]: if b["status"] in ("reduced", "fixed"): continue out.append("") - out.append("Not reduced: " + ", ".join(b["labels"]) + - (" | invariants: " + ", ".join(b["invariants"]) if b.get("invariants") else "")) + out.append( + "Not reduced: " + + ", ".join(b["labels"]) + + (" | invariants: " + ", ".join(b["invariants"]) if b.get("invariants") else "") + ) if b.get("reason"): out.append(_wrap(f"{b['reason']}.", " ", width)) if b.get("split"): sp = b["split"] - out.append(f" split orbits: {', '.join(sp['positive'])} where {sp['invariant']} > 0, " - f"{', '.join(sp['negative'])} where it is < 0") + out.append( + f" split orbits: {', '.join(sp['positive'])} where {sp['invariant']} > 0, " + f"{', '.join(sp['negative'])} where it is < 0" + ) return out @@ -649,11 +838,13 @@ def red_input_lines(x, width=None): if not ui or b.get("status") != "reduced": continue proof = ui["proof"] if isinstance(ui["proof"], str) else " and ".join(ui["proof"]) - how = {"inversion": "solved from the derivatives of the observables", "lift": "changed along a pointwise lift", - "inversion and lift": "solved from the observables or changed along a lift"}.get(proof, proof) + how = { + "inversion": "solved from the derivatives of the observables", + "lift": "changed along a pointwise lift", + "inversion and lift": "solved from the observables or changed along a lift", + }.get(proof, proof) groups.setdefault((", ".join(ui["absorb"]), how, ui["condition"]), []).extend(b["labels"]) - out = [_wrap(f"{{{', '.join(labs)}}} {w} {how}: {cond}.", " ", width) - for (w, how, cond), labs in groups.items()] + out = [_wrap(f"{{{', '.join(labs)}}} {w} {how}: {cond}.", " ", width) for (w, how, cond), labs in groups.items()] return ["", "Unknown inputs:"] + out if out else [] @@ -667,21 +858,31 @@ def branch_lines(x, width=None): chosen = (d.get("branch") or {}).get("branch") out = ["", "Branches (sides of the fixed set of the discrete symmetry):"] for b in bs: - (dl, dv), = b["new_parameters"].items() - (xk, xv), = b["solved"].items() + ((dl, dv),) = b["new_parameters"].items() + ((xk, xv),) = b["solved"].items() mark = " [trafo]" if b["branch"] == chosen else "" claims = "" if not b["unproven"] else "; unproven: " + ", ".join(u.split(":")[0] for u in b["unproven"]) out.append(_wrap(f"{b['branch']}: {xk} = {xv}, {dl} = {dv} > 0{claims}{mark}", " ", width)) - out.append(_wrap("boundary: " + ", ".join(bs[0]["boundary"]) + - ("" if chosen else "; reduce(branch=...) takes one as the trafo"), " ", width)) + out.append( + _wrap( + "boundary: " + + ", ".join(bs[0]["boundary"]) + + ("" if chosen else "; reduce(branch=...) takes one as the trafo"), + " ", + width, + ) + ) return out def _verbose_family_lines(fam, ind, width): """The possible choices, the matroid rows and the gauge note of a block.""" + def wrap(lead, items, sep=", "): - return textwrap.fill(lead + sep.join(items), width=max(40, width), initial_indent=ind, - subsequent_indent=ind + " " * len(lead)) + return textwrap.fill( + lead + sep.join(items), width=max(40, width), initial_indent=ind, subsequent_indent=ind + " " * len(lead) + ) + out = [] if fam.get("choices") is not None: out.append(wrap("choices ", ["{" + ",".join(T) + "}" for T in fam["choices"]])) @@ -700,9 +901,13 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail out = [bar, f"reduce | directions: {n_dir}", bar] if not n_dir: return out + ["Nothing to reduce."] - out += [red_verdict(x)] + red_chart_lines(x, width) + \ - red_section_lines(x, width, detailed=detailed, detail_call=detail_call) + red_input_lines(x, width) + \ - red_zero_lines(x, width) + out += ( + [red_verdict(x)] + + red_chart_lines(x, width) + + red_section_lines(x, width, detailed=detailed, detail_call=detail_call) + + red_input_lines(x, width) + + red_zero_lines(x, width) + ) out += ["", "Blocks"] rows = [] for b in x["blocks"]: @@ -713,8 +918,10 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail gauge = [] if b.get("removed_by_fixed"): k = b["removed_by_fixed"] - gauge.append(f"fixed removed {k} direction{'' if k == 1 else 's'}" + - (f" (redundant: {', '.join(b['redundant_fixed'])})" if b.get("redundant_fixed") else "")) + gauge.append( + f"fixed removed {k} direction{'' if k == 1 else 's'}" + + (f" (redundant: {', '.join(b['redundant_fixed'])})" if b.get("redundant_fixed") else "") + ) if b.get("section"): gauge.append(", ".join(b["section"])) elif b.get("transversal"): @@ -730,8 +937,7 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail gauge.append(f"matroid of {len(fam['matroid'])} row{'' if len(fam['matroid']) == 1 else 's'}") full = b["status"] not in ("reduced", "fixed") or verbose st = b.get("stage") - head = (f"{kind}, {b['status']}" + - (f" [{st}]" if st and st not in ("transversal", "fixed", "none") else "")) + head = f"{kind}, {b['status']}" + (f" [{st}]" if st and st not in ("transversal", "fixed", "none") else "") ind = " " more = [] if b.get("module_combos"): @@ -739,8 +945,14 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail if b.get("invariants") and full: more.append(ind + "invariants " + ", ".join(b["invariants"])) if b.get("reason"): - more.append(textwrap.fill("reason " + b["reason"], width=max(40, width), - initial_indent=ind, subsequent_indent=ind + " ")) + more.append( + textwrap.fill( + "reason " + b["reason"], + width=max(40, width), + initial_indent=ind, + subsequent_indent=ind + " ", + ) + ) if verbose: more += _verbose_family_lines(fam, ind, width) rows.append(("{" + ", ".join(b["labels"]) + "}", head, ", ".join(gauge), more)) @@ -751,9 +963,14 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail out.append((f" {lab.ljust(wl)} {head.ljust(wh)}" + (f" | {gauge}" if gauge else "")).rstrip()) out += more if x["remaining"]: - out += ["", textwrap.fill(f"Remaining: {', '.join(x['remaining'])} | options: a structural " - "assumption, a separating experiment, or prediction profiles.", - width=max(40, width))] + out += [ + "", + textwrap.fill( + f"Remaining: {', '.join(x['remaining'])} | options: a structural " + "assumption, a separating experiment, or prediction profiles.", + width=max(40, width), + ), + ] if x.get("fixed"): out += ["", "fixed coordinates stay identity entries; keep passing fixed= to downstream calls."] return out diff --git a/src/symident/rexpr.py b/src/symident/rexpr.py index 9cbe6b2..dc6bc02 100644 --- a/src/symident/rexpr.py +++ b/src/symident/rexpr.py @@ -6,16 +6,18 @@ from .errors import SYMPY_FAILS, InapplicableError -_TOKEN = re.compile(r""" +_TOKEN = re.compile( + r""" (?P\s+) | (?P0[xX][0-9a-fA-F]+L?|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?L?) | (?P[A-Za-z.][A-Za-z0-9._]*|`[^`]*`) | (?P"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*') | (?P\*\*|<=|>=|==|!=|&&|\|\||<-|->|%[^%]*%|[-+*/^(),<>!&|=\[\]{}:;~?$@]) -""", re.VERBOSE) +""", + re.VERBOSE, +) -_CONSTS = {"TRUE", "FALSE", "NULL", "NA", "Inf", "NaN", "NA_integer_", "NA_real_", - "NA_character_", "pi"} +_CONSTS = {"TRUE", "FALSE", "NULL", "NA", "Inf", "NaN", "NA_integer_", "NA_real_", "NA_character_", "pi"} _KEYWORDS = {"function", "if", "else", "for", "while", "repeat", "in", "next", "break"} @@ -110,8 +112,7 @@ def _replace_one(expr, table, bare): toks = tokens(expr) # a replacement that is the whole expression needs no parentheses sym = bare if len(toks) == 1 else table - return "".join((bare if k == "fun" else sym).get(t, t) if k in ("sym", "fun", "num") else t - for k, t in toks) + return "".join((bare if k == "fun" else sym).get(t, t) if k in ("sym", "fun", "num") else t for k, t in toks) def replace_symbols(what, by, x): @@ -142,6 +143,7 @@ def apply(e): if isinstance(e, (dict, list, str)) and len(e) == 0: return e return replace_symbols(keys, vals, e) + return apply @@ -171,11 +173,23 @@ def free_exponent_bases(exprs, states): _FUNS = { - "exp": math.exp, "log": lambda x, b=None: math.log(x) if b is None else math.log(x, b), - "log10": math.log10, "log2": math.log2, "sqrt": math.sqrt, "abs": abs, - "sin": math.sin, "cos": math.cos, "tan": math.tan, "sinh": math.sinh, - "cosh": math.cosh, "tanh": math.tanh, "exp10": lambda x: 10.0 ** x, - "max": max, "min": min, "pmax": max, "pmin": min, + "exp": math.exp, + "log": lambda x, b=None: math.log(x) if b is None else math.log(x, b), + "log10": math.log10, + "log2": math.log2, + "sqrt": math.sqrt, + "abs": abs, + "sin": math.sin, + "cos": math.cos, + "tan": math.tan, + "sinh": math.sinh, + "cosh": math.cosh, + "tanh": math.tanh, + "exp10": lambda x: 10.0**x, + "max": max, + "min": min, + "pmax": max, + "pmin": min, "ifelse": lambda c, a, b: a if c else b, } @@ -188,8 +202,9 @@ def to_python(expr): parts.append("**") elif kind == "num": t = text.rstrip("L") if text[-1:] == "L" and not text.startswith("0x") else text - parts.append({"TRUE": "True", "FALSE": "False", "Inf": "inf", "NaN": "nan", - "NA": "nan", "NULL": "None"}.get(t, t)) + parts.append( + {"TRUE": "True", "FALSE": "False", "Inf": "inf", "NaN": "nan", "NA": "nan", "NULL": "None"}.get(t, t) + ) elif kind == "op" and text in ("&&", "&"): parts.append(" and ") elif kind == "op" and text in ("||", "|"): diff --git a/src/symident/rjson.py b/src/symident/rjson.py index 9e1f456..a0cf362 100644 --- a/src/symident/rjson.py +++ b/src/symident/rjson.py @@ -40,10 +40,30 @@ def _dumps(x): return json.dumps(_clean(x), default=_default) -DETECT_ARGS = ("f", "g", "trafo", "conditions", "events", "reactions", "totals", "parameters", - "fixed", "forcings", "free_initial", "equilibrate", "reduce_cq", "reconstruct", - "verify", "positive", "sym_engine", "cores", "scalings_only", "regimes", "unknown_inputs", - "known_inputs") +DETECT_ARGS = ( + "f", + "g", + "trafo", + "conditions", + "events", + "reactions", + "totals", + "parameters", + "fixed", + "forcings", + "free_initial", + "equilibrate", + "reduce_cq", + "reconstruct", + "verify", + "positive", + "sym_engine", + "cores", + "scalings_only", + "regimes", + "unknown_inputs", + "known_inputs", +) def kwargs_of(spec): @@ -53,8 +73,9 @@ def kwargs_of(spec): gp = spec["gauge_preference"] kw["gauge_preference"] = None if gp == "AUTO" else gp if spec.get("control"): - kw["control"] = reconst_control(**{k: (math.inf if v == "Inf" else v) - for k, v in spec["control"].items() if v is not None}) + kw["control"] = reconst_control( + **{k: (math.inf if v == "Inf" else v) for k, v in spec["control"].items() if v is not None} + ) return kw @@ -89,9 +110,11 @@ def detect_json(spec, env=None): kw["reconstruct"] = True with _context(env), warnings.catch_warnings(record=True) as rec: warnings.simplefilter("always") - res = pivot_choice(lambda pivots, cq_pivots: symmetry_detection(**dict(kw, free_initial=pivots, - cq_pivots=cq_pivots)), - kw.get("free_initial"), bool(kw.get("reduce_cq"))) + res = pivot_choice( + lambda pivots, cq_pivots: symmetry_detection(**dict(kw, free_initial=pivots, cq_pivots=cq_pivots)), + kw.get("free_initial"), + bool(kw.get("reduce_cq")), + ) if mode == "global": res = _global(res, kw, sp.get("global_options")) if res.get("info") and res["info"].get("kernel") is not None: @@ -105,11 +128,22 @@ def detect_json(spec, env=None): def _global(res, kw, options): """The result `res` of the detection with `kw` after the global analysis on the model of `kw`.""" from .api import Model, Symmetries, global_step - model = Model(kw["f"], kw["g"], trafo=kw.get("trafo"), conditions=kw.get("conditions"), events=kw.get("events"), - inputs=kw.get("forcings") or (), unknown_inputs=kw.get("unknown_inputs") or (), - known_inputs=kw.get("known_inputs") or (), fixed=kw.get("fixed") or (), - parameters=kw.get("parameters") or (), reactions=kw.get("reactions"), totals=kw.get("totals"), - regimes=kw.get("regimes")) + + model = Model( + kw["f"], + kw["g"], + trafo=kw.get("trafo"), + conditions=kw.get("conditions"), + events=kw.get("events"), + inputs=kw.get("forcings") or (), + unknown_inputs=kw.get("unknown_inputs") or (), + known_inputs=kw.get("known_inputs") or (), + fixed=kw.get("fixed") or (), + parameters=kw.get("parameters") or (), + reactions=kw.get("reactions"), + totals=kw.get("totals"), + regimes=kw.get("regimes"), + ) sym = Symmetries(res, model) global_step(sym, options, int(kw.get("cores") or 1)) return sym._raw @@ -134,6 +168,7 @@ def reduce_json(obj, args, env=None): res = symmetry_reduction(o, **kw) finish_reduction(o, res) from .api import attach_discrete + attach_discrete(o, res, kw.get("positive"), branch) if check and isinstance(o.get("spec"), dict) and res.get("trafo") and o.get("method") == "observability": with _context(env), warnings.catch_warnings(): @@ -147,13 +182,29 @@ def _loop(spec, red, gauge): """The detection of `spec` with the trafo of the reduction applied: the directions found against the remaining ones.""" from .api import loop_outcome, reduced_model + want = len(red.get("remaining") or []) - rm = reduced_model(dict(spec.get("f") or {}), spec.get("g"), spec.get("trafo"), spec.get("conditions"), - spec.get("events"), red["trafo"], bool(spec.get("equilibrate"))) + rm = reduced_model( + dict(spec.get("f") or {}), + spec.get("g"), + spec.get("trafo"), + spec.get("conditions"), + spec.get("events"), + red["trafo"], + bool(spec.get("equilibrate")), + ) if rm["why"] is not None: return {"ok": None, "directions": None, "expected": want, "reason": "not run, " + rm["why"]} - s = dict(spec, reconstruct=False, trafo=rm["trafo"], conditions=rm["conditions"], - fixed=list(dict.fromkeys(list(spec.get("fixed") or []) + list(gauge or []) + - list(red.get("fixed") or []) + rm["fixed"]))) + s = dict( + spec, + reconstruct=False, + trafo=rm["trafo"], + conditions=rm["conditions"], + fixed=list( + dict.fromkeys( + list(spec.get("fixed") or []) + list(gauge or []) + list(red.get("fixed") or []) + rm["fixed"] + ) + ), + ) s.pop("gauge_preference", None) return loop_outcome(lambda: symmetry_detection(**kwargs_of(s)), want) diff --git a/src/symident/session.py b/src/symident/session.py index a7227d0..a8d9cc8 100644 --- a/src/symident/session.py +++ b/src/symident/session.py @@ -49,7 +49,7 @@ def marks(): def notes_since(m): """The records added after marks() returned `m`.""" s = state.get("session") - return None if s is None or m is None else {k: v[m[k]:] for k, v in s.notes.items()} + return None if s is None or m is None else {k: v[m[k] :] for k, v in s.notes.items()} def merge_notes(new): @@ -67,6 +67,7 @@ def current(): def _model_text(f, g): def strs(d): return {str(k): str(v) for k, v in dict(d).items()} + gs = [strs(x) for x in g] if isinstance(g, (list, tuple)) else strs(g or {}) return json.dumps([strs(f or {}), gs], sort_keys=True) @@ -78,6 +79,7 @@ def opened(kw): yield state.get("session") return from .options import reconst_control + control = {**reconst_control(), **dict(kw.get("control") or {})} s = Session(control["seed"], _model_text(kw.get("f"), kw.get("g"))) s.control = control diff --git a/src/symident/state.py b/src/symident/state.py index 1e8f337..f8bbb2a 100644 --- a/src/symident/state.py +++ b/src/symident/state.py @@ -3,8 +3,8 @@ import contextlib import os -_OPTIONS = {} -_SWITCHES = {} +_OPTIONS: dict = {} +_SWITCHES: dict = {} _MISSING = object() @@ -88,14 +88,24 @@ def switches(**kw): "LIEPLATEAU_BLOCK": ("number", "the plateau per condition block; 0 for one plateau"), "VERIFY_MARGIN": ("number", "orders the saturation guard checks past the reported one (6)"), "JETWORK": ("number", "characters of jets the jet route may form (1000000)"), - "BLOCKMB": ("number", "megabytes of Taylor values per column block of the kernel (an eighth of the physical " - "memory over the cores, 256 to 1024); environment only"), - "JETMB": ("number", "megabytes of the jets the kernel keeps for calls at higher orders (eight column blocks); " - "environment only"), - "KERNEL_MODE": ("debug", "forward or reverse fixes the mode of the kernel rows, check builds every call in " - "both and raises where the rows differ; environment only"), - "MSOLVE_GB": ("number", "gigabytes of address space of one call of msolve in discrete() where memory is " - "not given (8)"), + "BLOCKMB": ( + "number", + "megabytes of Taylor values per column block of the kernel (an eighth of the physical " + "memory over the cores, 256 to 1024); environment only", + ), + "JETMB": ( + "number", + "megabytes of the jets the kernel keeps for calls at higher orders (eight column blocks); environment only", + ), + "KERNEL_MODE": ( + "debug", + "forward or reverse fixes the mode of the kernel rows, check builds every call in " + "both and raises where the rows differ; environment only", + ), + "MSOLVE_GB": ( + "number", + "gigabytes of address space of one call of msolve in discrete() where memory is not given (8)", + ), "FIBER_TERMS": ("number", "terms of the equations of the fiber that one count of discrete() takes (400000)"), "MSOLVE": ("install", "path of the msolve executable"), "CACHE": ("install", "directory of the symident cache"), @@ -125,14 +135,17 @@ def env(name): def active(): """The switches that are set, by name.""" - names = {k[len("SYMIDENT_"):] for k in os.environ if k.startswith("SYMIDENT_")} | set(_SWITCHES) + names = {k[len("SYMIDENT_") :] for k in os.environ if k.startswith("SYMIDENT_")} | set(_SWITCHES) return {n: env_value(n) for n in sorted(names) if env_value(n) not in (None, "")} def check_names(): """Warn about SYMIDENT_* variables and switches that name no switch.""" import warnings + unknown = [n for n in active() if n not in SWITCHES] if unknown: - warnings.warn("unknown switch " + ", ".join("SYMIDENT_" + n for n in unknown) + - "; see symident.state.SWITCHES", stacklevel=4) + warnings.warn( + "unknown switch " + ", ".join("SYMIDENT_" + n for n in unknown) + "; see symident.state.SWITCHES", + stacklevel=4, + ) diff --git a/src/symident/sym/algebraic.py b/src/symident/sym/algebraic.py index 121c4b1..47e2711 100644 --- a/src/symident/sym/algebraic.py +++ b/src/symident/sym/algebraic.py @@ -9,8 +9,7 @@ def radical_relation(name, expr): """The irreducible factors in `name` of a polynomial vanishing at name = expr, radicals eliminated by resultants.""" X = spy.Symbol(str(name)) e = spy.sympify(expr) - rads = sorted((a for a in e.atoms(spy.Pow) if a.exp.is_Rational and not a.exp.is_Integer), - key=spy.count_ops) + rads = sorted((a for a in e.atoms(spy.Pow) if a.exp.is_Rational and not a.exp.is_Integer), key=spy.count_ops) if not rads: return None try: @@ -22,7 +21,7 @@ def radical_relation(name, expr): sub = {a: r ** int(a.exp.p)} F = F.xreplace(sub) rels.append((r, spy.numer(spy.together(r ** int(a.exp.q) - a.base)))) - rads = rads[:k + 1] + [w.xreplace(sub) for w in rads[k + 1:]] + rads = rads[: k + 1] + [w.xreplace(sub) for w in rads[k + 1 :]] F = spy.numer(spy.together(F)) for r, rel in reversed(rels): F = spy.resultant(F, rel, r) diff --git a/src/symident/sym/charts.py b/src/symident/sym/charts.py index 105ad2b..9c388ba 100644 --- a/src/symident/sym/charts.py +++ b/src/symident/sym/charts.py @@ -20,8 +20,7 @@ def _hyp_to_exp(e): def _has_exp(e): """True if e contains an exponential or the number E.""" e = spy.sympify(e) - return e.has(spy.E) or any(_exp_atom(a) is not None - for a in e.atoms(spy.exp, spy.Pow)) + return e.has(spy.E) or any(_exp_atom(a) is not None for a in e.atoms(spy.exp, spy.Pow)) def _strip_log_obs(g): @@ -48,8 +47,7 @@ def _strip_log_obs(g): out = out * L.args[0] ** c for t in spy.Add.make_args(rest): nl = [a for a in t.atoms(spy.log) if a.args[0].is_number] - out = out * (nl[0].args[0] ** spy.cancel(t / nl[0]) if len(nl) == 1 - else spy.exp(t)) + out = out * (nl[0].args[0] ** spy.cancel(t / nl[0]) if len(nl) == 1 else spy.exp(t)) if not out.atoms(spy.log): return out return g @@ -105,6 +103,7 @@ def _log_param_denominators(base_of, exprs): def _log_param_sub(lp): """Rewriter of base^(sum c_i theta_i + k) to base^k * prod X_i^(c_i L_i), lp: theta -> (X, base[, L]).""" + def repl(at): be = _exp_atom(at) if be is None: @@ -114,7 +113,7 @@ def repl(at): k = terms.pop(spy.Integer(1), spy.Integer(0)) if not terms or any(t not in lp or lp[t][1] != base for t in terms): return at - out = base ** k if k != 0 else spy.Integer(1) + out = base**k if k != 0 else spy.Integer(1) for t, cf in terms.items(): L = lp[t][2] if len(lp[t]) > 2 else 1 out = out * lp[t][0] ** (cf * L) @@ -125,6 +124,7 @@ def sub(e): if not lp: return e return e.replace(lambda x: _exp_atom(x) is not None, repl) + return sub @@ -151,30 +151,31 @@ def sign_chart(f, gs, positive): lines = list(fl.values()) + [v for g in gl for v in g.values()] + [str(k) for k in fl] local, parse = _make_local_parse(lines) local = dict(local) - local.update({'abs': spy.Abs, 'sign': spy.sign}) + local.update({"abs": spy.Abs, "sign": spy.sign}) parse = _make_parse(local) pos, _ = declared(positive) names = {str(sym) for sym in local.values() if isinstance(sym, spy.Symbol)} - to_pos = {spy.Symbol(n): spy.Symbol(n, positive=True) - for n in names if pos is None or n in pos} + to_pos = {spy.Symbol(n): spy.Symbol(n, positive=True) for n in names if pos is None or n in pos} back = {v: k for k, v in to_pos.items()} def one(k, rhs): - if any(t in rhs for t in ('max(', 'min(', 'pmax(', 'pmin(', 'ifelse(', - 'Heaviside(')): - raise InapplicableError('%s: max, min and steps are not analytic; analyze each ' - 'regime on its own, e.g. through `conditions`' % k) + if any(t in rhs for t in ("max(", "min(", "pmax(", "pmin(", "ifelse(", "Heaviside(")): + raise InapplicableError( + "%s: max, min and steps are not analytic; analyze each regime on its own, e.g. through `conditions`" % k + ) e = parse(rhs).xreplace(to_pos) if e.atoms(spy.Abs, spy.sign): - raise InapplicableError('%s: the sign inside abs() or sign() is not decided by ' - 'the coordinates declared `positive`' % k) + raise InapplicableError( + "%s: the sign inside abs() or sign() is not decided by the coordinates declared `positive`" % k + ) return to_r(e.xreplace(back)) + try: Fn = {k: one(k, str(v)) for k, v in fl.items()} Gn = [{k: one(k, str(v)) for k, v in g.items()} for g in gl] except ValueError as err: - return {'why': str(err)} - return {'f': Fn, 'g': Gn} + return {"why": str(err)} + return {"f": Fn, "g": Gn} def _log_numbers(e, consts): @@ -186,11 +187,11 @@ def _log_numbers(e, consts): continue n = spy.nsimplify(n) if not (n.is_Rational and n > 0): - raise InapplicableError('log(%s) of a number that is not a positive rational' % n) + raise InapplicableError("log(%s) of a number that is not a positive rational" % n) out = spy.Integer(0) for q, sgn in ((n.p, 1), (n.q, -1)): for pr, ex in spy.factorint(q).items(): - sym = spy.Symbol('lognum_%d' % pr) + sym = spy.Symbol("lognum_%d" % pr) consts.add(str(sym)) out += sgn * ex * sym rep[a] = out @@ -205,8 +206,7 @@ def _split(u): """u over a common denominator, factored, or split by the common factors of u when the degree is high.""" t = spy.together(u) try: - deg = max((spy.Poly(x, *x.free_symbols).total_degree() if x.free_symbols else 0) - for x in spy.fraction(t)) + deg = max((spy.Poly(x, *x.free_symbols).total_degree() if x.free_symbols else 0) for x in spy.fraction(t)) except (spy.PolynomialError, spy.GeneratorsNeeded): deg = 0 return spy.factor_terms(t) if deg > _FACTOR_DEGREE else spy.factor(t) @@ -217,9 +217,13 @@ def log_arg_chart(f, gs, positive, taken, ics=None, skip=()): fl = dict(f) gl = [dict(g) for g in gs] il = [dict(ic) for ic in (ics or [])] - lines = (list(fl.values()) + [v for g in gl for v in g.values()] + - [v for ic in il for v in ic.values()] + - [str(k) for k in fl] + [str(t) for t in taken]) + lines = ( + list(fl.values()) + + [v for g in gl for v in g.values()] + + [v for ic in il for v in ic.values()] + + [str(k) for k in fl] + + [str(t) for t in taken] + ) # conditions repeat the same texts: each distinct text is parsed and normalized once _, parse = _make_local_parse(list(dict.fromkeys(str(x) for x in lines))) pos, _ = declared(positive) @@ -233,13 +237,14 @@ def norm(e): P = {x: spy.Symbol(str(x), positive=True) for x in e.free_symbols if is_pos(x)} e = spy.expand_power_base(e.xreplace(P), deep=True) e = e.xreplace({v: k for k, v in P.items()}) - return e.replace(lambda x: x.is_Pow and x.base.is_Add and not x.exp.is_number, - lambda x: spy.exp(x.exp * spy.log(x.base))) + return e.replace( + lambda x: x.is_Pow and x.base.is_Add and not x.exp.is_number, lambda x: spy.exp(x.exp * spy.log(x.base)) + ) def sum_powers(e): # u^c of a sum u with c not an integer is exp(c*log(u)): the base u is treated like log(u) - return [pw.base for pw in e.atoms(spy.Pow) if pw.base.is_Add and pw.exp.is_Rational - and not pw.exp.is_Integer] + return [pw.base for pw in e.atoms(spy.Pow) if pw.base.is_Add and pw.exp.is_Rational and not pw.exp.is_Integer] + normal = {} def normal_of(v): @@ -247,15 +252,18 @@ def normal_of(v): if v not in normal: normal[v] = norm(parse(v)) return normal[v] + F = {k: normal_of(v) for k, v in fl.items()} G = [{k: normal_of(v) for k, v in g.items()} for g in gl] I = [{k: normal_of(v) for k, v in ic.items()} for ic in il] # the distinct expressions of the observables, in the order of their first occurrence G_exprs = list(dict.fromkeys(e for g in G for e in g.values())) g_texts = list(dict.fromkeys(str(v) for g in gl for v in g.values())) - normed = any(spy.simplify(F[k] - parse(str(v))) != 0 for k, v in fl.items()) or \ - any(spy.simplify(normal[v] - parse(v)) != 0 for v in g_texts) or \ - any(sum_powers(e) for e in list(F.values()) + G_exprs) + normed = ( + any(spy.simplify(F[k] - parse(str(v))) != 0 for k, v in fl.items()) + or any(spy.simplify(normal[v] - parse(v)) != 0 for v in g_texts) + or any(sum_powers(e) for e in list(F.values()) + G_exprs) + ) states = {spy.Symbol(k) for k in fl} one, zero = spy.Integer(1), spy.Integer(0) @@ -263,7 +271,7 @@ def positive_on(e): # sign certificate on the declared domain: coordinates are real, the declared ones positive return is_positive(e, positive) - chart = {} # v -> (a, b) + chart = {} # v -> (a, b) skip = {str(x) for x in skip} @@ -272,8 +280,7 @@ def positive_on(e): def claim(v, a, b): if str(v) in skip: return - if v in chart and (spy.simplify(chart[v][0] - a) != 0 or - spy.simplify(chart[v][1] - b) != 0): + if v in chart and (spy.simplify(chart[v][0] - a) != 0 or spy.simplify(chart[v][1] - b) != 0): # two logarithms of one symbol: no coordinate change, the recasts take the powers and logarithms contested.add(v) return @@ -304,8 +311,7 @@ def scan(e, ps): if v in b.free_symbols or b == 0: continue a = spy.expand(arg - b * v) - if v in chart and (spy.simplify(chart[v][0] - a) != 0 or - spy.simplify(chart[v][1] - b) != 0): + if v in chart and (spy.simplify(chart[v][0] - a) != 0 or spy.simplify(chart[v][1] - b) != 0): continue claim(v, a, b) done = True @@ -342,9 +348,11 @@ def scan(e, ps): for pw in e.atoms(spy.Pow): if pw.base in given and pw.base not in at_zero and not pw.exp.is_number and is_pos(pw.base): claim(pw.base, zero, one) + def charted(): # the names whose symbol the chart holds return {str(v) for v in chart if spy.Symbol(str(v)) in chart} + # an initial value of a transformed state enters as the logarithm of the argument while True: n0 = len(chart) @@ -363,7 +371,7 @@ def charted(): if len(chart) == n0: break except ValueError as err: - return {'why': str(err)} + return {"why": str(err)} # an affine coordinate change turns a free power of the symbol into a power of a sum for e in list(F.values()) + G_exprs: for pw in e.atoms(spy.Pow): @@ -378,9 +386,9 @@ def charted(): used = {str(t) for t in taken} | {str(k) for k in fl} L = {} for v in sorted(chart, key=str): - nm = 'log_%s' % v + nm = "log_%s" % v while nm in used: - nm += '_' + nm += "_" used.add(nm) L[v] = spy.Symbol(nm, real=True) sub0 = {v: (spy.exp(L[v]) - chart[v][0]) / chart[v][1] for v in chart} @@ -400,12 +408,14 @@ def tidy(e): x = x.xreplace({at: spy.log(spy.cancel(at.args[0])) for at in x.atoms(spy.log)}) r = tidied[e] = _log_numbers(spy.powsimp(spy.expand_log(x, force=True)), consts) return r + texts = {} def tidy_text(e): if e not in texts: texts[e] = str(tidy(e)) return texts[e] + Fn = {} for k, e in F.items(): ks = spy.Symbol(k) @@ -413,8 +423,9 @@ def tidy_text(e): # log(u)' = u'/u with u = a + b*v and u' over every state it holds a, b = chart[ks] u = a + b * ks - du = sum((spy.diff(u, spy.Symbol(s_)) * F[s_] for s_ in F - if spy.Symbol(s_) in u.free_symbols), spy.Integer(0)) + du = sum( + (spy.diff(u, spy.Symbol(s_)) * F[s_] for s_ in F if spy.Symbol(s_) in u.free_symbols), spy.Integer(0) + ) Fn[str(L[ks])] = str(spy.powsimp(spy.expand(tidy(du) * spy.exp(-L[ks])))) else: Fn[k] = str(tidy(e)) @@ -430,87 +441,96 @@ def tidy_text(e): u0 = (a + b * ks).xreplace(at0) if u0.is_number and u0.is_positive is not True: # log(u) and u^n are not analytic at a start of 0: no Lie derivatives at t = 0 - return {'why': 'the initial value %s = %s makes %s start at %s, but a logarithm, ' - 'fractional power or base of a free exponent must be positive, also at the start; ' - 'give that initial value as a positive parameter' % (k, e, a + b * ks, u0)} + return { + "why": "the initial value %s = %s makes %s start at %s, but a logarithm, " + "fractional power or base of a free exponent must be positive, also at the start; " + "give that initial value as a positive parameter" % (k, e, a + b * ks, u0) + } le = tidy(spy.log(u0)) # a logarithm left over is a function of the coordinates, for the recasts - if any(not at.args[0].is_number and not positive_on(at.args[0]) - for at in le.atoms(spy.log)): - return {'why': 'the initial value %s = %s does not split into ' - 'logarithms of positive coordinates' % (k, e)} + if any(not at.args[0].is_number and not positive_on(at.args[0]) for at in le.atoms(spy.log)): + return { + "why": "the initial value %s = %s does not split into " + "logarithms of positive coordinates" % (k, e) + } try: d[str(L[ks])] = str(_log_numbers(le, consts)) except ValueError as err: - return {'why': str(err)} + return {"why": str(err)} else: d[k] = tidy_text(e) In.append(d) - return {'f': Fn, 'g': Gn, 'ic': In, 'consts': sorted(consts), - 'map': [{'v': str(v), 'L': str(L[v]), 'a': str(chart[v][0]), - 'b': str(chart[v][1])} for v in sorted(chart, key=str)]} + return { + "f": Fn, + "g": Gn, + "ic": In, + "consts": sorted(consts), + "map": [ + {"v": str(v), "L": str(L[v]), "a": str(chart[v][0]), "b": str(chart[v][1])} for v in sorted(chart, key=str) + ], + } def log_arg_event(var, value, method, maps, positive=True): """One event in the log coordinates as {'var', 'value', 'method', 'consts'}, or {'why': ...}.""" maps = list(maps) - lines = [str(value)] + [str(m[k]) for m in maps for k in ('v', 'L', 'a', 'b')] + lines = [str(value)] + [str(m[k]) for m in maps for k in ("v", "L", "a", "b")] _, parse = _make_local_parse(lines) - ent = {str(m['v']): (spy.Symbol(str(m['L']), real=True), parse(str(m['a'])), - parse(str(m['b']))) for m in maps} + ent = {str(m["v"]): (spy.Symbol(str(m["L"]), real=True), parse(str(m["a"])), parse(str(m["b"]))) for m in maps} sub = {parse(v): (spy.exp(Lv) - a) / b for v, (Lv, a, b) in ent.items()} e = parse(str(value)).subs(sub) if str(var) not in ent: - return {'var': str(var), 'value': str(e), 'method': str(method), 'consts': []} + return {"var": str(var), "value": str(e), "method": str(method), "consts": []} Lv, a, b = ent[str(var)] - if method == 'add' and e == 0: - return {'var': str(Lv), 'value': '0', 'method': 'add', 'consts': []} - if method == 'multiply' and a == 0: - le, kind = spy.log(e), 'add' + if method == "add" and e == 0: + return {"var": str(Lv), "value": "0", "method": "add", "consts": []} + if method == "multiply" and a == 0: + le, kind = spy.log(e), "add" else: # the argument after the event, from exp(L) = a + b*v before it - u = {'replace': a + b * e, 'add': spy.exp(Lv) + b * e, - 'multiply': a + (spy.exp(Lv) - a) * e}[str(method)] - le, kind = spy.log(u), 'replace' + u = {"replace": a + b * e, "add": spy.exp(Lv) + b * e, "multiply": a + (spy.exp(Lv) - a) * e}[str(method)] + le, kind = spy.log(u), "replace" # positive on the domain, with the argument before the event positive - h = spy.Dummy('h', positive=True) + h = spy.Dummy("h", positive=True) v0 = parse(str(value)) - u_old = {'replace': a + b * v0, 'add': h + b * v0, 'multiply': a + (h - a) * v0}[str(method)] - if method == 'multiply' and a == 0: + u_old = {"replace": a + b * v0, "add": h + b * v0, "multiply": a + (h - a) * v0}[str(method)] + if method == "multiply" and a == 0: u_old = v0 if not is_positive(u_old, positive): - return {'why': 'the event value %s for %s, which is analyzed as log(%s), does not keep ' - 'the argument positive' % (value, var, a + b * parse(str(var)))} + return { + "why": "the event value %s for %s, which is analyzed as log(%s), does not keep " + "the argument positive" % (value, var, a + b * parse(str(var))) + } le = spy.powsimp(spy.expand_log(le, force=True)) consts = set() try: le = _log_numbers(le, consts) except ValueError as err: - return {'why': str(err)} - return {'var': str(Lv), 'value': str(le), 'method': kind, 'consts': sorted(consts)} + return {"why": str(err)} + return {"var": str(Lv), "value": str(le), "method": kind, "consts": sorted(consts)} def log_arg_back_vec(vec, maps): """A generator in the log coordinates back in the user's symbols.""" maps = list(maps) - lines = [str(x) for x in vec.values()] + [str(k) for k in vec] + \ - [str(m[k]) for m in maps for k in ('v', 'L', 'a', 'b')] + lines = ( + [str(x) for x in vec.values()] + [str(k) for k in vec] + [str(m[k]) for m in maps for k in ("v", "L", "a", "b")] + ) _, parse = _make_local_parse(lines) V = {str(k): parse(str(x)) for k, x in vec.items()} - ent = [(parse(str(m['v'])), str(m['L']), parse(str(m['a'])), parse(str(m['b']))) - for m in maps] + ent = [(parse(str(m["v"])), str(m["L"]), parse(str(m["a"])), parse(str(m["b"]))) for m in maps] Lnames = {Ln for _, Ln, _, _ in ent} vp = {v: spy.Symbol(str(v), positive=True) for v, _, _, _ in ent} to_l = {parse(Ln): spy.log(a + b * v) for v, Ln, a, b in ent} out = {k: e.subs(to_l) for k, e in V.items() if k not in Lnames} # a coordinate whose a, b hold another transformed symbol comes after it - order = sorted(ent, key=lambda t: len((t[2].free_symbols | t[3].free_symbols) & - set(vp))) + order = sorted(ent, key=lambda t: len((t[2].free_symbols | t[3].free_symbols) & set(vp))) for v, Ln, a, b in order: e_l = V.get(Ln, spy.Integer(0)).subs(to_l) def grad(h): return sum((spy.diff(h, parse(k)) * e for k, e in out.items()), spy.Integer(0)) + nv = ((a + b * v) * e_l - grad(a) - v * grad(b)) / b out[str(v)] = nv res = {} @@ -524,8 +544,7 @@ def grad(h): def scaling_weights(comps): """{name: weight} when every component is a number times the coordinate of that component, else None.""" - _, parse = _make_local_parse([str(v) for v in comps.values()] + - [str(k) for k in comps]) + _, parse = _make_local_parse([str(v) for v in comps.values()] + [str(k) for k in comps]) out = {} for k, v in comps.items(): w = spy.cancel(parse(str(v)) / parse(str(k))) @@ -594,9 +613,9 @@ def log_chart_generators(gens, coords, translated=()): taken = set(names) lp = {} for t, b in sorted(base_of.items(), key=lambda kv: str(kv[0])): - nm = 'exp_%s' % t + nm = "exp_%s" % t while nm in taken: - nm += '_' + nm += "_" taken.add(nm) lp[t] = (spy.Symbol(nm), b) sub = _log_param_sub(lp) @@ -625,9 +644,13 @@ def log_chart_generators(gens, coords, translated=()): if v.atoms(spy.log, spy.exp) or any(t in v.free_symbols for t in lp): return None out.append({k: str(v) for k, v in h.items()}) - return {'map': [{'theta': str(t), 'X': str(X), 'base': 'E' if b == spy.E else str(b), 'translated': t in moved} - for t, (X, b) in lp.items()], - 'gens': out} + return { + "map": [ + {"theta": str(t), "X": str(X), "base": "E" if b == spy.E else str(b), "translated": t in moved} + for t, (X, b) in lp.items() + ], + "gens": out, + } def exp_chart_generators(gens, coords, positive): @@ -640,8 +663,7 @@ def exp_chart_generators(gens, coords, positive): exprs_of.append(None) continue _, parse = _make_local_parse([str(v) for v in g.values()] + names) - exprs_of.append({str(k): spy.expand_log(spy.sympify(parse(str(v))), force=True) - for k, v in g.items()}) + exprs_of.append({str(k): spy.expand_log(spy.sympify(parse(str(v))), force=True) for k, v in g.items()}) coord_syms = {spy.Symbol(n) for n in names} cand = set() for g in exprs_of: @@ -666,9 +688,9 @@ def exp_chart_generators(gens, coords, positive): taken = set(names) L = {} for v in sorted(cand, key=str): - nm = 'log_%s' % v + nm = "log_%s" % v while nm in taken: - nm += '_' + nm += "_" taken.add(nm) L[v] = spy.Symbol(nm, real=True) sub = {v: spy.exp(L[v]) for v in cand} @@ -689,8 +711,7 @@ def exp_chart_generators(gens, coords, positive): if v.atoms(spy.log, spy.exp): return None out.append({k: str(v) for k, v in h.items()}) - return {'map': [{'v': str(v), 'L': str(L[v])} for v in sorted(cand, key=str)], - 'gens': out} + return {"map": [{"v": str(v), "L": str(L[v])} for v in sorted(cand, key=str)], "gens": out} def _model_str(e): @@ -700,8 +721,10 @@ def _model_str(e): def exp_chart_back(expr, v_names, l_names, solve_for=None): """An expression in L = log(v) back in v; with solve_for naming an L, exp() of it, the value of v.""" + def as_list(v): return list(v) if isinstance(v, (list, tuple)) else [v] + v_names, l_names = as_list(v_names), as_list(l_names) _, parse = _make_local_parse([str(expr)] + [str(x) for x in v_names + l_names]) e = parse(str(expr)) @@ -715,15 +738,17 @@ def as_list(v): def log_chart_back(expr, x_names, thetas, bases, solve_for=None): """An expression in X = b^theta back in theta; with solve_for naming an X, log_b of it, the value of theta.""" + def as_list(v): return list(v) if isinstance(v, (list, tuple)) else [v] + x_names, thetas, bases = as_list(x_names), as_list(thetas), as_list(bases) _, parse = _make_local_parse([str(expr)] + [str(x) for x in x_names + thetas]) e = parse(str(expr)) subs = {} logb = None for X, th, b in zip(x_names, thetas, bases): - bb = spy.E if str(b) == 'E' else spy.sympify(str(b)) + bb = spy.E if str(b) == "E" else spy.sympify(str(b)) subs[parse(str(X))] = bb ** parse(str(th)) if solve_for is not None and str(X) == str(solve_for): logb = spy.log(bb) @@ -735,14 +760,16 @@ def as_list(v): def log_param_backsub(expr, comp, x_names, thetas, bases): """A component in X = base^theta back in theta, divided by X*log(base) when comp names an X.""" + def as_list(v): return list(v) if isinstance(v, (list, tuple)) else [v] + x_names, thetas, bases = as_list(x_names), as_list(thetas), as_list(bases) _, parse = _make_local_parse([str(expr)] + [str(x) for x in x_names + thetas]) e = parse(str(expr)) subs = {} for X, th, b in zip(x_names, thetas, bases): - bb = spy.E if str(b) == 'E' else spy.sympify(str(b)) + bb = spy.E if str(b) == "E" else spy.sympify(str(b)) Xs = parse(str(X)) if str(comp) == str(X): e = e / (Xs * spy.log(bb)) @@ -752,14 +779,22 @@ def as_list(v): def _split_power_bases(per_cond): """`per_cond` with a product base of a symbolic power split into powers of the factors, (2*K)^n as 2^n*K^n.""" + def split(e): e = spy.sympify(e) - if any(not pw.exp.is_number and not pw.base.is_Symbol and not pw.base.is_number - for pw in e.atoms(spy.Pow)): + if any(not pw.exp.is_number and not pw.base.is_Symbol and not pw.base.is_number for pw in e.atoms(spy.Pow)): return spy.expand_power_base(e, force=True) return e - return [([split(e) for e in f_c], [split(e) for e in g_c], {k: split(v) for k, v in ic_c.items()}, - [split(e) for e in f_ss]) for (f_c, g_c, ic_c, f_ss) in per_cond] + + return [ + ( + [split(e) for e in f_c], + [split(e) for e in g_c], + {k: split(v) for k, v in ic_c.items()}, + [split(e) for e in f_ss], + ) + for (f_c, g_c, ic_c, f_ss) in per_cond + ] def _power_exponent(ex): @@ -775,7 +810,7 @@ def _detect_power_atoms(per_cond, states=()): """Sorted (base, n) of the symbolic powers base^(c0 + c*n), n not a state, or None for another power.""" pairs = set() states = set(states) - for (f_c, g_c, ic_c, f_ss) in per_cond: + for f_c, g_c, ic_c, f_ss in per_cond: for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss): for pw in spy.sympify(e).atoms(spy.Pow): if pw.exp.is_number or _exp_atom(pw) is not None: @@ -791,10 +826,10 @@ def _apply_power_recast(pairs, S, per_cond): """States, conditions and meta with E = base^n per pair and L = log(base) per base as new states.""" recast = {} Lof = {} - for (base, n) in pairs: - recast[(base, n)] = spy.Symbol('_E_%s_%s' % (base, n)) + for base, n in pairs: + recast[(base, n)] = spy.Symbol("_E_%s_%s" % (base, n)) if base not in Lof: - Lof[base] = spy.Symbol('_L_%s' % base) + Lof[base] = spy.Symbol("_L_%s" % base) def sub(expr): def repl(pw): @@ -803,21 +838,20 @@ def repl(pw): cn = _power_exponent(pw.exp) E = None if cn is None else recast.get((pw.base, cn[2])) return pw.base ** cn[0] * E ** cn[1] if E is not None else pw + return spy.sympify(expr).replace(lambda x: x.is_Pow, repl) - extra = [recast[(b, n)] for (b, n) in pairs] + \ - [Lof[b] for b in sorted(Lof, key=str)] + extra = [recast[(b, n)] for (b, n) in pairs] + [Lof[b] for b in sorted(Lof, key=str)] new_per_cond = [] - for (f_c, g_c, ic_c, f_ss) in per_cond: + for f_c, g_c, ic_c, f_ss in per_cond: f_r = [sub(e) for e in f_c] g_r = [sub(e) for e in g_c] ic_r = {k: sub(v) for k, v in ic_c.items()} ss_r = [sub(e) for e in f_ss] rhs_of = {str(X): f_r[i] for i, X in enumerate(S)} # a base state with a given initial value fixes the initial values of E and L - b0 = {b: spy.sympify(ic_c[str(b)]) for b in Lof - if str(b) in ic_c and spy.sympify(ic_c[str(b)]) not in (b, 0)} - for (b, n) in pairs: + b0 = {b: spy.sympify(ic_c[str(b)]) for b in Lof if str(b) in ic_c and spy.sympify(ic_c[str(b)]) not in (b, 0)} + for b, n in pairs: E = recast[(b, n)] brhs = rhs_of.get(str(b), spy.Integer(0)) ic_r[str(E)] = spy.exp(n * spy.log(b0[b])) if b in b0 else E @@ -828,19 +862,18 @@ def repl(pw): ic_r[str(L)] = spy.log(b0[b]) if b in b0 else L f_r.append(brhs / b if brhs != 0 else spy.Integer(0)) new_per_cond.append((f_r, g_r, ic_r, ss_r)) - meta = [{'E': str(recast[(b, n)]), 'L': str(Lof[b]), - 'base': str(b), 'exp': str(n)} for (b, n) in pairs] + meta = [{"E": str(recast[(b, n)]), "L": str(Lof[b]), "base": str(b), "exp": str(n)} for (b, n) in pairs] return list(S) + extra, new_per_cond, meta def recast_backsub_expr(expr, e_names, l_names, bases, exps): """An expression with E -> base**exp and L -> log(base) substituted back, canceled.""" + def as_list(v): return list(v) if isinstance(v, (list, tuple)) else [v] - e_names, l_names, bases, exps = (as_list(e_names), as_list(l_names), - as_list(bases), as_list(exps)) - _, parse = _make_local_parse( - [str(expr)] + [str(x) for x in e_names + l_names + bases + exps]) + + e_names, l_names, bases, exps = (as_list(e_names), as_list(l_names), as_list(bases), as_list(exps)) + _, parse = _make_local_parse([str(expr)] + [str(x) for x in e_names + l_names + bases + exps]) e = parse(str(expr)) subs = {} for E, L, base, exp in zip(e_names, l_names, bases, exps): diff --git a/src/symident/sym/continuation.py b/src/symident/sym/continuation.py index 9dd9a25..3951318 100644 --- a/src/symident/sym/continuation.py +++ b/src/symident/sym/continuation.py @@ -58,19 +58,21 @@ def _ser_value(numden, gser, p, T, pw): return None if inv is None else _ser_mul(num, inv, p, T) -_cont_cache = {} +_cont_cache: dict = {} -def continue_resting_state(model, state_names, param_names, param_vals, dirs, rest_vals, prime, - order, forcings=None, held=None): +def continue_resting_state( + model, state_names, param_names, param_vals, dirs, rest_vals, prime, order, forcings=None, held=None +): """Resting state as a power series in eps along param_vals + eps dirs, or {'ok': False, 'why'}.""" p, T = int(prime), int(order) model = _as_list(model) forcings = set(_as_list(forcings)) state_names = _as_list(state_names) param_names = _as_list(param_names) - (param_syms, solve_states, polys, _, _, gens, jx_terms, jt_terms, _, _, _, - _) = _ss_compile(model, state_names, param_names, forcings, linear=False) + (param_syms, solve_states, polys, _, _, gens, jx_terms, jt_terms, _, _, _, _) = _ss_compile( + model, state_names, param_names, forcings, linear=False + ) key = (tuple(model), tuple(state_names), tuple(param_names), tuple(sorted(forcings))) cached = _cont_cache.get(key) if cached is None: @@ -85,10 +87,14 @@ def continue_resting_state(model, state_names, param_names, param_vals, dirs, re rv = {str(k): int(v) % p for k, v in dict(rest_vals).items()} hv = {str(k): int(v) % p for k, v in dict(held or {}).items()} n_s = len(solve_states) - pser = [[pv.get(str(th), 0)] + [dv.get(str(th), 0)] + [0] * (T - 1) if T >= 1 - else [pv.get(str(th), 0)] for th in param_syms] - xser = [[rv.get(str(s_), 0)] + ([hv[str(s_)]] + [0] * (T - 1) if str(s_) in hv and T >= 1 - else [0] * T) for s_ in solve_states] + pser = [ + [pv.get(str(th), 0)] + [dv.get(str(th), 0)] + [0] * (T - 1) if T >= 1 else [pv.get(str(th), 0)] + for th in param_syms + ] + xser = [ + [rv.get(str(s_), 0)] + ([hv[str(s_)]] + [0] * (T - 1) if str(s_) in hv and T >= 1 else [0] * T) + for s_ in solve_states + ] keep = [i for i, s_ in enumerate(solve_states) if str(s_) not in hv] held_idx = [i for i, s_ in enumerate(solve_states) if str(s_) in hv] @@ -104,16 +110,16 @@ def f_series(): f0 = f_series() if f0 is None or any(f0[i][0] for i in keep): - return {'ok': False, 'why': 'the start is not a resting state at eps = 0'} + return {"ok": False, "why": "the start is not a resting state at eps = 0"} g0 = [pv.get(str(th), 0) for th in param_syms] + [rv.get(str(s_), 0) for s_ in solve_states] J0 = [[_eval_terms(jn_t[i][j], g0, p) for j in keep] for i in keep] for k in range(1, T + 1): fs = f_series() if fs is None: - return {'ok': False, 'why': 'a pole along the continuation'} + return {"ok": False, "why": "a pole along the continuation"} X = _solve_mod(J0, [[(-fs[i][k]) % p] for i in keep], p) if X is None: - return {'ok': False, 'why': 'a singular resting Jacobian'} + return {"ok": False, "why": "a singular resting Jacobian"} for r, i in enumerate(keep): xser[i][k] = X[r][0] % p pw = {} @@ -127,7 +133,11 @@ def ser_of(terms): df_jt = {str(th): [ser_of(jt_terms[str(th)][i]) for i in keep] for th in param_syms} for hj in held_idx: df_jt[str(solve_states[hj])] = [ser_of(jx_terms[i][hj]) for i in keep] - return {'ok': True, 'val_by': {str(solve_states[i]): xser[i] for i in range(n_s)}, - 'df_jx': df_jx, 'df_jt': df_jt, - 'df_state_cols': [str(solve_states[j]) for j in keep], - 'df_param_cols': [str(x) for x in param_syms] + [str(solve_states[j]) for j in held_idx]} + return { + "ok": True, + "val_by": {str(solve_states[i]): xser[i] for i in range(n_s)}, + "df_jx": df_jx, + "df_jt": df_jt, + "df_state_cols": [str(solve_states[j]) for j in keep], + "df_param_cols": [str(x) for x in param_syms] + [str(solve_states[j]) for j in held_idx], + } diff --git a/src/symident/sym/degrees.py b/src/symident/sym/degrees.py index 91f79bd..9692cad 100644 --- a/src/symident/sym/degrees.py +++ b/src/symident/sym/degrees.py @@ -24,6 +24,7 @@ def of(self, den): class Deg: """A rational function of the coordinates by degree bounds only: the degree of the numerator and the denominator as a product of factors of Atoms; a number is kept exactly, zero only where exactly zero.""" + __slots__ = ("A", "dn", "den", "c") def __init__(self, A, dn=0, den=None, c=None): @@ -96,7 +97,7 @@ def __eq__(self, x): return self.c == 0 return NotImplemented - __hash__ = None + __hash__ = None # type: ignore[assignment] def common(values): @@ -106,5 +107,4 @@ def common(values): for v in values: for a, e in v.den.items(): L[a] = max(L.get(a, 0), e) - return A.of(L), [None if v.c == 0 else v.dn + A.of({a: e - v.den.get(a, 0) for a, e in L.items()}) - for v in values] + return A.of(L), [None if v.c == 0 else v.dn + A.of({a: e - v.den.get(a, 0) for a, e in L.items()}) for v in values] diff --git a/src/symident/sym/direction.py b/src/symident/sym/direction.py index 7dbe440..c9911b4 100644 --- a/src/symident/sym/direction.py +++ b/src/symident/sym/direction.py @@ -72,8 +72,9 @@ def _classify_factored(infis, gens): cleared.append((cn / cd, {f: m for f, m in fm.items() if m})) common = None for _, fm in cleared: - common = dict(fm) if common is None else \ - {f: min(m, fm.get(f, 0)) for f, m in common.items() if fm.get(f, 0)} + common = ( + dict(fm) if common is None else {f: min(m, fm.get(f, 0)) for f, m in common.items() if fm.get(f, 0)} + ) coeffs = [c for c, _ in cleared] # integer-primitive: clear the rational coefficients, divide by their gcd dl = 1 @@ -97,16 +98,15 @@ def _classify_factored(infis, gens): d += m * spy.Poly(f, *gens).total_degree() prim[i] = e degs.append(d) - is_scaling = all(degs[k] == 1 and prim[i].free_symbols == {gens[i]} - and spy.Poly(prim[i], gens[i]).total_degree() == 1 - for k, i in enumerate(nz)) + is_scaling = all( + degs[k] == 1 and prim[i].free_symbols == {gens[i]} and spy.Poly(prim[i], gens[i]).total_degree() == 1 + for k, i in enumerate(nz) + ) comp_out = {str(gens[i]): str(prim[i]) for i in nz} if is_scaling: weights = {str(gens[i]): int(spy.Poly(prim[i], gens[i]).LC()) for i in nz} - return {'type': 'scaling', 'weights': weights, - 'components': comp_out, 'degree': 1} - return {'type': 'general', 'weights': None, 'components': comp_out, - 'degree': int(max(degs)) if degs else 0} + return {"type": "scaling", "weights": weights, "components": comp_out, "degree": 1} + return {"type": "general", "weights": None, "components": comp_out, "degree": int(max(degs)) if degs else 0} except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -118,15 +118,14 @@ def _classify_factored(infis, gens): def classify_generator(vector): """{'type', 'weights', 'components', 'degree'}: scaling or general, and the canonical generator.""" items = [(str(k), str(v)) for k, v in vector.items()] - fallback = {'type': 'general', 'weights': None, - 'components': {k: v for k, v in items}, 'degree': -1} + fallback = {"type": "general", "weights": None, "components": {k: v for k, v in items}, "degree": -1} if not items: - return {'type': 'general', 'weights': None, 'components': {}, 'degree': 0} + return {"type": "general", "weights": None, "components": {}, "degree": 0} # one moved coordinate: z*d/dz spans the same direction - moved = [(k, v) for k, v in items if v.strip() != '0'] + moved = [(k, v) for k, v in items if v.strip() != "0"] if len(moved) == 1: z = moved[0][0] - return {'type': 'scaling', 'weights': {z: 1}, 'components': {z: z}, 'degree': 1} + return {"type": "scaling", "weights": {z: 1}, "components": {z: z}, "degree": 1} # very long components skip the canonical form if sum(len(v) for _, v in items) > _CLASSIFY_MAX_CHARS: return fallback @@ -164,7 +163,7 @@ def classify_generator(vector): L = spy.lcm(L, d) nums = [spy.expand(spy.cancel(e * L)) for e in infis] for e in nums: - spy.Poly(e, *gens) # raises if not polynomial in gens + spy.Poly(e, *gens) # raises if not polynomial in gens except SYMPY_FAILS as exc: sympy_fail(exc) return fallback @@ -196,7 +195,5 @@ def classify_generator(vector): if prim[i] != 0: key = tuple(1 if j == i else 0 for j in range(n)) weights[str(gens[i])] = int(spy.Poly(prim[i], *gens).as_dict()[key]) - return {'type': 'scaling', 'weights': weights, - 'components': comp_out, 'degree': 1} - return {'type': 'general', 'weights': None, - 'components': comp_out, 'degree': int(maxdeg)} + return {"type": "scaling", "weights": weights, "components": comp_out, "degree": 1} + return {"type": "general", "weights": None, "components": comp_out, "degree": int(maxdeg)} diff --git a/src/symident/sym/domain.py b/src/symident/sym/domain.py index bd554c2..7c9d8ee 100644 --- a/src/symident/sym/domain.py +++ b/src/symident/sym/domain.py @@ -20,6 +20,7 @@ def declared(positive): names.add(p) else: from .parse import model_sympify + exprs.append(model_sympify(p)) return names, exprs diff --git a/src/symident/sym/exact.py b/src/symident/sym/exact.py index 0f489ee..d940a62 100644 --- a/src/symident/sym/exact.py +++ b/src/symident/sym/exact.py @@ -180,7 +180,7 @@ def parts(x): terms, k = parts(e.exp) if not k.is_Integer or any(not c.is_Rational for c, _ in terms): return e - return spy.Mul(*[atom((b, m)) ** c for c, m in terms]) * b ** k + return spy.Mul(*[atom((b, m)) ** c for c, m in terms]) * b**k return e.func(*[_split_powers(a, atoms) for a in e.args]) @@ -279,13 +279,15 @@ def regime_identities(regime, field, skip=()): if x in skip or (x not in moved and not _free(fx) & moved): continue xi = Y.at(x) - out.append((f"[Y, F] on {x}", Y(fx) - sum((F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), - spy.Integer(0)))) + out.append( + (f"[Y, F] on {x}", Y(fx) - sum((F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), spy.Integer(0))) + ) for th, xi in Y.c.items(): if th in F or th in skip or not xi.free_symbols & set(F): continue - out.append((f"[Y, F] on {th}", sum((F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), - spy.Integer(0)))) + out.append( + (f"[Y, F] on {th}", sum((F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), spy.Integer(0))) + ) for line in regime["g"]: h = _expr(str(line).split("=", 1)[1]) if "=" in str(line) else _expr(str(line)) if h.free_symbols & moved: @@ -298,6 +300,7 @@ def _in_span(target, fields, coords, label): coordinates fix the coefficients. The coefficients are solved from coordinates chosen at a random point, the identities are the other coordinates; fields[0] must take part.""" import random + A = spy.Matrix([[W.at(c) for W in fields] for c in coords]) rng = random.Random(len(coords)) pt = {x: spy.Rational(rng.randint(2, 997), rng.randint(2, 997)) for x in sorted(A.free_symbols, key=str)} @@ -318,8 +321,11 @@ def _in_span(target, fields, coords, label): if None in coef: return None used = [fields[j] for j in keep] - out = [(f"{label} on {c}", target[c] - sum((m * W.at(c) for m, W in zip(coef, used)), spy.Integer(0))) - for i, c in enumerate(coords) if i not in rows] + out = [ + (f"{label} on {c}", target[c] - sum((m * W.at(c) for m, W in zip(coef, used)), spy.Integer(0))) + for i, c in enumerate(coords) + if i not in rows + ] return coef, out @@ -339,8 +345,9 @@ def line_identities(regime, field, others=(), skip=()): br = {} for c in coords: xi = Y.at(c) - br[c] = (Y(F[c]) if c in F else spy.Integer(0)) - \ - sum((F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), spy.Integer(0)) + br[c] = (Y(F[c]) if c in F else spy.Integer(0)) - sum( + (F[s] * spy.diff(xi, s) for s in xi.free_symbols if s in F), spy.Integer(0) + ) got = _in_span(br, [Y] + Zs, coords, "[Y, F] - lam Y - mu Z") if got is None: return None @@ -373,6 +380,7 @@ def __init__(self, W): def at(self, c): return self.W.at(c).xreplace(E) + got = _in_span(target, [_At(Yt)] + [_At(Z) for Z in Zs], coords, "event: DE Y - nu Y - nu Z") if got is None: return None @@ -445,8 +453,7 @@ def initial_lift(field, ic_lines, states, f_lines=()): if not moved or not pars: return None eqs = [x - e for x, e in moved.items()] - totals = [sum((c * (x - x0.get(x, x)) for x, c in law.items()), spy.Integer(0)) - for law in _conserved(f_lines, sts)] + totals = [sum((c * (x - x0.get(x, x)) for x, c in law.items()), spy.Integer(0)) for law in _conserved(f_lines, sts)] implicit = None try: sol = spy.solve([t for t in totals if t.free_symbols & set(pars)], pars, dict=True) if totals else [] @@ -595,6 +602,7 @@ def degree(n, r): except SYMPY_FAILS as exc: sympy_fail(exc) return None + while left: todo = [spy.numer(spy.together(n.xreplace(sub))) for n in todo] todo = [n for n in todo if n != 0] @@ -647,8 +655,7 @@ def _rest_parametrization(eqs, rest, params): chosen = [] for p in params: trial = chosen + [p] - if not any(p in n.free_symbols for n in rem) or \ - any(spy.Poly(n, *trial).total_degree() > 1 for n in rem): + if not any(p in n.free_symbols for n in rem) or any(spy.Poly(n, *trial).total_degree() > 1 for n in rem): continue A = spy.Matrix([[spy.diff(n, q).xreplace(pt) for q in trial] for n in rem]) if A.rank() == len(trial): @@ -680,8 +687,9 @@ def rest_identities(conds, vector): b = spy.Matrix([-sum((spy.diff(F[x], p) * c for p, c in vec.items()), spy.Integer(0)) for x in xs]) xi = Jx.LUsolve(b) if xs else spy.Matrix([]) for h in obs: - e = sum((spy.diff(h, p) * c for p, c in vec.items()), spy.Integer(0)) + \ - sum((spy.diff(h, y) * xi[j] for j, y in enumerate(xs)), spy.Integer(0)) + e = sum((spy.diff(h, p) * c for p, c in vec.items()), spy.Integer(0)) + sum( + (spy.diff(h, y) * xi[j] for j, y in enumerate(xs)), spy.Integer(0) + ) out.append((f"resting output {h} of condition {k}", e)) return out diff --git a/src/symident/sym/fields.py b/src/symident/sym/fields.py index a6ba8b1..b3bdbc8 100644 --- a/src/symident/sym/fields.py +++ b/src/symident/sym/fields.py @@ -11,7 +11,7 @@ from ..errors import SYMPY_FAILS, InapplicableError, sympy_fail from .parse import _as_list, _clean, _make_local_parse -_LIFT_CACHE = {} +_LIFT_CACHE: dict = {} class _DistCheck: @@ -32,10 +32,9 @@ def value(self, e, syms, vals, p, skey=None): if fn is None: # decimals as exact rationals, rationals as Fraction: no float enters ex = e.xreplace({x: spy.Rational(str(x)) for x in e.atoms(spy.Float)}) - frac = spy.Function('Fraction') - ex = ex.xreplace({x: frac(x.p, x.q) for x in ex.atoms(spy.Rational) - if not x.is_Integer}) - fn = spy.lambdify(syms, ex, modules=[{'Fraction': Fraction}]) + frac = spy.Function("Fraction") + ex = ex.xreplace({x: frac(x.p, x.q) for x in ex.atoms(spy.Rational) if not x.is_Integer}) + fn = spy.lambdify(syms, ex, modules=[{"Fraction": Fraction}]) self.fns[key] = fn try: v = fn(*vals) @@ -83,7 +82,8 @@ def _span_coeffs(B, v, p): class _DualMod: """a + b*eps over GF(p) with eps^2 = 0, for directional derivatives of lambdified rational expressions.""" - __slots__ = ('a', 'b', 'p') + + __slots__ = ("a", "b", "p") def __init__(self, a, b, p): self.a, self.b, self.p = a % p, b % p, p @@ -94,11 +94,10 @@ def _c(self, o): if isinstance(o, Fraction): if o.denominator % self.p == 0: raise ZeroDivisionError - return _DualMod(o.numerator % self.p * pow(o.denominator % self.p, self.p - 2, - self.p), 0, self.p) + return _DualMod(o.numerator % self.p * pow(o.denominator % self.p, self.p - 2, self.p), 0, self.p) if isinstance(o, int): return _DualMod(o, 0, self.p) - raise InapplicableError('unsupported operand') + raise InapplicableError("unsupported operand") def __add__(self, o): o = self._c(o) @@ -137,7 +136,7 @@ def __pow__(self, n): if isinstance(n, Fraction) and n.denominator == 1: n = n.numerator if not isinstance(n, int): - raise InapplicableError('non-integer power') + raise InapplicableError("non-integer power") if n < 0: return _DualMod(1, 0, self.p) / (self ** (-n)) if n == 0: @@ -156,28 +155,28 @@ def verify_distribution(regimes, gens, events, lifts, p, npts=2, seed=1, q=None) mod = p lines = [] for rg in regimes: - lines += list(_as_list(rg['f'])) + list(_as_list(rg['g'])) + lines += list(_as_list(rg["f"])) + list(_as_list(rg["g"])) for gl in gens: for gg in gl: - lines += ['_ = %s' % v for v in dict(gg).values()] + lines += ["_ = %s" % v for v in dict(gg).values()] for ev in events: - lines += ['_ = %s' % e['value'] for e in _as_list(ev['ev'])] + lines += ["_ = %s" % e["value"] for e in _as_list(ev["ev"])] ck = _DistCheck(lines) rng = session.current().rng("distribution", seed) states = [] for rg in regimes: - for l in _as_list(rg['f']): - nm = _clean(l).split('=', 1)[0].strip() + for l in _as_list(rg["f"]): + nm = _clean(l).split("=", 1)[0].strip() if nm not in states: states.append(nm) F, H = [], [] for rg in regimes: rhs = {} - for l in _as_list(rg['f']): - lhs, e = _clean(l).split('=', 1) + for l in _as_list(rg["f"]): + lhs, e = _clean(l).split("=", 1) rhs[lhs.strip()] = ck.expr(e) F.append(rhs) - H.append([ck.expr(_clean(l).split('=', 1)[1]) for l in _as_list(rg['g'])]) + H.append([ck.expr(_clean(l).split("=", 1)[1]) for l in _as_list(rg["g"])]) Xm = [[{str(k): ck.expr(v) for k, v in dict(gg).items()} for gg in gl] for gl in gens] syms = set() for rhs in F: @@ -191,11 +190,11 @@ def verify_distribution(regimes, gens, events, lifts, p, npts=2, seed=1, q=None) for e in gg.values(): syms |= e.free_symbols for ev in events: - for e in _as_list(ev['ev']): - syms |= ck.expr(e['value']).free_symbols + for e in _as_list(ev["ev"]): + syms |= ck.expr(e["value"]).free_symbols for lf in lifts: - syms |= {spy.Symbol(str(k)) for k in dict(lf['point'])} - for v in _as_list(lf['vectors']): + syms |= {spy.Symbol(str(k)) for k in dict(lf["point"])} + for v in _as_list(lf["vectors"]): syms |= {spy.Symbol(str(k)) for k in dict(v)} coords = states + sorted({str(s) for s in syms} - set(states)) in_model = set() @@ -223,13 +222,12 @@ def dpart(e, s): return d def deriv_dir(e, field): - return sum((dpart(e, s) * comp(field, str(s)) for s in e.free_symbols - if str(s) in field), zero) + return sum((dpart(e, s) * comp(field, str(s)) for s in e.free_symbols if str(s) in field), zero) def vec(exprs, vals): out = [] for e in exprs: - v = ck.value(e, sym_list, vals, mod, skey='vd') + v = ck.value(e, sym_list, vals, mod, skey="vd") if v is None: return None out.append(v) @@ -242,7 +240,7 @@ def field_at(x, vals): for nm, e in x.items(): if nm not in pos_of or e == zero: continue - v = ck.value(e, sym_list, vals, mod, skey='vd') + v = ck.value(e, sym_list, vals, mod, skey="vd") if v is None: return None out[pos_of[nm]] = v @@ -257,9 +255,10 @@ def bracket(r, j): key = (r, j) if key not in bracket_cache: x, Fr = Xm[r][j], {nm: F[r].get(nm, zero) for nm in states} - bracket_cache[key] = [deriv_dir(comp(Fr, nm), x) - deriv_dir(comp(x, nm), Fr) - if nm in Fr else -deriv_dir(comp(x, nm), Fr) - for nm in coords] + bracket_cache[key] = [ + deriv_dir(comp(Fr, nm), x) - deriv_dir(comp(x, nm), Fr) if nm in Fr else -deriv_dir(comp(x, nm), Fr) + for nm in coords + ] return bracket_cache[key] def fields_at(r, vals): @@ -288,20 +287,21 @@ def lam(key, exprs): fn = lam_cache.get(key) if fn is None: ex = [] - frac = spy.Function('Fraction') + frac = spy.Function("Fraction") for e in exprs: e = spy.sympify(e) e = e.xreplace({x: spy.Rational(str(x)) for x in e.atoms(spy.Float)}) - e = e.xreplace({x: frac(x.p, x.q) for x in e.atoms(spy.Rational) - if not x.is_Integer}) + e = e.xreplace({x: frac(x.p, x.q) for x in e.atoms(spy.Rational) if not x.is_Integer}) ex.append(e) - fn = lam_cache[key] = spy.lambdify(sym_list, ex, modules=[{'Fraction': Fraction}]) + fn = lam_cache[key] = spy.lambdify(sym_list, ex, modules=[{"Fraction": Fraction}]) return fn def along(key, exprs, vals, dirv): """Values and derivatives of exprs at vals along dirv (residues), or None.""" - args = [_DualMod(int(v.numerator) % mod * pow(int(v.denominator) % mod, mod - 2, mod), - d, mod) for v, d in zip(vals, dirv)] + args = [ + _DualMod(int(v.numerator) % mod * pow(int(v.denominator) % mod, mod - 2, mod), d, mod) + for v, d in zip(vals, dirv) + ] try: out = lam(key, exprs)(*args) except SYMPY_FAILS as exc: @@ -327,8 +327,7 @@ def along(key, exprs, vals, dirv): def rat_idx(r): if r not in rat_of: - rat_of[r] = [k for k, nm in enumerate(states) - if not F[r].get(nm, zero).atoms(spy.Function)] + rat_of[r] = [k for k, nm in enumerate(states) if not F[r].get(nm, zero).atoms(spy.Function)] return rat_of[r] def bracket_at(r, j, vals): @@ -340,7 +339,7 @@ def bracket_at(r, j, vals): n_s = len(states) ri = rat_idx(r) df = [0] * n_s - fx = along(('F', r), [F[r].get(states[k], zero) for k in ri], vals, x) + fx = along(("F", r), [F[r].get(states[k], zero) for k in ri], vals, x) if fx is None: return None for k, (_, d) in zip(ri, fx): @@ -350,7 +349,7 @@ def bracket_at(r, j, vals): e = F[r].get(states[k], zero) if not supp & {str(t) for t in e.free_symbols}: continue - v = ck.value(deriv_dir(e, X), sym_list, vals, mod, skey='vd') + v = ck.value(deriv_dir(e, X), sym_list, vals, mod, skey="vd") if v is None: return None df[k] = v @@ -360,7 +359,7 @@ def bracket_at(r, j, vals): cx = comp(X, nm) dx = 0 if cx != zero: - dx = ck.value(deriv_dir(cx, Fr), sym_list, vals, mod, skey='vd') + dx = ck.value(deriv_dir(cx, Fr), sym_list, vals, mod, skey="vd") if dx is None: return None out.append(((df[k] if k < n_s else 0) - dx) % mod) @@ -376,21 +375,20 @@ def close(r, S): x = field_at(Xm[r][j], vals) hr = [h for h in H[r] if not h.atoms(spy.Function)] hs = [h for h in H[r] if h.atoms(spy.Function)] - ha = along(('H', r), hr, vals, x) if x is not None else None + ha = along(("H", r), hr, vals, x) if x is not None else None hb = vec([deriv_dir(h, Xm[r][j]) for h in hs], vals) if hs else [] if ha is None or hb is None or any(d for _, d in ha) or any(hb): - return None, 'regime %d: a field changes the output' % (r + 1) + return None, "regime %d: a field changes the output" % (r + 1) bv = bracket_at(r, j, vals) if bv is None: - return None, 'regime %d: a bracket has a pole' % (r + 1) + return None, "regime %d: a bracket has a pole" % (r + 1) sup = support(r, vals, bv) if sup is None: - return None, ('regime %d: the fields are not invariant under the ' - 'dynamics' % (r + 1)) + return None, ("regime %d: the fields are not invariant under the dynamics" % (r + 1)) for k in sup - S: S.add(k) todo.append(k) - return S, '' + return S, "" def image(ev_list, vals, x): """D E applied to the field or vector x at the point, and E of the point.""" @@ -398,84 +396,95 @@ def image(ev_list, vals, x): img = dict(val_of) xd = dict(zip(coords, x)) for e in ev_list: - ve = ck.expr(e['value']) - v = ck.value(ve, sym_list, vals, mod, skey='vd') + ve = ck.expr(e["value"]) + v = ck.value(ve, sym_list, vals, mod, skey="vd") if v is None: return None, None dv = 0 for s_ in ve.free_symbols: - d = ck.value(spy.diff(ve, s_), sym_list, vals, mod, skey='vd') + d = ck.value(spy.diff(ve, s_), sym_list, vals, mod, skey="vd") if d is None: return None, None dv = (dv + d * x[coords.index(str(s_))]) % mod if str(s_) in coords else dv - s0 = int(val_of[e['var']]) % mod - img[e['var']] = Fraction({'replace': v, 'add': (s0 + v) % mod, - 'multiply': s0 * v % mod}[e['method']]) - xd[e['var']] = {'replace': dv, 'add': (xd[e['var']] + dv) % mod, - 'multiply': (xd[e['var']] * v + s0 * dv) % mod}[e['method']] + s0 = int(val_of[e["var"]]) % mod + img[e["var"]] = Fraction({"replace": v, "add": (s0 + v) % mod, "multiply": s0 * v % mod}[e["method"]]) + xd[e["var"]] = { + "replace": dv, + "add": (xd[e["var"]] + dv) % mod, + "multiply": (xd[e["var"]] * v + s0 * dv) % mod, + }[e["method"]] return [xd[nm] for nm in coords], [img[nm] for nm in coords] visits, crossed = [], [] joins_of = {} for ev in events: - if ev.get('lift') is not None: - joins_of.setdefault(int(ev['lift']), []).append(ev) + if ev.get("lift") is not None: + joins_of.setdefault(int(ev["lift"]), []).append(ev) for li, lf in enumerate(lifts): - r = int(lf['regime']) - pt = {str(k): int(v) for k, v in dict(lf['point']).items()} + r = int(lf["regime"]) + pt = {str(k): int(v) for k, v in dict(lf["point"]).items()} vals0 = [Fraction(pt.get(nm, 0)) for nm in coords] - taus = [ck.expr(t) for t in _as_list(lf.get('times', []))] + taus = [ck.expr(t) for t in _as_list(lf.get("times", []))] mod = p - vecs = [{str(k): int(x) % p for k, x in dict(v).items()} - for v in _as_list(lf['vectors'])] + vecs = [{str(k): int(x) % p for k, x in dict(v).items()} for v in _as_list(lf["vectors"])] # (D) the lifted directions in the span at the start, and the fields they reach S = set() for vd in vecs: sup = support(r, vals0, [vd.get(nm, 0) for nm in coords]) if sup is None: - return {'ok': False, 'why': 'a kernel direction is not in the span of the fields'} + return {"ok": False, "why": "a kernel direction is not in the span of the fields"} S |= sup for tau in taus: - dv = [ck.value(spy.diff(tau, s_), sym_list, vals0, mod, skey='vd') for s_ in tau.free_symbols] - if any(x is None for x in dv) or sum( - x * vd.get(str(sy), 0) for x, sy in zip(dv, tau.free_symbols)) % mod: - return {'ok': False, 'why': 'a kernel direction moves an event time'} + dv = [ck.value(spy.diff(tau, s_), sym_list, vals0, mod, skey="vd") for s_ in tau.free_symbols] + if ( + any(x is None for x in dv) + or sum(x * vd.get(str(sy), 0) for x, sy in zip(dv, tau.free_symbols)) % mod + ): + return {"ok": False, "why": "a kernel direction moves an event time"} mod = q S, why = close(r, S) if S is None: - return {'ok': False, 'why': why} + return {"ok": False, "why": why} visits.append((r, frozenset(S))) us = [[vd.get(nm, 0) if nm in free else 0 for nm in coords] for vd in vecs] # (C) the joins of the chain in order for ev in joins_of.get(li, []): - r2 = int(ev['to']) - evs = _as_list(ev['ev']) + r2 = int(ev["to"]) + evs = _as_list(ev["ev"]) S2 = set() for _ in range(npts): vals = rand_point() items = [field_at(Xm[r][j], vals) for j in S] + us for x in items: if x is None: - return {'ok': False, 'why': 'a field has a pole before an event'} + return {"ok": False, "why": "a field has a pole before an event"} xi, zi = image(evs, vals, x) if xi is None: - return {'ok': False, 'why': 'an event value has a pole'} + return {"ok": False, "why": "an event value has a pole"} sup = support(r2, zi, xi) if sup is None: - return {'ok': False, 'why': 'an event leaves the span of the fields'} + return {"ok": False, "why": "an event leaves the span of the fields"} S2 |= sup crossed.append((r, r2, evs, frozenset(S), us)) S, why = close(r2, S2) if S is None: - return {'ok': False, 'why': why} + return {"ok": False, "why": why} visits.append((r2, frozenset(S))) r = r2 if q == p: - return {'ok': True, 'why': ''} - rows = {'F': F, 'H': H, 'X': Xm, 'units': len(free), 'sym': dict(zip(coords, sym_list)), - 'expr': ck.expr, 'deriv': deriv_dir, 'bracket': bracket} - return {'ok': True, 'why': '', 'bound': distribution_bound(rows, visits, crossed, q, npts)} + return {"ok": True, "why": ""} + rows = { + "F": F, + "H": H, + "X": Xm, + "units": len(free), + "sym": dict(zip(coords, sym_list)), + "expr": ck.expr, + "deriv": deriv_dir, + "bracket": bracket, + } + return {"ok": True, "why": "", "bound": distribution_bound(rows, visits, crossed, q, npts)} # operations of the expressions of one check beyond which no degree bound is taken @@ -485,8 +494,9 @@ def image(ev_list, vals, x): def distribution_bound(rows, visits, crossed, q, npts): """{'degree', 'points', 'prime', 'probability'} of verify_distribution's checks, or {'applies': False}.""" from ..detection.bound import _rational, _vector_degree + zero = spy.Integer(0) - sym = rows['sym'] + sym = rows["sym"] def deg(exprs): exprs = [spy.sympify(e) for e in exprs] @@ -494,49 +504,54 @@ def deg(exprs): if not exprs: return 0 if sum(spy.count_ops(e) for e in exprs) > _BOUND_OPS: - raise InapplicableError('an expression is too large for a degree bound') + raise InapplicableError("an expression is too large for a degree bound") if not all(_rational(e) for e in exprs): - raise InapplicableError('an expression is not rational') + raise InapplicableError("an expression is not rational") return _vector_degree(exprs) def image(evs, x): """D E applied to the field x and E itself, symbolically, as image() of the check.""" img, xd = dict(sym), dict(x) for e in evs: - ve = rows['expr'](e['value']) + ve = rows["expr"](e["value"]) dv = sum((spy.diff(ve, s_) * x.get(str(s_), zero) for s_ in ve.free_symbols), zero) - s0, var = sym[e['var']], e['var'] - img[var] = {'replace': ve, 'add': s0 + ve, 'multiply': s0 * ve}[e['method']] - xd[var] = {'replace': dv, 'add': xd.get(var, zero) + dv, - 'multiply': xd.get(var, zero) * ve + s0 * dv}[e['method']] + s0, var = sym[e["var"]], e["var"] + img[var] = {"replace": ve, "add": s0 + ve, "multiply": s0 * ve}[e["method"]] + xd[var] = {"replace": dv, "add": xd.get(var, zero) + dv, "multiply": xd.get(var, zero) * ve + s0 * dv}[ + e["method"] + ] return xd, {sym[k]: v for k, v in img.items()} try: D, checks = 0, 0 for r, S in visits: - span = sum(deg(X.values()) for X in rows['X'][r]) + span = sum(deg(X.values()) for X in rows["X"][r]) for j in S: - X = rows['X'][r][j] - tests = [rows['bracket'](r, j)] + [[rows['deriv'](h, X)] for h in rows['H'][r]] + X = rows["X"][r][j] + tests = [rows["bracket"](r, j)] + [[rows["deriv"](h, X)] for h in rows["H"][r]] D = max([D] + [span + deg(t) for t in tests]) checks += len(tests) for r, r2, evs, S, us in crossed: - items = [rows['X'][r][j] for j in S] + items = [rows["X"][r][j] for j in S] items += [{nm: spy.Integer(int(c)) for nm, c in zip(sym, u) if c} for u in us] sub = image(evs, {})[1] - span = sum(deg([v.xreplace(sub) for v in X.values()]) for X in rows['X'][r2]) + span = sum(deg([v.xreplace(sub) for v in X.values()]) for X in rows["X"][r2]) for x in items: D = max(D, span + deg(image(evs, x)[0].values())) checks += 1 except InapplicableError as exc: - return {'applies': False, 'why': str(exc)} + return {"applies": False, "why": str(exc)} except SYMPY_FAILS as exc: sympy_fail(exc) - return {'applies': False, 'why': 'no degree bound of an expression'} + return {"applies": False, "why": "no degree bound of an expression"} # every identity and every decomposition that picks the fields reached m = 2 * checks - return {'degree': int(D), 'points': int(npts), 'prime': int(q), - 'probability': float(min(1.0, m * min(1.0, D / (q - 3)) ** npts))} + return { + "degree": int(D), + "points": int(npts), + "prime": int(q), + "probability": float(min(1.0, m * min(1.0, D / (q - 3)) ** npts)), + } def static_fields_symbolic(conds, param_names, forcings=None): @@ -548,19 +563,20 @@ def static_fields_symbolic(conds, param_names, forcings=None): def eqs(lines): out = {} for ln in _as_list(lines): - k, v = str(ln).split('=', 1) + k, v = str(ln).split("=", 1) out[k.strip()] = v.strip() return out def evkey(evs): - return tuple((str(e['var']), str(e['value']), str(e['method'])) for e in _as_list(evs)) + return tuple((str(e["var"]), str(e["value"]), str(e["method"])) for e in _as_list(evs)) + lines = [] for c in conds: - lines += list(eqs(c['rest']).values()) - for sg in c['segs']: - lines += list(eqs(sg['f']).values()) + list(eqs(sg['g']).values()) - lines += [str(e['value']) for e in _as_list(sg.get('ev'))] - lines += [str(e['value']) for e in _as_list(c.get('t0'))] + lines += list(eqs(c["rest"]).values()) + for sg in c["segs"]: + lines += list(eqs(sg["f"]).values()) + list(eqs(sg["g"]).values()) + lines += [str(e["value"]) for e in _as_list(sg.get("ev"))] + lines += [str(e["value"]) for e in _as_list(c.get("t0"))] _, parse0 = _make_local_parse(lines + pnames) parse = functools.lru_cache(maxsize=None)(parse0) @@ -570,28 +586,38 @@ def evkey(evs): static_of = [] reduced = set() for c in conds: - key = (tuple(_as_list(c['rest'])), - tuple((tuple(_as_list(sg['f'])), tuple(_as_list(sg['g'])), evkey(sg.get('ev'))) - for sg in c['segs']), evkey(c.get('t0'))) + key = ( + tuple(_as_list(c["rest"])), + tuple((tuple(_as_list(sg["f"])), tuple(_as_list(sg["g"])), evkey(sg.get("ev"))) for sg in c["segs"]), + evkey(c.get("t0")), + ) if key in info: - static_of.append(info[key]['static']) + static_of.append(info[key]["static"]) continue - rest = {k: parse(v) for k, v in eqs(c['rest']).items()} - segs = [({k: parse(v) for k, v in eqs(sg['f']).items()}, - {k: parse(v) for k, v in eqs(sg['g']).items()}, - _as_list(sg.get('ev'))) for sg in c['segs']] + rest = {k: parse(v) for k, v in eqs(c["rest"]).items()} + segs = [ + ( + {k: parse(v) for k, v in eqs(sg["f"]).items()}, + {k: parse(v) for k, v in eqs(sg["g"]).items()}, + _as_list(sg.get("ev")), + ) + for sg in c["segs"] + ] states = set(rest) | {k for f, _, _ in segs for k in f} # forcings held and the condition's zero states (as the resting model has them) held = {spy.Symbol(x): 0 for x in forcings} - held.update({spy.Symbol(str(z)): 0 for z in _as_list(c.get('zero'))}) + held.update({spy.Symbol(str(z)): 0 for z in _as_list(c.get("zero"))}) rest = {k: v.xreplace(held) for k, v in rest.items()} moved = set() - for ev in list(_as_list(c.get('t0'))) + [e for _, _, evs in segs for e in evs]: - v = parse(str(ev['value'])) - m = str(ev['method']) - var = str(ev['var']) - if (m == 'add' and v != 0) or (m == 'multiply' and v != 1) or \ - (m == 'replace' and not (var in forcings and v == 0)): + for ev in list(_as_list(c.get("t0"))) + [e for _, _, evs in segs for e in evs]: + v = parse(str(ev["value"])) + m = str(ev["method"]) + var = str(ev["var"]) + if ( + (m == "add" and v != 0) + or (m == "multiply" and v != 1) + or (m == "replace" and not (var in forcings and v == 0)) + ): moved.add(var) dyn = set(moved) while True: @@ -602,8 +628,11 @@ def evkey(evs): e = f.get(s_) if e is None: continue - if {str(x) for x in e.free_symbols} & dyn or r0 is None or \ - (e.xreplace(held) != r0 and spy.expand(e.xreplace(held) - r0) != 0): + if ( + {str(x) for x in e.free_symbols} & dyn + or r0 is None + or (e.xreplace(held) != r0 and spy.expand(e.xreplace(held) - r0) != 0) + ): dyn.add(s_) break if len(dyn) == n0: @@ -620,23 +649,22 @@ def evkey(evs): for e in g.values(): seen |= e.free_symbols for ev in evs: - seen |= parse(str(ev['value'])).free_symbols - for ev in _as_list(c.get('t0')): - seen |= parse(str(ev['value'])).free_symbols + seen |= parse(str(ev["value"])).free_symbols + for ev in _as_list(c.get("t0")): + seen |= parse(str(ev["value"])).free_symbols reduced |= {str(x) for x in seen if str(x) in pset} - info[key] = {'static': static, 'rest': rest, 'seen': seen, - 'zero': [str(z) for z in _as_list(c.get('zero'))]} + info[key] = {"static": static, "rest": rest, "seen": seen, "zero": [str(z) for z in _as_list(c.get("zero"))]} static_of.append(static) # a parameter outside every static resting equation (one that enters only through # a recast atom, say) is not absorbed in_static = set() for inf in info.values(): - for x in inf['static']: - if x in inf['rest']: - in_static |= {str(y) for y in inf['rest'][x].free_symbols} + for x in inf["static"]: + if x in inf["rest"]: + in_static |= {str(y) for y in inf["rest"][x].free_symbols} absorbed = [x for x in pnames if x not in reduced and x in in_static] if not absorbed: - return {'fields': [], 'absorbed': [], 'static': static_of} + return {"fields": [], "absorbed": [], "static": static_of} aset = {parse(x) for x in absorbed} # pass 2: fields that leave every static rest in place (delta rho = 0). Each resting @@ -644,8 +672,8 @@ def evkey(evs): # a row d e / d theta_A; zero states (forced or sink clusters) are taken out first rows = [] for inf in info.values(): - rest, static = inf['rest'], inf['static'] - zero = {spy.Symbol(x): 0 for x in inf.get('zero', [])} + rest, static = inf["rest"], inf["static"] + zero = {spy.Symbol(x): 0 for x in inf.get("zero", [])} for x in static: if x not in rest or spy.Symbol(x) in zero: continue @@ -659,27 +687,22 @@ def evkey(evs): except spy.PolynomialError: linear = False if not linear: - return {'fields': [], 'why': 'a static resting equation not linear in the state', - 'static': static_of} + return {"fields": [], "why": "a static resting equation not linear in the state", "static": static_of} try: own = spy.solve(num, xs) except NotImplementedError: own = [] if len(own) != 1: - return {'fields': [], 'why': 'a static resting equation not solved for the state', - 'static': static_of} - rows.append([spy.cancel(spy.diff(e, a).xreplace({xs: own[0]})) for a in - [parse(y) for y in absorbed]]) + return {"fields": [], "why": "a static resting equation not solved for the state", "static": static_of} + rows.append([spy.cancel(spy.diff(e, a).xreplace({xs: own[0]})) for a in [parse(y) for y in absorbed]]) if state.env("STATICDIAG"): - sys.stderr.write("[staticdiag] %d row(s) over %d absorbed parameter(s)\n" - % (len(rows), len(absorbed))) + sys.stderr.write("[staticdiag] %d row(s) over %d absorbed parameter(s)\n" % (len(rows), len(absorbed))) asy = [parse(x) for x in absorbed] if rows: basis = spy.Matrix(rows).nullspace(simplify=True) else: - basis = [spy.Matrix([1 if j == i else 0 for j in range(len(asy))]) - for i in range(len(asy))] - state_syms = {spy.Symbol(x) for inf in info.values() for x in inf['rest']} + basis = [spy.Matrix([1 if j == i else 0 for j in range(len(asy))]) for i in range(len(asy))] + state_syms = {spy.Symbol(x) for inf in info.values() for x in inf["rest"]} fields = [] for v in basis: v = spy.Matrix([spy.cancel(spy.together(x)) for x in v]) @@ -688,46 +711,47 @@ def evkey(evs): den = spy.lcm([spy.fraction(x)[1] for x in v]) v = spy.Matrix([spy.factor(spy.cancel(x * den)) for x in v]) fields.append({absorbed[i]: str(v[i]) for i in range(len(absorbed)) if v[i] != 0}) - return {'fields': fields, 'absorbed': absorbed, 'static': static_of} + return {"fields": fields, "absorbed": absorbed, "static": static_of} def extend_fields(fields, ic_lines, event_groups, states): """Fields extended to the parameters set by initial values or events; a state-dependent one is dropped.""" ic_lines = _as_list(ic_lines) groups = [_as_list(g) for g in _as_list(event_groups)] - lines = list(ic_lines) + ['_ = %s' % e['value'] for g in groups for e in g] + lines = list(ic_lines) + ["_ = %s" % e["value"] for g in groups for e in g] for fld in _as_list(fields): - lines += ['_ = %s' % v for v in dict(fld).values()] - local, parse = _make_local_parse(lines + ['_ = %s' % st for st in _as_list(states)]) + lines += ["_ = %s" % v for v in dict(fld).values()] + local, parse = _make_local_parse(lines + ["_ = %s" % st for st in _as_list(states)]) state_set = set(_as_list(states)) + def sym(nm): return local.get(nm, spy.Symbol(nm)) + state_syms = {sym(nm) for nm in state_set} out = [] for fld in _as_list(fields): eta = {str(k): spy.sympify(parse(str(v))) for k, v in dict(fld).items()} ext = {} for l in ic_lines: - lhs, rhs = _clean(l).split('=', 1) + lhs, rhs = _clean(l).split("=", 1) x, e = lhs.strip(), spy.sympify(parse(rhs)) if e.is_Symbol and str(e) not in state_set: ext[str(e)] = eta.get(x, spy.Integer(0)).subs(sym(x), e) for g in groups: - vals = {str(ev['var']): spy.sympify(parse(str(ev['value']))) for ev in g} + vals = {str(ev["var"]): spy.sympify(parse(str(ev["value"]))) for ev in g} E = {} for ev in g: - s_, v = str(ev['var']), vals[str(ev['var'])] + s_, v = str(ev["var"]), vals[str(ev["var"])] xs = sym(s_) - E[xs] = {'add': xs + v, 'replace': v, 'multiply': xs * v}[ev['method']] + E[xs] = {"add": xs + v, "replace": v, "multiply": xs * v}[ev["method"]] for ev in g: - s_, v = str(ev['var']), vals[str(ev['var'])] + s_, v = str(ev["var"]), vals[str(ev["var"])] if not (v.is_Symbol and str(v) not in state_set): continue xs = sym(s_) es = eta.get(s_, spy.Integer(0)) e_e = es.xreplace(E) if E else es - ext[str(v)] = {'add': e_e - es, 'replace': e_e, - 'multiply': (e_e - v * es) / xs}[ev['method']] + ext[str(v)] = {"add": e_e - es, "replace": e_e, "multiply": (e_e - v * es) / xs}[ev["method"]] ok = True for k, val in ext.items(): val = spy.simplify(val) @@ -750,14 +774,12 @@ def lift_start(ic_lines, t0events, point, vector, p, joint=False): vv = {str(k): int(v) % p for k, v in dict(vector).items()} names = sorted(pt) # parsed lines, lambdified values and derivatives are reused across points and primes - key = (tuple(ic_lines), tuple((e['var'], str(e['value']), e['method']) for e in evs), - tuple(names)) + key = (tuple(ic_lines), tuple((e["var"], str(e["value"]), e["method"]) for e in evs), tuple(names)) ck = _LIFT_CACHE.get(key) if ck is None: if len(_LIFT_CACHE) > 256: _LIFT_CACHE.clear() - ck = _DistCheck(ic_lines + ['_ = %s' % e['value'] for e in evs] + - ['_ = %s' % k for k in names]) + ck = _DistCheck(ic_lines + ["_ = %s" % e["value"] for e in evs] + ["_ = %s" % k for k in names]) ck.parsed, ck.derivs = {}, {} _LIFT_CACHE[key] = ck syms = [ck.local.get(n, spy.Symbol(n)) for n in names] @@ -786,20 +808,20 @@ def val_and_dir(e): if not joint: for l in ic_lines: - lhs, e = _clean(l).split('=', 1) + lhs, e = _clean(l).split("=", 1) x, dx = val_and_dir(parsed(e)) if x is None: return None pt[lhs.strip()], vv[lhs.strip()] = x, dx for e in evs: - v, dv = val_and_dir(parsed(str(e['value']))) + v, dv = val_and_dir(parsed(str(e["value"]))) if v is None: return None - s0, d0 = pt.get(e['var'], 0), vv.get(e['var'], 0) - if e['method'] == 'replace': - pt[e['var']], vv[e['var']] = v, dv - elif e['method'] == 'add': - pt[e['var']], vv[e['var']] = (s0 + v) % p, (d0 + dv) % p + s0, d0 = pt.get(e["var"], 0), vv.get(e["var"], 0) + if e["method"] == "replace": + pt[e["var"]], vv[e["var"]] = v, dv + elif e["method"] == "add": + pt[e["var"]], vv[e["var"]] = (s0 + v) % p, (d0 + dv) % p else: - pt[e['var']], vv[e['var']] = s0 * v % p, (d0 * v + s0 * dv) % p - return {'point': pt, 'vector': vv} + pt[e["var"]], vv[e["var"]] = s0 * v % p, (d0 * v + s0 * dv) % p + return {"point": pt, "vector": vv} diff --git a/src/symident/sym/gfpoly.py b/src/symident/sym/gfpoly.py index d8be789..8fbc570 100644 --- a/src/symident/sym/gfpoly.py +++ b/src/symident/sym/gfpoly.py @@ -78,8 +78,7 @@ def _eval_bipoly_dict(bip, paramvals, p): def _dp_mul(a, b, nv, p): """Product of two dict polynomials mod p.""" if len(a) * len(b) * nv < 4096: - pairs = ((tuple(ma[k] + mb[k] for k in range(nv)), ca * cb) - for ma, ca in a.items() for mb, cb in b.items()) + pairs = ((tuple(ma[k] + mb[k] for k in range(nv)), ca * cb) for ma, ca in a.items() for mb, cb in b.items()) else: A = np.array(list(a), dtype=np.int64).reshape(len(a), nv) B = np.array(list(b), dtype=np.int64).reshape(len(b), nv) @@ -117,7 +116,7 @@ def _dp_subst(d, i, expr, nv, p): return out -_REDUCE_TERMS_CAP = 2000 # past this polynomial size msolve is faster than the reduction +_REDUCE_TERMS_CAP = 2000 # past this polynomial size msolve is faster than the reduction def _dp_add(a, b, p): @@ -136,7 +135,7 @@ def _dp_coeffs(d, i): """Coefficients {k: dict poly free of var i} of d as a polynomial in var i.""" cs = {} for m, c in d.items(): - cs.setdefault(m[i], {})[m[:i] + (0,) + m[i + 1:]] = c + cs.setdefault(m[i], {})[m[:i] + (0,) + m[i + 1 :]] = c return cs @@ -207,9 +206,14 @@ def _reduce_system(dps, nv, p): continue cs = _dp_coeffs(dps[j], i) a = cs[1] - key = (0 if all(not any(m) for m in a) else 1, 0 if i == j else 1, - max(sum(m) for m in a) + occ[i] - 1, - len(a) + len(cs.get(0, {})), i, j) + key = ( + 0 if all(not any(m) for m in a) else 1, + 0 if i == j else 1, + max(sum(m) for m in a) + occ[i] - 1, + len(a) + len(cs.get(0, {})), + i, + j, + ) if best is None or key < best[0]: best = (key, j, i, a, cs.get(0, {})) if best is None: @@ -229,7 +233,7 @@ def _reduce_system(dps, nv, p): def _pow_mod(base, e, f, p): """base^e modulo the monic dense polynomial f over GF(p), highest degree first.""" n = len(f) - 1 - low = [c % p for c in f[1:]] # x^n = -(low) in the quotient ring + low = [c % p for c in f[1:]] # x^n = -(low) in the quotient ring def mulmod(a, b): # a, b highest degree first, padded to n; the reduced product highest degree first @@ -239,7 +243,7 @@ def mulmod(a, b): if ai: for j, bj in enumerate(b): prod[i + j] += ai * bj - for k in range(2 * n - 2, n - 1, -1): # reduce the degrees >= n from the top + for k in range(2 * n - 2, n - 1, -1): # reduce the degrees >= n from the top c = prod[k] % p if c: for j, lj in enumerate(low): @@ -267,6 +271,7 @@ def _x_pow_mod(f, p): def _split_roots(g, p, a=1): """The roots over GF(p) of the monic g, a product of distinct linear factors.""" from ..gfp import sqrt_mod + if len(g) == 2: return [(-g[1]) % p] if len(g) == 3: @@ -281,8 +286,9 @@ def _split_roots(g, p, a=1): d = _gft.gf_gcd(g, h, p, _ZZ) if 1 < len(d) < len(g): q = _gft.gf_quo(g, d, p, _ZZ) - return _split_roots(_gft.gf_monic(d, p, _ZZ)[1], p, a + 1) + \ - _split_roots(_gft.gf_monic(q, p, _ZZ)[1], p, a + 1) + return _split_roots(_gft.gf_monic(d, p, _ZZ)[1], p, a + 1) + _split_roots( + _gft.gf_monic(q, p, _ZZ)[1], p, a + 1 + ) a += 1 @@ -369,8 +375,10 @@ def _core_candidates(resid, core, p): return None bound = max(sum(k) for k in P1) * max(sum(k) for k in P2) rng = session.current().rng("gfpoly.gcd", p) - dg = min(len(_gft.gf_gcd(_bi_at_u(P1, a, p), _bi_at_u(P2, a, p), p, _ZZ)) - 1 - for a in (rng.randrange(1, p), rng.randrange(1, p))) + dg = min( + len(_gft.gf_gcd(_bi_at_u(P1, a, p), _bi_at_u(P2, a, p), p, _ZZ)) - 1 + for a in (rng.randrange(1, p), rng.randrange(1, p)) + ) n1, n2 = max(k[1] for k in P1), max(k[1] for k in P2) xs, ys = [], [] a = 0 @@ -381,7 +389,7 @@ def _core_candidates(resid, core, p): continue G = _gft.gf_gcd(f1, f2, p, _ZZ) if len(G) - 1 > dg: - r = 0 # a common root on top of g: a root of the resultant + r = 0 # a common root on top of g: a root of the resultant else: r = _gf_resultant(_gft.gf_quo(f1, G, p, _ZZ), _gft.gf_quo(f2, G, p, _ZZ), p) xs.append(a) @@ -437,7 +445,7 @@ def _solve_states_reduced(dps, solve_states, p, on_branch=None, accept=None): break # a pinned branch without a root here leaves the point out, as a point without any root if first is None or (accept is not None and taken is None): - return None, {'ok': False, 'why': 'no consistent interior point'} + return None, {"ok": False, "why": "no consistent interior point"} if several: (on_branch or note_branch)(solve_states) taken = first if taken is None else taken @@ -447,5 +455,10 @@ def _solve_states_reduced(dps, solve_states, p, on_branch=None, accept=None): def note_branch(states): """Record that the resting states have several interior roots modulo p and the first is taken.""" from .. import session - session.note("branches", "resting states " + ", ".join(sorted(map(str, states))) + - ": several interior roots modulo p, the first is taken") + + session.note( + "branches", + "resting states " + + ", ".join(sorted(map(str, states))) + + ": several interior roots modulo p, the first is taken", + ) diff --git a/src/symident/sym/invariants.py b/src/symident/sym/invariants.py index 6a4a53d..3862a5d 100644 --- a/src/symident/sym/invariants.py +++ b/src/symident/sym/invariants.py @@ -9,9 +9,9 @@ def _parse_generators(gens, extra_lines): """Shared symbol table + parsed xi dicts for a list of generator dicts.""" gens = _as_list(gens) - all_lines = list(extra_lines) + \ - [str(v) for g in gens for v in g.values()] + \ - [str(kk) for g in gens for kk in g.keys()] + all_lines = ( + list(extra_lines) + [str(v) for g in gens for v in g.values()] + [str(kk) for g in gens for kk in g.keys()] + ) _, parse = _make_local_parse(all_lines) xis = [{str(kk): parse(str(v)) for kk, v in g.items()} for g in gens] return xis, parse @@ -24,8 +24,7 @@ def module_reduce_replay(rows, cols, schedule): k = len(rows) all_lines = [str(v) for r in rows for v in r.values()] + cols _, parse = _make_local_parse(all_lines) - E = [{c: (parse(str(r[c])) if c in r and str(r[c]) != "0" - else spy.Integer(0)) for c in cols} for r in rows] + E = [{c: (parse(str(r[c])) if c in r and str(r[c]) != "0" else spy.Integer(0)) for c in cols} for r in rows] C = [[spy.Integer(1 if i == j else 0) for j in range(k)] for i in range(k)] for st in _as_list(schedule): r = int(st[0]) - 1 @@ -41,9 +40,10 @@ def module_reduce_replay(rows, cols, schedule): E[j][c2] = spy.cancel(E[j][c2] - m * E[r][c2]) for l in range(k): C[j][l] = spy.cancel(C[j][l] - m * C[r][l]) - return {'rows': [{c: str(E[j][c]) for c in cols if E[j][c] != 0} - for j in range(k)], - 'combo': [[str(x) for x in row] for row in C]} + return { + "rows": [{c: str(E[j][c]) for c in cols if E[j][c] != 0} for j in range(k)], + "combo": [[str(x) for x in row] for row in C], + } def darboux_cofactors(candidates, generators): @@ -77,7 +77,7 @@ def darboux_cofactors(candidates, generators): kept.append(P) Ps.append(str(P)) lams.append(lam) - return {'Ps': Ps, 'lams': lams} + return {"Ps": Ps, "lams": lams} def verify_invariants(invariants, generators): @@ -85,6 +85,7 @@ def verify_invariants(invariants, generators): invs = [str(i) for i in _as_list(invariants)] xis, parse = _parse_generators(generators, invs) out = [] + def _real(e): return e.subs({t: spy.Symbol(t.name, real=True) for t in e.free_symbols}) @@ -113,16 +114,14 @@ def _real(e): def integrating_factor_integral(Mstr, xi1, xi2, z1, z2): """First integral by quadrature from a 2D integrating factor, or None if unevaluated or X(I) != 0.""" - _, parse = _make_local_parse([str(Mstr), str(xi1), str(xi2), - str(z1), str(z2)]) + _, parse = _make_local_parse([str(Mstr), str(xi1), str(xi2), str(z1), str(z2)]) try: M = parse(str(Mstr)) f1 = parse(str(xi1)) f2 = parse(str(xi2)) # real symbols throughout: ratint then prefers real atan/log forms, and # a leftover complex-logarithm pair can be realified by re() - real = {s: spy.Symbol(s.name, real=True) - for s in (M.free_symbols | f1.free_symbols | f2.free_symbols)} + real = {s: spy.Symbol(s.name, real=True) for s in (M.free_symbols | f1.free_symbols | f2.free_symbols)} M = M.subs(real) f1 = f1.subs(real) f2 = f2.subs(real) diff --git a/src/symident/sym/jets.py b/src/symident/sym/jets.py index bfdc66d..550c8d7 100644 --- a/src/symident/sym/jets.py +++ b/src/symident/sym/jets.py @@ -25,7 +25,7 @@ def jet_generator(conds, support, anchor, max_order=8, max_chars=20000, work_lim work = [0, 50 * max_chars if work_limit is None else int(work_limit)] primary, extra = _jet_expand_chains(conds) res = _jet_core(primary, support, anchor, max_order, max_chars, work) - if not res['ok'] and extra and str(res.get('reason', '')).startswith('rank'): + if not res["ok"] and extra and str(res.get("reason", "")).startswith("rank"): res = _jet_core(primary + extra, support, anchor, max_order, max_chars, work) return res @@ -36,11 +36,10 @@ def _jet_core(conds, support, anchor, max_order, max_chars, work): anchor = str(anchor) m = len(support) if m < 2 or anchor not in support: - return {'ok': False, 'reason': 'support'} + return {"ok": False, "reason": "support"} lines = [] for c in conds: - lines += list(_as_list(c['f'])) + list(_as_list(c['ic'])) + \ - [str(x) for x in _as_list(c['g'])] + lines += list(_as_list(c["f"])) + list(_as_list(c["ic"])) + [str(x) for x in _as_list(c["g"])] lines += support local, parse = _make_local_parse(lines) zs = [local.get(s, spy.Symbol(s)) for s in support] @@ -55,14 +54,14 @@ def num(e): parsed = [] for c in conds: - fl = [l.split(' = ', 1) for l in _as_list(c['f'])] + fl = [l.split(" = ", 1) for l in _as_list(c["f"])] states = [local.get(a.strip(), spy.Symbol(a.strip())) for a, _ in fl] rhs = [spy.sympify(parse(b)) for _, b in fl] icd = {} - for l in _as_list(c['ic']): - a, b = l.split(' = ', 1) + for l in _as_list(c["ic"]): + a, b = l.split(" = ", 1) icd[local.get(a.strip(), spy.Symbol(a.strip()))] = spy.sympify(parse(b)) - gs = [spy.sympify(parse(str(x))) for x in _as_list(c['g'])] + gs = [spy.sympify(parse(str(x))) for x in _as_list(c["g"])] parsed.append((states, rhs, icd, gs)) rows, numrows = [], [] rank = 0 @@ -71,7 +70,7 @@ def num(e): for ci, (_states, _rhs, icd, _gs) in enumerate(parsed): for h in jets[ci]: if work[0] > work[1]: - return {'ok': False, 'reason': 'work limit'} + return {"ok": False, "reason": "work limit"} he = h.xreplace(icd) if icd else h row = [spy.diff(he, z) for z in zs] if all(r == 0 for r in row): @@ -97,25 +96,24 @@ def num(e): for ci, (states, rhs, _icd, _gs) in enumerate(parsed): new = [] for h in jets[ci]: - d = sum((spy.diff(h, states[i]) * rhs[i] for i in range(len(states))), - spy.Integer(0)) + d = sum((spy.diff(h, states[i]) * rhs[i] for i in range(len(states))), spy.Integer(0)) size = _chars(d, max_chars) work[0] += size if size > max_chars: - return {'ok': False, 'reason': 'jet too large'} + return {"ok": False, "reason": "jet too large"} new.append(d) jets[ci] = new if rank < m - 1: - return {'ok': False, 'reason': 'rank %d of %d within order %d' % (rank, m - 1, max_order)} + return {"ok": False, "reason": "rank %d of %d within order %d" % (rank, m - 1, max_order)} M = spy.Matrix(rows) comps = [] for i in range(m): sub = M[:, [j for j in range(m) if j != i]] # the minor by cofactor expansion, kept as a product/sum tree (no expansion) - comps.append((-1) ** i * (sub.det(method='berkowitz') if m > 2 else sub[0, 0])) + comps.append((-1) ** i * (sub.det(method="berkowitz") if m > 2 else sub[0, 0])) ia = support.index(anchor) if comps[ia] == 0: - return {'ok': False, 'reason': 'anchor component vanishes'} + return {"ok": False, "reason": "anchor component vanishes"} vec = {} for i in range(m): e = spy.together(comps[i] / comps[ia]) @@ -124,10 +122,10 @@ def num(e): if len(str(e)) <= max_chars // 40: e = spy.factor(spy.cancel(e)) if len(str(e)) > max_chars: - return {'ok': False, 'reason': 'closed form too large'} + return {"ok": False, "reason": "closed form too large"} if e != 0: vec[support[i]] = str(e) - return {'ok': True, 'vector': vec, 'order': int(order)} + return {"ok": True, "vector": vec, "order": int(order)} def _jet_expand_chains(conds): @@ -135,28 +133,32 @@ def _jet_expand_chains(conds): out, extra = [], [] for c in _as_list(conds): c = dict(c) - if 'segments' not in c: + if "segments" not in c: out.append(c) continue - segs = [dict(sg) for sg in _as_list(c['segments'])] + segs = [dict(sg) for sg in _as_list(c["segments"])] if not segs: continue - ic = [str(l) for l in _as_list(segs[0]['ic'])] - out.append({'f': segs[0]['f'], 'g': segs[0]['g'], 'ic': ic}) + ic = [str(l) for l in _as_list(segs[0]["ic"])] + out.append({"f": segs[0]["f"], "g": segs[0]["g"], "ic": ic}) for sg in segs[1:]: - if not sg.get('time_fixed', True): + if not sg.get("time_fixed", True): break - icd = dict(l.split(' = ', 1) for l in ic) + icd = dict(l.split(" = ", 1) for l in ic) pre = dict(icd) - for ev in _as_list(sg.get('ev', [])): + for ev in _as_list(sg.get("ev", [])): ev = dict(ev) - X, v, how = str(ev['var']), str(ev['value']), str(ev['method']) + X, v, how = str(ev["var"]), str(ev["value"]), str(ev["method"]) # at gap order 0 a state in the value stands for the start value before the events - v = replace_symbols(list(pre), ['(%s)' % e for e in pre.values()], v) + v = replace_symbols(list(pre), ["(%s)" % e for e in pre.values()], v) old = icd.get(X, X) - icd[X] = ('(%s)' % v if how == 'replace' else - '(%s) + (%s)' % (old, v) if how == 'add' else - '(%s)*(%s)' % (old, v)) - ic = ['%s = %s' % (X, e) for X, e in icd.items()] - extra.append({'f': sg['f'], 'g': sg['g'], 'ic': ic}) + icd[X] = ( + "(%s)" % v + if how == "replace" + else "(%s) + (%s)" % (old, v) + if how == "add" + else "(%s)*(%s)" % (old, v) + ) + ic = ["%s = %s" % (X, e) for X, e in icd.items()] + extra.append({"f": sg["f"], "g": sg["g"], "ic": ic}) return out, extra diff --git a/src/symident/sym/liecert.py b/src/symident/sym/liecert.py index bb33148..586c04a 100644 --- a/src/symident/sym/liecert.py +++ b/src/symident/sym/liecert.py @@ -104,9 +104,10 @@ def rows(self, k): if any(spy.count_ops(h) > _OPS for h in self.jets): raise OverflowError("a Lie derivative grows past the size cap") self.orders.append([[spy.diff(h, w) for w in self.W] for h in self.jets]) - self.jets = [spy.expand(sum((spy.diff(h, x) * self.f[x] for x in self.S), spy.Integer(0))) - for h in self.jets] - return [r for o in self.orders[:k + 1] for r in o] + self.jets = [ + spy.expand(sum((spy.diff(h, x) * self.f[x] for x in self.S), spy.Integer(0))) for h in self.jets + ] + return [r for o in self.orders[: k + 1] for r in o] def _certify(cond, cap, p, seed): diff --git a/src/symident/sym/linalg.py b/src/symident/sym/linalg.py index 5f987ef..5387435 100644 --- a/src/symident/sym/linalg.py +++ b/src/symident/sym/linalg.py @@ -11,7 +11,7 @@ def _rref_mod_p(A, p): """Vectorized int64 Gauss-Jordan over GF(p): (R, pivots); products < p^2 < 2^62 fit int64.""" - A = (np.asarray(A, dtype=np.int64) % p) + A = np.asarray(A, dtype=np.int64) % p nrows, ncols = A.shape pivots = [] r = 0 @@ -57,6 +57,7 @@ def _rational_reconstruct(a, m): def sym_rat_recon_big(residues, primes): """Per-row CRT and rational reconstruction in arbitrary precision: {'num', 'den'}, den '0' where no lift.""" from sympy.ntheory.modular import crt + mods = [int(p) for p in primes] M = 1 for m in mods: @@ -74,7 +75,7 @@ def sym_rat_recon_big(residues, primes): val = spy.Rational(val) num.append(str(int(val.p))) den.append(str(int(val.q))) - return {'num': num, 'den': den} + return {"num": num, "den": den} def _crt_nullspace(reduce_mod_p, ncols): @@ -88,6 +89,7 @@ def _crt_nullspace(reduce_mod_p, ncols): first = list(_PRIMES[:4]) try: from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(max_workers=len(first)) as ex: pre = dict(zip(first, ex.map(lambda q: _rref_mod_p(reduce_mod_p(q), q), first))) except Exception as exc: @@ -111,6 +113,7 @@ def _crt_nullspace(reduce_mod_p, ncols): return None from sympy.ntheory.modular import crt + exact = {} for key, res in residues.items(): x, Mmod = crt(mods, res) @@ -133,8 +136,7 @@ def _modular_nullspace(M): """Exact nullspace of a sympy Matrix via _crt_nullspace, validated symbolically; None if that fails.""" nrows, ncols = M.shape if nrows == 0: - return [spy.Matrix([1 if j == c else 0 for j in range(ncols)]) - for c in range(ncols)] + return [spy.Matrix([1 if j == c else 0 for j in range(ncols)]) for c in range(ncols)] Aint = [] for i in range(nrows): row = [spy.Rational(M[i, j]) for j in range(ncols)] @@ -195,8 +197,7 @@ def exact_int_kernel(rows, ncols): def exact_nullspace(rows, ncols): """Nullspace basis of an integer matrix as sympy column vectors, by the modular path first.""" if not rows: - return [spy.Matrix([1 if j == c else 0 for j in range(ncols)]) - for c in range(ncols)] + return [spy.Matrix([1 if j == c else 0 for j in range(ncols)]) for c in range(ncols)] basis = _modular_nullspace_int(rows, ncols) if basis is not None: return basis diff --git a/src/symident/sym/modp.py b/src/symident/sym/modp.py index 48c1ec6..1547b7f 100644 --- a/src/symident/sym/modp.py +++ b/src/symident/sym/modp.py @@ -24,7 +24,7 @@ def __new__(cls, expo): def _mono_nz(expo): - nz = getattr(expo, 'nz', None) + nz = getattr(expo, "nz", None) return nz if nz is not None else tuple((k, e) for k, e in enumerate(expo) if e) @@ -35,6 +35,7 @@ def _poly_terms(expr, gens): return [(zero, (0, 1))], [(zero, (1, 1))] num, den = spy.fraction(spy.together(expr)) pos = {g: k for k, g in enumerate(gens)} + def terms(e): # the Poly over the generators present only; a dense one over all of them # recurses through every level @@ -52,6 +53,7 @@ def terms(e): full[pos[g]] = int(m) out.append((_Mono(full), (int(r.p), int(r.q)))) return out + return terms(num), terms(den) @@ -86,7 +88,7 @@ def _solve_mod(A, B, p): return [M[i][n:] for i in range(n)] -_inv_mod_cache = {} +_inv_mod_cache: dict = {} def _inv_mod(a, p): @@ -108,7 +110,7 @@ def _eval_poly_terms(terms, ptvals, p): for monom, (cn, cd) in terms: if not cn: continue - c = (cn % p) * _inv_mod(cd, p) % p # cd is a compile-time constant + c = (cn % p) * _inv_mod(cd, p) % p # cd is a compile-time constant for k, e in _mono_nz(monom): c = c * pow(ptvals[k], e, p) % p acc = (acc + c) % p @@ -119,7 +121,7 @@ def _eval_terms(numden, ptvals, p): """Residue num/den mod p of a (num, den) term list at the point `ptvals`.""" nv = _eval_poly_terms(numden[0], ptvals, p) dv = _eval_poly_terms(numden[1], ptvals, p) - if dv == 1: # polynomial entry: no inverse + if dv == 1: # polynomial entry: no inverse return nv return nv * pow(dv % p, p - 2, p) % p @@ -156,7 +158,7 @@ def eval_rational_mod(expr, names, vals, q): return int((num % q) * pow(den, q - 2, q) % q) -_eval_batch_cache = {} +_eval_batch_cache: dict = {} def eval_rational_mod_batch(exprs, names, points, q): @@ -197,8 +199,7 @@ def eval_rational_mod_batch(exprs, names, points, q): if v is None or v.denominator % q == 0: row.append(-1) else: - row.append(int(v.numerator % q) * - pow(v.denominator % q, q - 2, q) % q) + row.append(int(v.numerator % q) * pow(v.denominator % q, q - 2, q) % q) out.append(row) return out @@ -245,4 +246,4 @@ def eval_rational_batch(exprs, names, points): drow.append(str(v.denominator)) nums.append(nrow) dens.append(drow) - return {'num': nums, 'den': dens} + return {"num": nums, "den": dens} diff --git a/src/symident/sym/msolve.py b/src/symident/sym/msolve.py index fccc269..1c9eab9 100644 --- a/src/symident/sym/msolve.py +++ b/src/symident/sym/msolve.py @@ -34,7 +34,8 @@ def _msolve_binary(): if path is None: raise MsolveMissingError( "this analysis needs msolve, which was not found; run symident.install_msolve(), or " - "set SYMIDENT_MSOLVE to an msolve executable.") + "set SYMIDENT_MSOLVE to an msolve executable." + ) return path @@ -61,7 +62,7 @@ def _const_reduce(dps, nv, p): dps.pop(j) plan.append((i, b, inv)) a1 = {tuple([0] * nv): 1} - b1 = {m: c * inv % p for m, c in b.items()} # x_i = -(b * inv) + b1 = {m: c * inv % p for m, c in b.items()} # x_i = -(b * inv) dps = [(_dp_subst_rat(d, i, a1, b1, nv, p) if any(m[i] for m in d) else d) for d in dps] dps = [d for d in dps if d] @@ -73,6 +74,7 @@ def _msolve_points(polys, vars_idx, p): import tempfile from ..detection import work + names = {i: "x%d" % i for i in vars_idx} def pstr(d): @@ -87,7 +89,7 @@ def pstr(d): why = work.msolve_too_large(vs, eqs) if why: session.note("limits", f"msolve: a resting state was not solved: {why}") - return {'ok': False, 'why': why} + return {"ok": False, "why": why} with tempfile.TemporaryDirectory() as td: fi, fo = os.path.join(td, "in.ms"), os.path.join(td, "out.ms") with open(fi, "w") as fh: @@ -95,27 +97,27 @@ def pstr(d): r = work.run_msolve([_msolve_binary(), "-f", fi, "-o", fo, "-P", "1", "-t", str(_MSOLVE_THREADS)]) if r.capped: session.note("limits", f"msolve: a resting state was not solved: {r.capped}") - return {'ok': False, 'why': r.capped} + return {"ok": False, "why": r.capped} txt = "" if os.path.exists(fo): with open(fo) as fh: txt = fh.read() if r.returncode != 0 or "too large" in (r.stdout + r.stderr) or not txt.strip(): - return {'ok': False, 'why': 'msolve failed: %s' % (r.stdout + r.stderr).strip()[-200:]} + return {"ok": False, "why": "msolve failed: %s" % (r.stdout + r.stderr).strip()[-200:]} data = ast.literal_eval(txt.strip().rstrip(":")) if data[0] != 0: - return {'ok': False, 'why': 'positive-dimensional steady state'} + return {"ok": False, "why": "positive-dimensional steady state"} _, _, deg, vnames, lin, par = data[1] if deg <= 0 or par[0] != 1: - return {'ok': False, 'why': 'no consistent interior point'} + return {"ok": False, "why": "no consistent interior point"} elim, den, params = par[1][0][1], par[1][1][1], par[1][2] lin = [int(c) % p for c in lin] last = len(vnames) - 1 if lin[last] == 0: - return {'ok': False, 'why': 'msolve: unexpected linear form'} + return {"ok": False, "why": "msolve: unexpected linear form"} idx_of = {names[i]: i for i in vars_idx} - def ev(coeffs, x): # coefficients lowest degree first + def ev(coeffs, x): # coefficients lowest degree first acc = 0 for c in reversed(coeffs): acc = (acc * x + c) % p @@ -147,6 +149,7 @@ def find(a): parent[a] = parent[parent[a]] a = parent[a] return a + owner = {} for j, v in enumerate(vs): for i in v: @@ -161,7 +164,7 @@ def find(a): for js in blocks.values(): bv = sorted(set().union(*(vs[j] for j in js))) if not bv: - return {'ok': False, 'why': 'no consistent interior point'} + return {"ok": False, "why": "no consistent interior point"} if len(bv) == 1: i = bv[0] roots = None @@ -178,7 +181,7 @@ def find(a): if isinstance(pts, dict): return pts if not pts: - return {'ok': False, 'why': 'no consistent interior point'} + return {"ok": False, "why": "no consistent interior point"} lists.append(pts) def merged(): @@ -187,6 +190,7 @@ def merged(): for c in combo: out.update(c) yield out + return merged() @@ -201,17 +205,23 @@ def _solve_states_msolve(dps, solve_states, p, on_branch=None, accept=None): for j, d in enumerate(rest): for i in {i for m in d for i in range(nv) if m[i]}: occ.setdefault(i, []).append(j) - pick = next(((i, js[0]) for i, js in sorted(occ.items()) if len(js) == 1 and - max(m[i] for m in rest[js[0]]) == 1 and len(occ) > 1), None) + pick = next( + ( + (i, js[0]) + for i, js in sorted(occ.items()) + if len(js) == 1 and max(m[i] for m in rest[js[0]]) == 1 and len(occ) > 1 + ), + None, + ) if pick is None: break i, j = pick cs = _dp_coeffs(rest[j], i) sinks.append((i, cs[1], cs.get(0, {}))) - rest = rest[:j] + rest[j + 1:] + rest = rest[:j] + rest[j + 1 :] vars_left = sorted({i for d in rest for m in d for i in range(nv) if m[i]}) if rest and not vars_left: - return None, {'ok': False, 'why': 'no consistent interior point'} + return None, {"ok": False, "why": "no consistent interior point"} cands = _component_points(rest, nv, p) if rest else iter([{}]) if isinstance(cands, dict): return None, cands @@ -239,7 +249,7 @@ def _solve_states_msolve(dps, solve_states, p, on_branch=None, accept=None): break # a pinned branch without a root here leaves the point out, as a point without any root if first is None or (accept is not None and taken is None): - return None, {'ok': False, 'why': 'no consistent interior point'} + return None, {"ok": False, "why": "no consistent interior point"} if several: (on_branch or note_branch)(solve_states) taken = first if taken is None else taken diff --git a/src/symident/sym/numfield.py b/src/symident/sym/numfield.py index c5c40ad..5be8cc9 100644 --- a/src/symident/sym/numfield.py +++ b/src/symident/sym/numfield.py @@ -49,7 +49,7 @@ def _reduce(self, a): if d == 1: # the field is Q, with s the rational root of W r = -Fraction(self.W[0]) - return (sum((c * r ** k for k, c in enumerate(a)), Fraction(0)),) + return (sum((c * r**k for k, c in enumerate(a)), Fraction(0)),) a = list(a) + [Fraction(0)] * max(0, d - len(a)) for k in range(len(a) - 1, d - 1, -1): c = a[k] @@ -119,6 +119,7 @@ def primes_of_degree_one(self, p): def _roots_mod(W, p): """The roots in GF(p) of the integer polynomial W, lowest degree first, zero included.""" from .gfpoly import _gf_roots + out = sorted(int(r) for r in _gf_roots([c % p for c in reversed(W)], p)) return [0] + out if W[0] % p == 0 else out diff --git a/src/symident/sym/parse.py b/src/symident/sym/parse.py index 2c57dcf..49c95a2 100644 --- a/src/symident/sym/parse.py +++ b/src/symident/sym/parse.py @@ -9,8 +9,7 @@ from sympy.printing.str import StrPrinter # primes below 1518500213, msolve's bound for FGLM -_PRIMES = [1518500183, 1518500173, 1518500171, 1518500143, - 1518500141, 1518500131, 1518500101, 1518500077] +_PRIMES = [1518500183, 1518500173, 1518500171, 1518500143, 1518500141, 1518500131, 1518500101, 1518500077] def _as_list(x): @@ -22,7 +21,7 @@ def _as_list(x): def _clean(line): - return line.replace('"', '').replace('^', '**').strip() + return line.replace('"', "").replace("^", "**").strip() def _build_symbol_table(all_lines): @@ -39,11 +38,11 @@ def _build_symbol_table(all_lines): for i, t in enumerate(toks): if t.type == tokenize.NAME: nxt = toks[i + 1] if i + 1 < len(toks) else None - if nxt is not None and nxt.type == tokenize.OP and nxt.string == '(': + if nxt is not None and nxt.type == tokenize.OP and nxt.string == "(": funcs.add(t.string) else: syms.add(t.string) - syms -= funcs | {'pi'} + syms -= funcs | {"pi"} return {s: spy.Symbol(s) for s in syms} @@ -55,35 +54,58 @@ def _function_aliases(): return dict(_ALIASES) -_ALIASES = {} +_ALIASES: dict = {} def _build_function_aliases(): - x = spy.Symbol('_x_') + x = spy.Symbol("_x_") return { - 'log10': spy.Lambda(x, spy.log(x) / spy.log(10)), - 'log2': spy.Lambda(x, spy.log(x) / spy.log(2)), - 'exp10': spy.Lambda(x, spy.Integer(10) ** x), - 'exp2': spy.Lambda(x, spy.Integer(2) ** x), - 'ln': spy.log, - 'acot': spy.Lambda(x, spy.atan(1 / x)), - 'asec': spy.Lambda(x, spy.acos(1 / x)), - 'acsc': spy.Lambda(x, spy.asin(1 / x)), - 'acoth': spy.Lambda(x, spy.atanh(1 / x)), - 'asech': spy.Lambda(x, spy.acosh(1 / x)), - 'acsch': spy.Lambda(x, spy.asinh(1 / x)), - 'round': spy.Lambda(x, spy.floor(x + spy.Rational(1, 2))), + "log10": spy.Lambda(x, spy.log(x) / spy.log(10)), + "log2": spy.Lambda(x, spy.log(x) / spy.log(2)), + "exp10": spy.Lambda(x, spy.Integer(10) ** x), + "exp2": spy.Lambda(x, spy.Integer(2) ** x), + "ln": spy.log, + "acot": spy.Lambda(x, spy.atan(1 / x)), + "asec": spy.Lambda(x, spy.acos(1 / x)), + "acsc": spy.Lambda(x, spy.asin(1 / x)), + "acoth": spy.Lambda(x, spy.atanh(1 / x)), + "asech": spy.Lambda(x, spy.acosh(1 / x)), + "acsch": spy.Lambda(x, spy.asinh(1 / x)), + "round": spy.Lambda(x, spy.floor(x + spy.Rational(1, 2))), } # the functions of the model language that are not switches, by name _MODEL_FUNCTIONS = { - 'exp': spy.exp, 'log': spy.log, 'sqrt': spy.sqrt, 'cbrt': spy.cbrt, 'root': spy.root, 'pow': spy.Pow, - 'sin': spy.sin, 'cos': spy.cos, 'tan': spy.tan, 'cot': spy.cot, 'sec': spy.sec, 'csc': spy.csc, - 'asin': spy.asin, 'acos': spy.acos, 'atan': spy.atan, 'atan2': spy.atan2, - 'sinh': spy.sinh, 'cosh': spy.cosh, 'tanh': spy.tanh, 'coth': spy.coth, 'sech': spy.sech, - 'csch': spy.csch, 'asinh': spy.asinh, 'acosh': spy.acosh, 'atanh': spy.atanh, - 'erf': spy.erf, 'erfc': spy.erfc, 'floor': spy.floor, 'ceiling': spy.ceiling, + "exp": spy.exp, + "log": spy.log, + "sqrt": spy.sqrt, + "cbrt": spy.cbrt, + "root": spy.root, + "pow": spy.Pow, + "sin": spy.sin, + "cos": spy.cos, + "tan": spy.tan, + "cot": spy.cot, + "sec": spy.sec, + "csc": spy.csc, + "asin": spy.asin, + "acos": spy.acos, + "atan": spy.atan, + "atan2": spy.atan2, + "sinh": spy.sinh, + "cosh": spy.cosh, + "tanh": spy.tanh, + "coth": spy.coth, + "sech": spy.sech, + "csch": spy.csch, + "asinh": spy.asinh, + "acosh": spy.acosh, + "atanh": spy.atanh, + "erf": spy.erf, + "erfc": spy.erfc, + "floor": spy.floor, + "ceiling": spy.ceiling, } @@ -117,6 +139,7 @@ def parse(rhs): e = parse_expr(_clean(rhs), local_dict=local_dict, evaluate=True) memo[key] = e return e + return parse @@ -143,9 +166,9 @@ def _read_equations(lines, parse): variables, functions = [], [] for raw in lines: line = _clean(raw) - if '=' not in line: + if "=" not in line: continue - lhs, rhs = line.split('=', 1) + lhs, rhs = line.split("=", 1) variables.append(spy.Symbol(lhs.strip())) functions.append(parse(rhs)) allsyms = set() diff --git a/src/symident/sym/recast.py b/src/symident/sym/recast.py index 14a0b6d..a9f8d29 100644 --- a/src/symident/sym/recast.py +++ b/src/symident/sym/recast.py @@ -13,6 +13,7 @@ class SeriesExp(spy.Function): """exp(w) of a w that vanishes at the state of zero gaps, a series the kernel sums.""" + nargs = 1 @classmethod @@ -26,6 +27,7 @@ def fdiff(self, argindex=1): class SeriesLog1p(spy.Function): """log(1 + w) of a w that vanishes at the state of zero gaps, a series the kernel sums.""" + nargs = 1 @classmethod @@ -39,6 +41,7 @@ def fdiff(self, argindex=1): class SeriesSin(spy.Function): """sin(w) of a w that vanishes at the state of zero gaps, a series the kernel sums.""" + nargs = 1 @classmethod @@ -52,6 +55,7 @@ def fdiff(self, argindex=1): class SeriesCos(spy.Function): """cos(w) of a w that vanishes at the state of zero gaps, a series the kernel sums.""" + nargs = 1 @classmethod @@ -79,7 +83,7 @@ def _chains(K, chain_of): return out -_PRE = '_sx_' +_PRE = "_sx_" def pre_state(name): @@ -90,7 +94,7 @@ def pre_state(name): def pre_state_name(sym): """The state a pre_state() symbol stands for, else None.""" nm = str(sym) - return nm[len(_PRE):] if nm.startswith(_PRE) else None + return nm[len(_PRE) :] if nm.startswith(_PRE) else None def _series_events(S, ic, ev, chain_of, ln): @@ -104,13 +108,13 @@ def _series_events(S, ic, ev, chain_of, ln): out = [list(evs) for evs in ev] def compose(cur, method, v): - return {'replace': v, 'add': cur + v, 'multiply': cur * v}[method] + return {"replace": v, "add": cur + v, "multiply": cur * v}[method] def series_exp(psi, psi0, r): # r^psi = r^psi0 * exp(log(r)*(psi - psi0)), psi0 the value at zero gaps if r == spy.E: return spy.exp(psi0) * SeriesExp(psi - psi0) - return r ** psi0 * SeriesExp(ln(r) * (psi - psi0)) + return r**psi0 * SeriesExp(ln(r) * (psi - psi0)) def series_log(u, u0): if u0 == 0: @@ -151,12 +155,12 @@ def rewrite(e, x0): pre = dict(x0) new = [] for e in ev[c]: - v = spy.sympify(e['value']) - if e.get('t0'): + v = spy.sympify(e["value"]) + if e.get("t0"): # an event at a start at rest reads the resting coordinates themselves at_pre = v.xreplace(pre) new.append(dict(e, value=at_pre)) - elif e.get('marked'): + elif e.get("marked"): at_pre = v.xreplace({pre_state(s): pre[s] for s in S}) new.append(e) else: @@ -164,11 +168,13 @@ def rewrite(e, x0): try: new.append(dict(e, value=rewrite(v, pre), marked=True, plain=v)) except _NotExpandableError: - return {'why': 'the event value %s for %s is a function of the states that the ' - 'finite-field engine does not expand' % (v, e['var'])} - var = sym_of.get(str(e['var'])) + return { + "why": "the event value %s for %s is a function of the states that the " + "finite-field engine does not expand" % (v, e["var"]) + } + var = sym_of.get(str(e["var"])) if var is not None: - x0[var] = compose(x0[var], str(e['method']), at_pre) + x0[var] = compose(x0[var], str(e["method"]), at_pre) out[c] = new return out @@ -181,7 +187,7 @@ def _state_events(ev, states, atoms): """The first event value with an atom of `atoms(value)` that reads `states`, else None.""" for evs in ev: for e in evs: - for a in atoms(spy.sympify(e['value'])): + for a in atoms(spy.sympify(e["value"])): if a.free_symbols & states: return e, a return None @@ -251,8 +257,7 @@ def _terms_independent(atoms): if not all(v.is_Rational for v in vals): continue for bi, b in enumerate(basis): - rows.append([comps[k].get(b, 0) * vals[k] for k in range(m)] + - [1 if j == bi else 0 for j in range(nb)]) + rows.append([comps[k].get(b, 0) * vals[k] for k in range(m)] + [1 if j == bi else 0 for j in range(nb)]) npts += 1 if npts >= m + 3: break @@ -270,16 +275,17 @@ def _terms_independent(atoms): class _ExpCtx: """Fresh symbols and constant leaves of one rewrite: e^(1/L0) as `ec`, log(p) as one leaf per prime.""" + def __init__(self, taken): self.taken = set(taken) - self.ec = self.fresh('_e_', positive=True) + self.ec = self.fresh("_e_", positive=True) self.ln_sym = {} def fresh(self, stem, **kw): """A new symbol from `stem`, with underscores appended until unused, marked as taken.""" nm = stem while nm in self.taken: - nm += '_' + nm += "_" self.taken.add(nm) return spy.Symbol(nm, **kw) @@ -291,22 +297,22 @@ def ln_of(self, r): out += e continue if pr not in self.ln_sym: - self.ln_sym[pr] = self.fresh('_ln%d_' % pr, positive=True) + self.ln_sym[pr] = self.fresh("_ln%d_" % pr, positive=True) out += e * self.ln_sym[pr] return out @staticmethod def rpow(r, e): """`r` to the power `e`, as exp(e) for the base E.""" - return spy.exp(e) if r == spy.E else r ** e + return spy.exp(e) if r == spy.E else r**e def const(self, r, c0): """r^c0, None when it is irrational and not a power of e.""" if c0 == 0: return spy.Integer(1) if r == spy.E: - return self.ec ** c0 - return r ** c0 if c0.is_Integer else None + return self.ec**c0 + return r**c0 if c0.is_Integer else None def numbers(self, e): """E as the leaf ec, log(b) of a number as a multiple of a log leaf.""" @@ -368,9 +374,8 @@ def _exp_leaf_canon(exprs, ctx, held=None): held = held if held is not None else [set()] * len(exprs) atoms, logs, log_of = [], [], {} for e, hs in zip(exprs, held): - if any((be := _exp_atom(a)) is not None and be[1].free_symbols & hs - for a in e.atoms(spy.exp, spy.Pow)): - return {'why': 'an event value with the exponential of a state is not supported'} + if any((be := _exp_atom(a)) is not None and be[1].free_symbols & hs for a in e.atoms(spy.exp, spy.Pow)): + return {"why": "an event value with the exponential of a state is not supported"} while True: exprs = _exponent_logs(exprs, ctx, held, logs, log_of) found = {} @@ -378,13 +383,13 @@ def _exp_leaf_canon(exprs, ctx, held=None): for at in e.atoms(spy.exp, spy.Pow): if at in found or _exp_atom(at) is None: continue - if any(_exp_atom(a) is not None - for a in _exp_atom(at)[1].atoms(spy.exp, spy.Pow)): + if any(_exp_atom(a) is not None for a in _exp_atom(at)[1].atoms(spy.exp, spy.Pow)): continue dec = _exp_terms(*_exp_atom(at)) if dec is None or ctx.const(dec[0], dec[1]) is None: - return {'why': 'the exponential %s is not supported by ' - 'engine="modular"; try engine="symbolic"' % at} + return { + "why": 'the exponential %s is not supported by engine="modular"; try engine="symbolic"' % at + } found[at] = dec if not found: break @@ -402,8 +407,10 @@ def _exp_leaf_canon(exprs, ctx, held=None): for tb, qb in comb.items(): pc[(B, tb)] = pc.get((B, tb), 0) + q * qb if any(ctx.const(B, c) is None for B, c in cst.items()): - return {'why': 'exponents that are linearly dependent over the rationals ' - 'up to a constant that is not an integer power are not supported'} + return { + "why": "exponents that are linearly dependent over the rationals " + "up to a constant that is not an integer power are not supported" + } pieces[at] = ({k: v for k, v in pc.items() if v != 0}, cst) den = {} for pc, _ in pieces.values(): @@ -411,9 +418,9 @@ def _exp_leaf_canon(exprs, ctx, held=None): den[key] = spy.ilcm(den.get(key, 1), spy.Rational(q).q) key_w = {} for (r, t), L in sorted(den.items(), key=lambda kv: (str(kv[0][0]), str(kv[0][1]))): - W = ctx.fresh('_ew%d_' % (len(atoms) + 1), positive=True) + W = ctx.fresh("_ew%d_" % (len(atoms) + 1), positive=True) key_w[(r, t)] = W - atoms.append({'W': W, 'r': r, 'tau': t, 'L': L}) + atoms.append({"W": W, "r": r, "tau": t, "L": L}) repl = {} for at, (r, c0, _terms) in found.items(): v = ctx.const(r, c0) @@ -426,23 +433,24 @@ def _exp_leaf_canon(exprs, ctx, held=None): exprs = [e.xreplace(repl) for e in exprs] # e^c as integer powers of the leaf e^(1/L0) L0 = 1 - for e in exprs + [w['tau'] for w in atoms]: + for e in exprs + [w["tau"] for w in atoms]: for pw in e.atoms(spy.Pow): if pw.base == ctx.ec: L0 = spy.ilcm(L0, spy.Rational(pw.exp).q) - ec_sub = {ctx.ec: ctx.ec ** L0} + ec_sub = {ctx.ec: ctx.ec**L0} exprs = [e.xreplace(ec_sub) for e in exprs] for w in atoms: - w['tau'] = w['tau'].xreplace(ec_sub) + w["tau"] = w["tau"].xreplace(ec_sub) ctx.L0 = L0 - ind = _terms_independent([(w['r'], w['tau']) for w in atoms]) + ind = _terms_independent([(w["r"], w["tau"]) for w in atoms]) if ind is None: - return {'why': 'an exponent is not a rational function of the coordinates (a logarithm of an initial ' - 'value in an exponent); give that initial value as a parameter'} + return { + "why": "an exponent is not a rational function of the coordinates (a logarithm of an initial " + "value in an exponent); give that initial value as a parameter" + } if not ind: - return {'why': 'exponents that are linearly dependent over the rationals ' - 'are not supported'} - return {'exprs': exprs, 'atoms': atoms, 'logs': logs} + return {"why": "exponents that are linearly dependent over the rationals are not supported"} + return {"exprs": exprs, "atoms": atoms, "logs": logs} def _exponent_logs(vals, ctx, held, leaves, leaf_of): @@ -462,10 +470,11 @@ def as_logs(u): out += sgn * ctx.numbers(spy.log(c)) for p, m in facs: if p not in leaf_of: - leaf_of[p] = ctx.fresh('_el%d_' % (len(leaves) + 1), real=True) - leaves.append({'V': leaf_of[p], 'p': p}) + leaf_of[p] = ctx.fresh("_el%d_" % (len(leaves) + 1), real=True) + leaves.append({"V": leaf_of[p], "p": p}) out += sgn * m * leaf_of[p] return out + out = [] for e, states in zip(vals, held): rep = {} @@ -475,8 +484,12 @@ def as_logs(u): continue for L in be[1].atoms(spy.log): u = L.args[0] - if u.is_number or u.free_symbols & states or L in rep or \ - any(_exp_atom(a) is not None for a in u.atoms(spy.exp, spy.Pow)): + if ( + u.is_number + or u.free_symbols & states + or L in rep + or any(_exp_atom(a) is not None for a in u.atoms(spy.exp, spy.Pow)) + ): continue v = as_logs(u) if v is not None: @@ -487,11 +500,11 @@ def as_logs(u): def _exp_back(atoms, ctx, used): """Back-substitution map {name: value string} for the leaves and constants.""" - back = {str(w['W']): str(ctx.rpow(w['r'], w['tau'] / w['L'])) for w in atoms} + back = {str(w["W"]): str(ctx.rpow(w["r"], w["tau"] / w["L"])) for w in atoms} if ctx.ec in used: back[str(ctx.ec)] = str(spy.exp(spy.Rational(1, ctx.L0))) for r, s in ctx.ln_sym.items(): - back[str(s)] = 'log(%s)' % r + back[str(s)] = "log(%s)" % r return back @@ -505,11 +518,11 @@ def _apply_exp_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_rest g = [[ctx.numbers(e) for e in p[1]] for p in per_cond] ic = [{k: ctx.numbers(v) for k, v in p[2].items()} for p in per_cond] fss = [list(p[3]) for p in per_cond] - ev = [[dict(e, value=ctx.numbers(e['value'])) for e in evs] for evs in ev_per] + ev = [[dict(e, value=ctx.numbers(e["value"])) for e in evs] for evs in ev_per] tm = [None if t is None else ctx.numbers(t) for t in tm_per] # ---- dynamics: auxiliary states, innermost exponential first - aux = [] # {'X', 'r', 'phi'} + aux = [] # {'X', 'r', 'phi'} n_real = len(S) while True: states = set(S) @@ -517,6 +530,7 @@ def _apply_exp_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_rest def state_atom(a): be = _exp_atom(a) return be is not None and bool(be[1].free_symbols & states) + found = {} for c in range(K): for e in f[c] + g[c]: @@ -527,8 +541,9 @@ def state_atom(a): continue dec = _exp_terms(*_exp_atom(at)) if dec is None or const(dec[0], dec[1]) is None: - return {'why': 'the exponential %s is not supported by ' - 'engine="modular"; try engine="symbolic"' % at} + return { + "why": 'the exponential %s is not supported by engine="modular"; try engine="symbolic"' % at + } found[at] = dec if not found: break @@ -539,9 +554,9 @@ def state_atom(a): den[(r, t)] = spy.ilcm(den.get((r, t), 1), q.q) key_x = {} for (r, t), D in sorted(den.items(), key=lambda kv: (str(kv[0][0]), str(kv[0][1]))): - X = ctx.fresh('_ex%d_' % (len(aux) + 1)) + X = ctx.fresh("_ex%d_" % (len(aux) + 1)) key_x[(r, t)] = X - aux.append({'X': X, 'r': r, 'phi': t / D}) + aux.append({"X": X, "r": r, "phi": t / D}) repl = {} for at, (r, c0, terms) in found.items(): v = const(r, c0) @@ -553,17 +568,17 @@ def state_atom(a): repl[at] = v f = [[e.xreplace(repl) for e in fc] for fc in f] g = [[e.xreplace(repl) for e in gc] for gc in g] - new_aux = aux[len(aux) - len(key_x):] + new_aux = aux[len(aux) - len(key_x) :] for c in range(K): rhs_of = dict(zip(S, f[c])) for a in new_aux: - phi = a['phi'] + phi = a["phi"] dphi = sum(spy.diff(phi, s) * rhs_of[s] for s in phi.free_symbols & states) - f[c].append(spy.expand(a['X'] * ctx.ln_of(a['r']) * dphi)) + f[c].append(spy.expand(a["X"] * ctx.ln_of(a["r"]) * dphi)) ic_sub = {s: ic[c][str(s)] for s in phi.free_symbols & states} - ic[c][str(a['X'])] = rpow(a['r'], phi.xreplace(ic_sub)) + ic[c][str(a["X"])] = rpow(a["r"], phi.xreplace(ic_sub)) fss[c].append(spy.Integer(0)) - S += [a['X'] for a in new_aux] + S += [a["X"] for a in new_aux] # an auxiliary state no observable depends on stays at 1 in that condition idx = {X: i for i, X in enumerate(S)} @@ -575,14 +590,14 @@ def state_atom(a): while front: nxt = set() for a in aux: - if a['X'] in front and a['X'] not in used: - used.add(a['X']) - nxt |= f[c][idx[a['X']]].free_symbols + if a["X"] in front and a["X"] not in used: + used.add(a["X"]) + nxt |= f[c][idx[a["X"]]].free_symbols front = nxt - used for a in aux: - if a['X'] not in used: - f[c][idx[a['X']]] = spy.Integer(0) - ic[c][str(a['X'])] = spy.Integer(1) + if a["X"] not in used: + f[c][idx[a["X"]]] = spy.Integer(0) + ic[c][str(a["X"])] = spy.Integer(1) # later events on a state inside an exponent move the auxiliary states with it Sset = set(S) @@ -594,89 +609,106 @@ def state_atom(a): while queue: cur = queue.pop(0) for a in aux: - phi = a['phi'] - vs = [s for s in phi.free_symbols if str(s) == str(cur['var'])] - if not vs or f[c][idx[a['X']]] == 0: + phi = a["phi"] + vs = [s for s in phi.free_symbols if str(s) == str(cur["var"])] + if not vs or f[c][idx[a["X"]]] == 0: continue vsym = vs[0] d1 = spy.diff(phi, vsym) - v = spy.sympify(cur['value']) - if (cur['method'] == 'add' and spy.diff(d1, vsym) == 0 and - not ((d1.free_symbols | v.free_symbols) & Sset)): - new = {'var': str(a['X']), 'method': 'multiply', 'value': rpow(a['r'], v * d1)} + v = spy.sympify(cur["value"]) + if ( + cur["method"] == "add" + and spy.diff(d1, vsym) == 0 + and not ((d1.free_symbols | v.free_symbols) & Sset) + ): + new = {"var": str(a["X"]), "method": "multiply", "value": rpow(a["r"], v * d1)} else: # the exponent at the state after the event; values read the states before it - after = {'replace': v, 'add': vsym + v, 'multiply': vsym * v}[cur['method']] - new = {'var': str(a['X']), 'method': 'replace', - 'value': rpow(a['r'], phi.xreplace({vsym: after}))} - if cur.get('t0'): - new['t0'] = True + after = {"replace": v, "add": vsym + v, "multiply": vsym * v}[cur["method"]] + new = { + "var": str(a["X"]), + "method": "replace", + "value": rpow(a["r"], phi.xreplace({vsym: after})), + } + if cur.get("t0"): + new["t0"] = True out.append(new) queue.append(new) ev[c] = out ev = _series_events(S, ic, ev, chain_of, lambda r: ctx.numbers(spy.log(r))) - if 'why' in ev: + if "why" in ev: return ev # ---- leaf level: generic exponential leaves W - refs = ([('f', c, i) for c in range(K) for i in range(len(f[c]))] + - [('g', c, i) for c in range(K) for i in range(len(g[c]))] + - [('ic', c, k) for c in range(K) for k in ic[c]] + - [('ev', c, i) for c in range(K) for i in range(len(ev[c]))] + - [('tm', c, None) for c in range(K) if tm[c] is not None] + - # a start at rest: the resting model in the same leaves - ([('fss', c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else [])) - store = {'f': f, 'g': g, 'ic': ic, 'fss': fss} + refs = ( + [("f", c, i) for c in range(K) for i in range(len(f[c]))] + + [("g", c, i) for c in range(K) for i in range(len(g[c]))] + + [("ic", c, k) for c in range(K) for k in ic[c]] + + [("ev", c, i) for c in range(K) for i in range(len(ev[c]))] + + [("tm", c, None) for c in range(K) if tm[c] is not None] + + + # a start at rest: the resting model in the same leaves + ([("fss", c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else []) + ) + store = {"f": f, "g": g, "ic": ic, "fss": fss} vals = [] for kind, c, i in refs: - vals.append(ev[c][i]['value'] if kind == 'ev' else tm[c] if kind == 'tm' - else store[kind][c][i]) + vals.append(ev[c][i]["value"] if kind == "ev" else tm[c] if kind == "tm" else store[kind][c][i]) # in event values the states at the event are pre_state() symbols; plain state names are initial values held = {pre_state(s) for s in S} - lc = _exp_leaf_canon(vals, ctx, [held if kind == 'ev' else set() for kind, _, _ in refs]) - if 'why' in lc: + lc = _exp_leaf_canon(vals, ctx, [held if kind == "ev" else set() for kind, _, _ in refs]) + if "why" in lc: return lc - logleaves = lc['logs'] - for (kind, c, i), v in zip(refs, lc['exprs']): - if kind == 'ev': - ev[c][i]['value'] = v - elif kind == 'tm': + logleaves = lc["logs"] + for (kind, c, i), v in zip(refs, lc["exprs"]): + if kind == "ev": + ev[c][i]["value"] = v + elif kind == "tm": tm[c] = v else: store[kind][c][i] = v - w_atoms = lc['atoms'] + w_atoms = lc["atoms"] for w in w_atoms: - ctx.ln_of(w['r']) + ctx.ln_of(w["r"]) const_syms = set(ctx.ln_sym.values()) used = set() - for v in lc['exprs'] + [w['tau'] for w in w_atoms]: + for v in lc["exprs"] + [w["tau"] for w in w_atoms]: used |= v.free_symbols if ctx.ec in used: const_syms.add(ctx.ec) rel = [] for w in w_atoms: - phi = w['tau'] / w['L'] + phi = w["tau"] / w["L"] for z in sorted(phi.free_symbols - const_syms, key=str): - rel.append((str(w['W']), str(z), - spy.together(w['W'] * ctx.ln_of(w['r']) * spy.diff(phi, z)))) + rel.append((str(w["W"]), str(z), spy.together(w["W"] * ctx.ln_of(w["r"]) * spy.diff(phi, z)))) back = _exp_back(w_atoms, ctx, used) for lf in logleaves: - for z in sorted(lf['p'].free_symbols - const_syms, key=str): - rel.append((str(lf['V']), str(z), spy.together(spy.diff(lf['p'], z) / lf['p']))) - back[str(lf['V'])] = str(spy.log(lf['p'])) + for z in sorted(lf["p"].free_symbols - const_syms, key=str): + rel.append((str(lf["V"]), str(z), spy.together(spy.diff(lf["p"], z) / lf["p"]))) + back[str(lf["V"])] = str(spy.log(lf["p"])) per_cond = [(f[c], g[c], ic[c], fss[c]) for c in range(K)] - return {'S': S, 'per_cond': per_cond, 'ev_per': ev, 'tm_per': tm, 'rel': rel, - 'consts': sorted(str(s) for s in const_syms), - 'atoms': [str(w['W']) for w in w_atoms] + [str(lf['V']) for lf in logleaves], 'back': back, - 'n_aux': len(aux), 'codim': len(aux) + len(w_atoms) + len(logleaves)} + return { + "S": S, + "per_cond": per_cond, + "ev_per": ev, + "tm_per": tm, + "rel": rel, + "consts": sorted(str(s) for s in const_syms), + "atoms": [str(w["W"]) for w in w_atoms] + [str(lf["V"]) for lf in logleaves], + "back": back, + "n_aux": len(aux), + "codim": len(aux) + len(w_atoms) + len(logleaves), + } _TRIG = (spy.sin, spy.cos, spy.tan) -_TRIG_RECIPROCAL = {spy.cot: lambda a: spy.cos(a) / spy.sin(a), - spy.sec: lambda a: 1 / spy.cos(a), - spy.csc: lambda a: 1 / spy.sin(a)} +_TRIG_RECIPROCAL = { + spy.cot: lambda a: spy.cos(a) / spy.sin(a), + spy.sec: lambda a: 1 / spy.cos(a), + spy.csc: lambda a: 1 / spy.sin(a), +} def _has_trig(e): @@ -686,8 +718,7 @@ def _has_trig(e): def _trig_basic(e): """cot, sec and csc through sin and cos.""" - return spy.sympify(e).replace(lambda x: type(x) in _TRIG_RECIPROCAL, - lambda x: _TRIG_RECIPROCAL[type(x)](x.args[0])) + return spy.sympify(e).replace(lambda x: type(x) in _TRIG_RECIPROCAL, lambda x: _TRIG_RECIPROCAL[type(x)](x.args[0])) def _trig_terms(fn, u): @@ -698,13 +729,14 @@ def _trig_terms(fn, u): terms = dict(u.as_coefficients_dict()) c0 = terms.pop(spy.Integer(1), spy.Integer(0)) cp = terms.pop(spy.pi, spy.Integer(0)) - if not (c0.is_Rational and cp.is_Rational and (2 * cp).is_Integer and - all(q.is_Rational for q in terms.values())): + if not (c0.is_Rational and cp.is_Rational and (2 * cp).is_Integer and all(q.is_Rational for q in terms.values())): return None # an inner trig atom left in a term is one the later leaf pass resolves - if any(_has_exp(t) or not _is_rational_expr( - t.replace(lambda x: isinstance(x, _TRIG), lambda x: spy.Dummy()) - .xreplace({spy.pi: 1})) for t in terms): + if any( + _has_exp(t) + or not _is_rational_expr(t.replace(lambda x: isinstance(x, _TRIG), lambda x: spy.Dummy()).xreplace({spy.pi: 1})) + for t in terms + ): return None return c0, cp, terms @@ -717,8 +749,8 @@ def _trig_value(fn, factors, k, rest): d = spy.Dummy(real=True) reps[d] = T A *= (1 + I * d) ** m if m > 0 else (1 - I * d) ** (-m) - n *= (1 + T ** 2) ** abs(m) - Z = I ** (int(k) % 4) * spy.expand(A ** 2) + n *= (1 + T**2) ** abs(m) + Z = I ** (int(k) % 4) * spy.expand(A**2) if rest != 0: C, Sn = spy.Dummy(real=True), spy.Dummy(real=True) reps[C], reps[Sn] = spy.cos(rest), spy.sin(rest) @@ -740,6 +772,7 @@ def g(e): if r is None: r = memo[e] = fn(e) return r + return g @@ -763,7 +796,7 @@ def _trig_find(exprs, in_scope, why): continue dec = _trig_terms(type(at), at.args[0]) if dec is None: - return {'why': why % at} + return {"why": why % at} found[at] = dec return found @@ -781,7 +814,7 @@ def _trig_den(found, keep): def _apply_trig_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_rest=False): """The model with trigonometric functions as half-angle states and leaves, as _apply_exp_recast.""" ctx = _ExpCtx(taken) - pis = ctx.fresh('_pi_', positive=True) + pis = ctx.fresh("_pi_", positive=True) S = list(S) K = len(per_cond) basic = _shared(_trig_basic) @@ -790,56 +823,54 @@ def _apply_trig_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_res g = [[basic(e) for e in p[1]] for p in per_cond] ic = [{k: basic(v) for k, v in p[2].items()} for p in per_cond] fss = [[basic_pi(e) for e in p[3]] for p in per_cond] - ev = [[dict(e, value=basic(e['value'])) for e in evs] for evs in ev_per] + ev = [[dict(e, value=basic(e["value"])) for e in evs] for evs in ev_per] tm = [None if t is None else basic(t) for t in tm_per] free = _shared(lambda e: e.free_symbols) - unsupported = ('the argument of %s is not supported by engine="modular"; ' - 'try engine="symbolic"') + unsupported = 'the argument of %s is not supported by engine="modular"; try engine="symbolic"' # ---- dynamics: auxiliary half-angle states, innermost first - aux = [] # {'X', 'phi'} + aux = [] # {'X', 'phi'} while True: states = set(S) + def state_atom(a): return bool(a.args[0].free_symbols & states) - found = _trig_find([e for c in range(K) for e in f[c] + g[c]], state_atom, - unsupported) - if 'why' in found: + + found = _trig_find([e for c in range(K) for e in f[c] + g[c]], state_atom, unsupported) + if "why" in found: return found if not found: break den = _trig_den(found, lambda t: bool(t.free_symbols & states)) key_x = {} for t, D in sorted(den.items(), key=lambda kv: str(kv[0])): - X = ctx.fresh('_tx%d_' % (len(aux) + 1)) + X = ctx.fresh("_tx%d_" % (len(aux) + 1)) key_x[t] = X - aux.append({'X': X, 'phi': t / D}) + aux.append({"X": X, "phi": t / D}) repl = {} for at, (c0, cp, terms) in found.items(): - factors = [(key_x[t], int(q * den[t])) - for t, q in terms.items() if t in key_x] - rest = c0 + sum((q * t for t, q in terms.items() if t not in key_x), - spy.Integer(0)) + factors = [(key_x[t], int(q * den[t])) for t, q in terms.items() if t in key_x] + rest = c0 + sum((q * t for t, q in terms.items() if t not in key_x), spy.Integer(0)) repl[at] = _trig_value(type(at), factors, 2 * cp, rest) xr = _shared(lambda e, repl=repl: e.xreplace(repl)) f = [[xr(e) for e in fc] for fc in f] g = [[xr(e) for e in gc] for gc in g] - new_aux = aux[len(aux) - len(key_x):] + new_aux = aux[len(aux) - len(key_x) :] dmemo = {} for c in range(K): rhs_of = dict(zip(S, f[c])) for a in new_aux: - phi = a['phi'] + phi = a["phi"] inside = sorted(phi.free_symbols & states, key=str) - key = (a['X'], tuple(rhs_of[s] for s in inside)) + key = (a["X"], tuple(rhs_of[s] for s in inside)) if key not in dmemo: dphi = sum(spy.diff(phi, s) * rhs_of[s] for s in inside) - dmemo[key] = spy.expand((1 + a['X'] ** 2) * dphi / 2) + dmemo[key] = spy.expand((1 + a["X"] ** 2) * dphi / 2) f[c].append(dmemo[key]) ic_sub = {s: ic[c][str(s)] for s in phi.free_symbols & states} - ic[c][str(a['X'])] = spy.tan(phi.xreplace(ic_sub) / 2) + ic[c][str(a["X"])] = spy.tan(phi.xreplace(ic_sub) / 2) fss[c].append(spy.Integer(0)) - S += [a['X'] for a in new_aux] + S += [a["X"] for a in new_aux] # an auxiliary state no observable depends on stays at 0 in that condition n_real = len(S) - len(aux) @@ -851,14 +882,14 @@ def state_atom(a): while front: nxt = set() for a in aux: - if a['X'] in front and a['X'] not in used: - used.add(a['X']) - nxt |= free(f[c][idx[a['X']]]) + if a["X"] in front and a["X"] not in used: + used.add(a["X"]) + nxt |= free(f[c][idx[a["X"]]]) front = nxt - used for a in aux: - if a['X'] not in used: - f[c][idx[a['X']]] = spy.Integer(0) - ic[c][str(a['X'])] = spy.Integer(0) + if a["X"] not in used: + f[c][idx[a["X"]]] = spy.Integer(0) + ic[c][str(a["X"])] = spy.Integer(0) # a later event on a state inside an argument resets the auxiliary state for c in range(K): @@ -866,37 +897,41 @@ def state_atom(a): for e in ev[c]: out.append(e) for a in aux: - phi = a['phi'] - vs = [s for s in phi.free_symbols if str(s) == str(e['var'])] - if not vs or f[c][idx[a['X']]] == 0: + phi = a["phi"] + vs = [s for s in phi.free_symbols if str(s) == str(e["var"])] + if not vs or f[c][idx[a["X"]]] == 0: continue # the half angle at the state after the event; values read the states before it - v = spy.sympify(e['value']) - after = {'replace': v, 'add': vs[0] + v, 'multiply': vs[0] * v}[e['method']] - new = {'var': str(a['X']), 'method': 'replace', 'value': spy.tan(phi.xreplace({vs[0]: after}) / 2)} - if e.get('t0'): - new['t0'] = True + v = spy.sympify(e["value"]) + after = {"replace": v, "add": vs[0] + v, "multiply": vs[0] * v}[e["method"]] + new = {"var": str(a["X"]), "method": "replace", "value": spy.tan(phi.xreplace({vs[0]: after}) / 2)} + if e.get("t0"): + new["t0"] = True out.append(new) ev[c] = out ev = _series_events(S, ic, ev, chain_of, spy.log) - if 'why' in ev: + if "why" in ev: return ev hit = _state_events(ev, {pre_state(s) for s in S}, lambda e: e.atoms(*_TRIG)) if hit is not None: - return {'why': 'the event value %s for %s reads the state through %s, which is not ' - 'supported' % (hit[0]['value'], hit[0]['var'], hit[1])} + return { + "why": "the event value %s for %s reads the state through %s, which is not " + "supported" % (hit[0]["value"], hit[0]["var"], hit[1]) + } # ---- leaf level: generic half-angle leaves V and the constant leaves - refs = ([('f', c, i) for c in range(K) for i in range(len(f[c]))] + - [('g', c, i) for c in range(K) for i in range(len(g[c]))] + - [('ic', c, k) for c in range(K) for k in ic[c]] + - [('ev', c, i) for c in range(K) for i in range(len(ev[c]))] + - [('tm', c, None) for c in range(K) if tm[c] is not None] + - # a start at rest: the resting model in the same leaves - ([('fss', c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else [])) - store = {'f': f, 'g': g, 'ic': ic, 'fss': fss} - vals = [ev[c][i]['value'] if kind == 'ev' else tm[c] if kind == 'tm' - else store[kind][c][i] for kind, c, i in refs] + refs = ( + [("f", c, i) for c in range(K) for i in range(len(f[c]))] + + [("g", c, i) for c in range(K) for i in range(len(g[c]))] + + [("ic", c, k) for c in range(K) for k in ic[c]] + + [("ev", c, i) for c in range(K) for i in range(len(ev[c]))] + + [("tm", c, None) for c in range(K) if tm[c] is not None] + + + # a start at rest: the resting model in the same leaves + ([("fss", c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else []) + ) + store = {"f": f, "g": g, "ic": ic, "fss": fss} + vals = [ev[c][i]["value"] if kind == "ev" else tm[c] if kind == "tm" else store[kind][c][i] for kind, c, i in refs] # rational offsets c0 as powers of e^(i/M0), M0 over all arguments atoms, M0 = [], 1 for e in _once(vals): @@ -904,103 +939,128 @@ def state_atom(a): dec = _trig_terms(type(at), at.args[0]) if dec is not None: M0 = spy.ilcm(M0, dec[0].q) - tc = ctx.fresh('_tc_', positive=True) + tc = ctx.fresh("_tc_", positive=True) while True: found = _trig_find(vals, lambda a: True, unsupported) - if 'why' in found: + if "why" in found: return found if not found: break den = _trig_den(found, lambda t: True) key_v = {} for t, D in sorted(den.items(), key=lambda kv: str(kv[0])): - V = ctx.fresh('_tw%d_' % (len(atoms) + 1)) + V = ctx.fresh("_tw%d_" % (len(atoms) + 1)) key_v[t] = V - atoms.append({'V': V, 'phi': t / D}) + atoms.append({"V": V, "phi": t / D}) repl = {} for at, (c0, cp, terms) in found.items(): factors = [(key_v[t], int(q * den[t])) for t, q in terms.items()] if c0 != 0: if not (c0 * M0).is_Integer: - return {'why': unsupported % at} + return {"why": unsupported % at} factors.append((tc, int(c0 * M0))) repl[at] = _trig_value(type(at), factors, 2 * cp, spy.Integer(0)) xr = _shared(lambda e, repl=repl: e.xreplace(repl)) vals = [xr(e) for e in vals] - if not _terms_independent([(spy.E, a['phi'].xreplace({spy.pi: spy.Symbol('_pi_')})) - for a in atoms]): - return {'why': 'arguments of trigonometric functions that are linearly ' - 'dependent over the rationals are not supported'} + if not _terms_independent([(spy.E, a["phi"].xreplace({spy.pi: spy.Symbol("_pi_")})) for a in atoms]): + return { + "why": "arguments of trigonometric functions that are linearly " + "dependent over the rationals are not supported" + } xr = _shared(lambda e: e.xreplace({spy.pi: pis})) vals = [xr(e) for e in vals] for a in atoms: - a['phi'] = a['phi'].xreplace({spy.pi: pis}) + a["phi"] = a["phi"].xreplace({spy.pi: pis}) for (kind, c, i), v in zip(refs, vals): - if kind == 'ev': - ev[c][i]['value'] = v - elif kind == 'tm': + if kind == "ev": + ev[c][i]["value"] = v + elif kind == "tm": tm[c] = v else: store[kind][c][i] = v used = set() - for v in _once(vals + [a['phi'] for a in atoms] + [e for fc in fss for e in fc]): + for v in _once(vals + [a["phi"] for a in atoms] + [e for fc in fss for e in fc]): used |= free(v) consts = {pis, tc} & used rel = [] for a in atoms: - for z in sorted(a['phi'].free_symbols - consts, key=str): - rel.append((str(a['V']), str(z), - spy.together((1 + a['V'] ** 2) * spy.diff(a['phi'], z) / 2))) - back = {str(a['V']): str(spy.tan(a['phi'].xreplace({pis: spy.pi}) / 2)) - for a in atoms} + for z in sorted(a["phi"].free_symbols - consts, key=str): + rel.append((str(a["V"]), str(z), spy.together((1 + a["V"] ** 2) * spy.diff(a["phi"], z) / 2))) + back = {str(a["V"]): str(spy.tan(a["phi"].xreplace({pis: spy.pi}) / 2)) for a in atoms} if pis in consts: - back[str(pis)] = 'pi' + back[str(pis)] = "pi" if tc in consts: back[str(tc)] = str(spy.tan(spy.Rational(1, 2 * M0))) per_cond = [(f[c], g[c], ic[c], fss[c]) for c in range(K)] - return {'S': S, 'per_cond': per_cond, 'ev_per': ev, 'tm_per': tm, 'rel': rel, - 'consts': sorted(str(s) for s in consts), - 'atoms': [str(a['V']) for a in atoms], 'back': back, - 'n_aux': len(aux), 'codim': len(aux) + len(atoms)} + return { + "S": S, + "per_cond": per_cond, + "ev_per": ev, + "tm_per": tm, + "rel": rel, + "consts": sorted(str(s) for s in consts), + "atoms": [str(a["V"]) for a in atoms], + "back": back, + "n_aux": len(aux), + "codim": len(aux) + len(atoms), + } def _apply_const_recast(S, per_cond, ev_per, tm_per, taken): """pi and Euler's number as fixed generic leaves; arguments and return as _apply_exp_recast.""" ctx = _ExpCtx(taken) - leaves = {spy.pi: ctx.fresh('_pi_', positive=True), spy.E: ctx.ec} + leaves = {spy.pi: ctx.fresh("_pi_", positive=True), spy.E: ctx.ec} def sub(e): return spy.sympify(e).xreplace(leaves) - per_cond = [([sub(e) for e in f], [sub(e) for e in g], {k: sub(v) for k, v in ic.items()}, - [sub(e) for e in fss]) for f, g, ic, fss in per_cond] - ev = [[dict(e, value=sub(e['value'])) for e in evs] for evs in ev_per] + + per_cond = [ + ([sub(e) for e in f], [sub(e) for e in g], {k: sub(v) for k, v in ic.items()}, [sub(e) for e in fss]) + for f, g, ic, fss in per_cond + ] + ev = [[dict(e, value=sub(e["value"])) for e in evs] for evs in ev_per] tm = [None if t is None else sub(t) for t in tm_per] exprs = [e for p in per_cond for e in list(p[0]) + list(p[1]) + list(p[2].values()) + list(p[3])] - exprs += [e['value'] for evs in ev for e in evs] + [t for t in tm if t is not None] + exprs += [e["value"] for evs in ev for e in evs] + [t for t in tm if t is not None] used = set().union(*[e.free_symbols for e in exprs]) & set(leaves.values()) - back = {str(v): 'pi' if k == spy.pi else 'exp(1)' for k, v in leaves.items() if v in used} - return {'S': list(S), 'per_cond': per_cond, 'ev_per': ev, 'tm_per': tm, 'rel': [], - 'consts': sorted(back), 'atoms': [], 'back': back, 'n_aux': 0, 'codim': 0} + back = {str(v): "pi" if k == spy.pi else "exp(1)" for k, v in leaves.items() if v in used} + return { + "S": list(S), + "per_cond": per_cond, + "ev_per": ev, + "tm_per": tm, + "rel": [], + "consts": sorted(back), + "atoms": [], + "back": back, + "n_aux": 0, + "codim": 0, + } def _merge_recast(a, b): """Two recast results as one: b applied after a.""" if a is None or b is None: return b if a is None else a - back = dict(a['back']) - back.update(b['back']) - return dict(b, rel=a['rel'] + b['rel'], atoms=a['atoms'] + b['atoms'], back=back, - consts=sorted(set(a['consts']) | set(b['consts'])), - n_aux=a['n_aux'] + b['n_aux'], codim=a['codim'] + b['codim']) + back = dict(a["back"]) + back.update(b["back"]) + return dict( + b, + rel=a["rel"] + b["rel"], + atoms=a["atoms"] + b["atoms"], + back=back, + consts=sorted(set(a["consts"]) | set(b["consts"])), + n_aux=a["n_aux"] + b["n_aux"], + codim=a["codim"] + b["codim"], + ) def _tidy_logs(e): """Common factors pulled out and each numeric sum of logs as one log.""" e = spy.factor_terms(spy.cancel(e)) - return e.replace(lambda x: x.is_Add and x.is_number and x.has(spy.log), - lambda x: spy.logcombine(x, force=True)) + return e.replace(lambda x: x.is_Add and x.is_number and x.has(spy.log), lambda x: spy.logcombine(x, force=True)) def drop_monomial_content(vector, skip=None): @@ -1028,22 +1088,29 @@ def drop_monomial_content(vector, skip=None): b, x = f.as_base_exp() if b.is_Symbol and x.is_Integer: pw[b] = pw.get(b, 0) + sgn * int(x) - common = pw if common is None else { - b: (min(x, common[b]) if x > 0 else max(x, common[b])) - for b, x in pw.items() if b in common and (x > 0) == (common[b] > 0)} + common = ( + pw + if common is None + else { + b: (min(x, common[b]) if x > 0 else max(x, common[b])) + for b, x in pw.items() + if b in common and (x > 0) == (common[b] > 0) + } + ) m = spy.Integer(1) for b, x in (common or {}).items(): - m *= b ** x + m *= b**x return {k: str(spy.cancel(e / m)) for (k, _), e in zip(items, es)} def exp_backsub_expr(expr, names, values): """A component in the exponential leaves back in the model symbols.""" + def as_list(v): return list(v) if isinstance(v, (list, tuple)) else [v] + names, values = as_list(names), as_list(values) - _, parse = _make_local_parse([str(expr)] + [str(v) for v in values] + - [str(n) for n in names]) + _, parse = _make_local_parse([str(expr)] + [str(v) for v in values] + [str(n) for n in names]) e = parse(str(expr)) sub = {parse(str(n)): parse(str(v)) for n, v in zip(names, values)} for _ in range(len(sub) + 1): @@ -1063,7 +1130,7 @@ def trig_full_angle(vector, skip=None): halves = sorted(set().union(*[e.atoms(spy.tan) for e in es]), key=str) if not halves: return dict(items) - Vs = [spy.Dummy('V') for _ in halves] + Vs = [spy.Dummy("V") for _ in halves] es = [spy.cancel(e.xreplace(dict(zip(halves, Vs)))) for e in es] keep = [k not in skip for k, _ in items] L = spy.Integer(1) @@ -1080,9 +1147,8 @@ def trig_full_angle(vector, skip=None): # sin(u) = 2V/(1 + V^2), cos(u) = (1 - V^2)/(1 + V^2), 1 + V^2 = 2/(1 + cos(u)) rels, sub = [], {} for h, V in zip(halves, Vs): - deg = max((spy.degree(e, V) for e, kp in zip(es, keep) if kp and e != 0), - default=0) - es = [e / (1 + V ** 2) ** ((deg + 1) // 2) for e in es] + deg = max((spy.degree(e, V) for e, kp in zip(es, keep) if kp and e != 0), default=0) + es = [e / (1 + V**2) ** ((deg + 1) // 2) for e in es] sn, cs = spy.sin(2 * h.args[0]), spy.cos(2 * h.args[0]) sub[V] = sn / (1 + cs) rels.append((sn, cs)) @@ -1091,8 +1157,8 @@ def trig_full_angle(vector, skip=None): v = spy.cancel(spy.together(e.xreplace(sub))) num, den = spy.fraction(v) for sn, cs in rels: - num = spy.expand(num).subs(sn ** 2, 1 - cs ** 2) - den = spy.expand(den).subs(sn ** 2, 1 - cs ** 2) + num = spy.expand(num).subs(sn**2, 1 - cs**2) + den = spy.expand(den).subs(sn**2, 1 - cs**2) v = spy.factor(spy.cancel(num / den)) if spy.count_ops(v) < 200: v = spy.factor(spy.trigsimp(v)) @@ -1108,8 +1174,7 @@ def trig_full_angle(vector, skip=None): def _func_pow(a): - return a.is_Pow and not a.base.is_Symbol and not a.base.is_number and \ - a.exp.is_Rational and not a.exp.is_Integer + return a.is_Pow and not a.base.is_Symbol and not a.base.is_number and a.exp.is_Rational and not a.exp.is_Integer def _func_atoms(e): @@ -1127,23 +1192,24 @@ def _func_derivative(a, u): if t is spy.log: return 1 / u if t is spy.atan: - return 1 / (1 + u ** 2) + return 1 / (1 + u**2) if t is spy.atanh: - return 1 / (1 - u ** 2) + return 1 / (1 - u**2) if t is spy.asin: - return 1 / spy.sqrt(1 - u ** 2) + return 1 / spy.sqrt(1 - u**2) if t is spy.acos: - return -1 / spy.sqrt(1 - u ** 2) + return -1 / spy.sqrt(1 - u**2) if t is spy.asinh: - return 1 / spy.sqrt(1 + u ** 2) + return 1 / spy.sqrt(1 + u**2) if t is spy.acosh: - return 1 / spy.sqrt(u ** 2 - 1) + return 1 / spy.sqrt(u**2 - 1) return None def _engine_holds(constants=(), degrees=()): """True if every prime holds the roots and denominators, else raises NeedPrimesError.""" from ..gfp import NeedPrimesError, all_primes, holds_roots + if not all(holds_roots(constants, q, degrees) for q in all_primes()): raise NeedPrimesError(constants, degrees) return True @@ -1182,10 +1248,10 @@ def _apply_func_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_res g = [[spy.sympify(e) for e in p[1]] for p in per_cond] ic = [{k: spy.sympify(v) for k, v in p[2].items()} for p in per_cond] fss = [list(p[3]) for p in per_cond] - ev = [[dict(e, value=spy.sympify(e['value'])) for e in evs] for evs in ev_per] + ev = [[dict(e, value=spy.sympify(e["value"])) for e in evs] for evs in ev_per] tm = [None if t is None else spy.sympify(t) for t in tm_per] ev = _series_events(S, ic, ev, chain_of, spy.log) - if 'why' in ev: + if "why" in ev: return ev # ---- dynamics: auxiliary states, innermost function first @@ -1199,18 +1265,17 @@ def _apply_func_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_res u = _func_arg(a) if a in found or not (u.free_symbols & states): continue - if any(_func_atoms(x) and (_func_arg(x).free_symbols & states) - for x in _func_atoms(u)): + if any(_func_atoms(x) and (_func_arg(x).free_symbols & states) for x in _func_atoms(u)): continue found.append(a) if not found: break found.sort(key=spy.default_sort_key) - key = {a: ctx.fresh('_fx%d_' % (len(aux) + i + 1)) for i, a in enumerate(found)} + key = {a: ctx.fresh("_fx%d_" % (len(aux) + i + 1)) for i, a in enumerate(found)} f = [[e.xreplace(key) for e in fc] for fc in f] g = [[e.xreplace(key) for e in gc] for gc in g] for a in found: - aux.append({'X': key[a], 'atom': a}) + aux.append({"X": key[a], "atom": a}) for c in range(K): rhs_of = dict(zip(S, f[c])) for a in found: @@ -1224,48 +1289,59 @@ def _apply_func_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_res if isinstance(a, (spy.Pow, spy.log)) and u0.is_number and u0.is_positive is not True: # the auxiliary state of a power or logarithm divides by its argument, which must not # start at zero or below - return {'why': 'the argument of %s starts at %s, but a logarithm, fractional power or ' - 'base of a free exponent must be positive; give that initial value as a positive ' - 'parameter' % (str(a).replace('**', '^'), u0)} + return { + "why": "the argument of %s starts at %s, but a logarithm, fractional power or " + "base of a free exponent must be positive; give that initial value as a positive " + "parameter" % (str(a).replace("**", "^"), u0) + } ic[c][str(W)] = a.xreplace(ic_sub) fss[c].append(spy.Integer(0)) for c in range(K): for e in ev[c]: - if any(str(e['var']) in {str(s) for s in _func_arg(a).free_symbols} for a in found): - return {'why': 'an event on %s, which enters the argument of %s, is not ' - 'supported' % (e['var'], next(a for a in found if str(e['var']) in - {str(s) for s in _func_arg(a).free_symbols}))} + if any(str(e["var"]) in {str(s) for s in _func_arg(a).free_symbols} for a in found): + return { + "why": "an event on %s, which enters the argument of %s, is not " + "supported" + % ( + e["var"], + next(a for a in found if str(e["var"]) in {str(s) for s in _func_arg(a).free_symbols}), + ) + } S += [key[a] for a in found] hit = _state_events(ev, {pre_state(s) for s in S}, _func_atoms) if hit is not None: - return {'why': 'the event value %s for %s reads the state through %s, which is not ' - 'supported' % (hit[0]['value'], hit[0]['var'], hit[1])} + return { + "why": "the event value %s for %s reads the state through %s, which is not " + "supported" % (hit[0]["value"], hit[0]["var"], hit[1]) + } # ---- leaf level: transcendental functions of leaves as generic leaves - refs = ([('f', c, i) for c in range(K) for i in range(len(f[c]))] + - [('g', c, i) for c in range(K) for i in range(len(g[c]))] + - [('ic', c, k) for c in range(K) for k in ic[c]] + - [('ev', c, i) for c in range(K) for i in range(len(ev[c]))] + - [('tm', c, None) for c in range(K) if tm[c] is not None] + - # a start at rest: the resting model in the same leaves - ([('fss', c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else [])) - store = {'f': f, 'g': g, 'ic': ic, 'fss': fss} - vals = [ev[c][i]['value'] if kind == 'ev' else tm[c] if kind == 'tm' - else store[kind][c][i] for kind, c, i in refs] + refs = ( + [("f", c, i) for c in range(K) for i in range(len(f[c]))] + + [("g", c, i) for c in range(K) for i in range(len(g[c]))] + + [("ic", c, k) for c in range(K) for k in ic[c]] + + [("ev", c, i) for c in range(K) for i in range(len(ev[c]))] + + [("tm", c, None) for c in range(K) if tm[c] is not None] + + + # a start at rest: the resting model in the same leaves + ([("fss", c, i) for c in range(K) for i in range(len(fss[c]))] if at_rest else []) + ) + store = {"f": f, "g": g, "ic": ic, "fss": fss} + vals = [ev[c][i]["value"] if kind == "ev" else tm[c] if kind == "tm" else store[kind][c][i] for kind, c, i in refs] atoms, consts, back = [], [], {} leaf_of = {} def log_leaf(p): # one generic leaf per irreducible factor: logs of distinct irreducibles are independent if p not in leaf_of: - V = ctx.fresh('_fl%d_' % (len(atoms) + 1)) + V = ctx.fresh("_fl%d_" % (len(atoms) + 1)) leaf_of[p] = V - atoms.append({'V': V, 'phi': p, 'kind': 'log', 'atom': spy.log(p), 'dphi': 1 / p}) + atoms.append({"V": V, "phi": p, "kind": "log", "atom": spy.log(p), "dphi": 1 / p}) return leaf_of[p] def const_leaf(a): if a not in leaf_of: - C = ctx.fresh('_fc%d_' % (len(consts) + 1), positive=bool(a.is_positive)) + C = ctx.fresh("_fc%d_" % (len(consts) + 1), positive=bool(a.is_positive)) leaf_of[a] = C consts.append(C) back[str(C)] = str(a) @@ -1301,12 +1377,12 @@ def leaf_value(a): return None if lo is None or hi is None else (lo - hi) / 2 if t in (spy.atan, spy.asin, spy.acos, spy.asinh, spy.acosh): if a not in leaf_of: - V = ctx.fresh('_fa%d_' % (len(atoms) + 1)) + V = ctx.fresh("_fa%d_" % (len(atoms) + 1)) leaf_of[a] = V - atoms.append({'V': V, 'phi': u, 'kind': 'inv', 'atom': a, - 'dphi': _func_derivative(a, u)}) + atoms.append({"V": V, "phi": u, "kind": "inv", "atom": a, "dphi": _func_derivative(a, u)}) return leaf_of[a] return None + while True: found = {} for e in vals: @@ -1321,25 +1397,28 @@ def leaf_value(a): vals = [e.xreplace(found) for e in vals] # a leaf that cancels from every value is no coordinate used = set().union(*(spy.sympify(e).free_symbols for e in vals)) - atoms = [a for a in atoms if a['V'] in used] + atoms = [a for a in atoms if a["V"] in used] # pi and e left by an evaluated function value are transcendental constants - vals = [e.xreplace({c: const_leaf(c) for c in e.atoms(spy.NumberSymbol) if c in (spy.pi, spy.E)}) - for e in vals] + vals = [e.xreplace({c: const_leaf(c) for c in e.atoms(spy.NumberSymbol) if c in (spy.pi, spy.E)}) for e in vals] for a in aux: for (kind, _c, k), v in zip(refs, vals): - if kind == 'ic' and k == str(a['X']) and not _is_sqrt_rational(v): - return {'why': 'the term %s starts at %s, which the finite-field engine ' - 'cannot evaluate exactly; use engine="symbolic"' - % (str(a['atom']).replace('**', '^'), str(v).replace('**', '^'))} - inv_args = [a['phi'] for a in atoms if a['kind'] == 'inv'] + if kind == "ic" and k == str(a["X"]) and not _is_sqrt_rational(v): + return { + "why": "the term %s starts at %s, which the finite-field engine " + 'cannot evaluate exactly; use engine="symbolic"' + % (str(a["atom"]).replace("**", "^"), str(v).replace("**", "^")) + } + inv_args = [a["phi"] for a in atoms if a["kind"] == "inv"] for i, u in enumerate(inv_args): - if any(u.free_symbols & v.free_symbols for v in inv_args[i + 1:]): - return {'why': 'inverse trigonometric or hyperbolic functions of leaves that share ' - 'a coordinate (%s) are not supported' % u} + if any(u.free_symbols & v.free_symbols for v in inv_args[i + 1 :]): + return { + "why": "inverse trigonometric or hyperbolic functions of leaves that share " + "a coordinate (%s) are not supported" % u + } for (kind, c, i), v in zip(refs, vals): - if kind == 'ev': - ev[c][i]['value'] = v - elif kind == 'tm': + if kind == "ev": + ev[c][i]["value"] = v + elif kind == "tm": tm[c] = v else: store[kind][c][i] = v @@ -1347,12 +1426,20 @@ def leaf_value(a): cset = set(consts) rel = [] for a in atoms: - u = a['phi'] + u = a["phi"] for z in sorted(u.free_symbols - cset, key=str): - rel.append((str(a['V']), str(z), spy.together(a['dphi'] * spy.diff(u, z)))) - back[str(a['V'])] = str(a['atom']) + rel.append((str(a["V"]), str(z), spy.together(a["dphi"] * spy.diff(u, z)))) + back[str(a["V"])] = str(a["atom"]) per_cond = [(f[c], g[c], ic[c], fss[c]) for c in range(K)] - return {'S': S, 'per_cond': per_cond, 'ev_per': ev, 'tm_per': tm, 'rel': rel, - 'consts': sorted(str(s) for s in consts), - 'atoms': [str(a['V']) for a in atoms], 'back': back, - 'n_aux': len(aux), 'codim': len(aux) + len(atoms)} + return { + "S": S, + "per_cond": per_cond, + "ev_per": ev, + "tm_per": tm, + "rel": rel, + "consts": sorted(str(s) for s in consts), + "atoms": [str(a["V"]) for a in atoms], + "back": back, + "n_aux": len(aux), + "codim": len(aux) + len(atoms), + } diff --git a/src/symident/sym/restcheck.py b/src/symident/sym/restcheck.py index 0eac0f8..e786e9f 100644 --- a/src/symident/sym/restcheck.py +++ b/src/symident/sym/restcheck.py @@ -22,6 +22,7 @@ def _run_msolve(names, eqs): (work.quick_msolve()).""" from ..detection import work from .msolve import MsolveMissingError, _msolve_binary + try: exe = _msolve_binary() except MsolveMissingError: @@ -41,6 +42,7 @@ def _run_msolve(names, eqs): if not txt: return None from ..detection.discrete import parse_rational + try: return parse_rational(txt) except (SyntaxError, ValueError, TypeError, NameError): @@ -104,6 +106,7 @@ def modular_decision(eqs, unknowns, pos, rng, draws=_POINTS): from ..detection import work from ..detection.discrete import _gb_count from ..gfp import PRIMES + if not unknowns or not eqs: return {"exists": "open", "bound": None, "draws": []} xs = [spy.Symbol(x) for x in unknowns] @@ -120,7 +123,7 @@ def modular_decision(eqs, unknowns, pos, rng, draws=_POINTS): names = [f"x{i}" for i in range(len(xs))] ren = dict(zip(xs, [spy.Symbol(n) for n in names])) square = len(nums) == len(xs) - M = 2 ** 64 + M = 2**64 Dt = math.prod(max(1, int(d)) for d in deg_theta) bound, verdicts = 1.0, [] for _ in range(draws): @@ -154,8 +157,14 @@ def modular_decision(eqs, unknowns, pos, rng, draws=_POINTS): verdicts.append("no") else: verdicts.append("open") - elif k and square and whole and dims and k == dims[0] and \ - all(any(int(c) % p for c in q.coeffs()) for q in polys + [w]): + elif ( + k + and square + and whole + and dims + and k == dims[0] + and all(any(int(c) % p for c in q.coeffs()) for q in polys + [w]) + ): # as many distinct values as the dimension of the quotient, no equation zero modulo p: every point is simple verdicts.append("proven") else: @@ -179,10 +188,16 @@ def rest_check(multi, zero_of, positive, points=_POINTS): return {"checked": False, "why": f"more than {_MAX_STATES} resting states"} pos = _positive_names(positive) rng = session.current().rng("rest check") - report = {"points": 0, "consistent": 0, "in_domain": 0, "undecided": 0, "checked": True, - "how": "msolve over Q at random rational parameter values, real roots isolated; a check at " - "random points, not a proof. exists: a Groebner basis modulo a random prime at random " - "integer points, proven by a simple point, or no with the error bound"} + report = { + "points": 0, + "consistent": 0, + "in_domain": 0, + "undecided": 0, + "checked": True, + "how": "msolve over Q at random rational parameter values, real roots isolated; a check at " + "random points, not a proof. exists: a Groebner basis modulo a random prime at random " + "integer points, proven by a simple point, or no with the error bound", + } constant = set() for _ in range(points): # per system: "none" (no complex solution), "out" (none in the domain), "unsure" or "in" @@ -227,6 +242,7 @@ def rest_check(multi, zero_of, positive, points=_POINTS): data = _run_msolve(names, polys) if data is None: from .msolve import MsolveMissingError, _msolve_binary + try: _msolve_binary() except MsolveMissingError: @@ -242,7 +258,7 @@ def rest_check(multi, zero_of, positive, points=_POINTS): verdicts = [] for sol in data[1][1]: v = "in" - for x, (lo, hi) in zip(unknowns, sol[:len(unknowns)]): + for x, (lo, hi) in zip(unknowns, sol[: len(unknowns)]): if pos is True or x in pos: if hi <= 0: v = "out" @@ -266,18 +282,25 @@ def rest_check(multi, zero_of, positive, points=_POINTS): if decisions: verdict = [d["exists"] for d in decisions] report["exists"] = "no" if "no" in verdict else "proven" if all(v == "proven" for v in verdict) else "open" - report["bound"] = max((d["bound"] for d in decisions if d["exists"] == "no" and d["bound"] is not None), - default=None) if report["exists"] == "no" else None + report["bound"] = ( + max((d["bound"] for d in decisions if d["exists"] == "no" and d["bound"] is not None), default=None) + if report["exists"] == "no" + else None + ) if report["exists"] == "no" and any(d["exists"] == "no" and d["bound"] is None for d in decisions): report["bound"] = None if report["points"] and not report["consistent"] and report.get("exists") != "proven": states = sorted(constant) or sorted({x for _, u in systems for x in u}) - what = (f"the balance{'s' if len(states) > 1 else ''} of {', '.join(states)} at rest, with the inputs " - f"at zero, {'are nonzero constants' if len(states) > 1 else 'is a nonzero constant'}" if constant - else "the resting balances of " + ", ".join(states) + " have no common solution over the complex " - "numbers") + what = ( + f"the balance{'s' if len(states) > 1 else ''} of {', '.join(states)} at rest, with the inputs " + f"at zero, {'are nonzero constants' if len(states) > 1 else 'is a nonzero constant'}" + if constant + else "the resting balances of " + ", ".join(states) + " have no common solution over the complex numbers" + ) sure = f" (error bound {report['bound']:.3g})" if report.get("bound") is not None else "" - raise InputError(f"equilibrate: {what} at {report['points']} random parameter values, " - f"so the model has no resting state for generic parameters{sure}; check the right-hand " - "sides, the inputs at rest and the conserved totals") + raise InputError( + f"equilibrate: {what} at {report['points']} random parameter values, " + f"so the model has no resting state for generic parameters{sure}; check the right-hand " + "sides, the inputs at rest and the conserved totals" + ) return report diff --git a/src/symident/sym/restforward.py b/src/symident/sym/restforward.py index 55f79ac..8ea9389 100644 --- a/src/symident/sym/restforward.py +++ b/src/symident/sym/restforward.py @@ -30,8 +30,11 @@ def _forward_rate_pick(rhs_by_name, solve_states, param_names, forcings, keep_fr keep_free = set(keep_free or []) # never solve for a recast coordinate: it multiplies a turnover rate, which would make # f bilinear in the rates - paramset = {spy.Symbol(pn) for pn in param_names - if pn not in keep_free and not pn.startswith('_E_') and not pn.startswith('_L_')} + paramset = { + spy.Symbol(pn) + for pn in param_names + if pn not in keep_free and not pn.startswith("_E_") and not pn.startswith("_L_") + } forc = {spy.Symbol(nm) for nm in forcings} cand, appear = {}, {} for s in solve_states: @@ -68,9 +71,9 @@ def _forward_rate_pick(rhs_by_name, solve_states, param_names, forcings, keep_fr def _rate_matching(cand, appear, order): """A complete matching of states to candidate rates by augmenting paths, or None if there is none.""" - prefs = {s: [r for _, _, r in sorted((sc, appear.get(r, 99), r) for sc, r in cand[s])] - for s in order} + prefs = {s: [r for _, _, r in sorted((sc, appear.get(r, 99), r) for sc, r in cand[s])] for s in order} owner = {} + def augment(s, seen): for r in prefs[s]: if r in seen: @@ -80,6 +83,7 @@ def augment(s, seen): owner[r] = s return True return False + sys.setrecursionlimit(max(sys.getrecursionlimit(), 10 * len(order) + 100)) for s in order: if not augment(s, set()): @@ -93,7 +97,7 @@ def _forward_plan(rhs_by_name, solve_states, param_names, forcings, keep_free=No pre = [] for _ in range(len(solve_states)): r = _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_free, pre) - if r is None or r[0] != 'dependent': + if r is None or r[0] != "dependent": return r new = [u for u in r[1] if u not in pre] if not new: @@ -102,11 +106,13 @@ def _forward_plan(rhs_by_name, solve_states, param_names, forcings, keep_free=No return None -def _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_free=None, - pre_bs=()): +def _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_free=None, pre_bs=()): keep_free = set(keep_free or []) - paramset = {spy.Symbol(pn) for pn in param_names - if pn not in keep_free and not pn.startswith('_E_') and not pn.startswith('_L_')} + paramset = { + spy.Symbol(pn) + for pn in param_names + if pn not in keep_free and not pn.startswith("_E_") and not pn.startswith("_L_") + } forc = {spy.Symbol(nm) for nm in forcings} polys = {s: spy.sympify(rhs_by_name[s]) for s in solve_states} params = {s: polys[s].free_symbols & paramset for s in solve_states} @@ -141,7 +147,7 @@ def _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_fr for a in ps: partners.setdefault(a, set()).update(x for x in ps if x != a) banned = set() - bs = list(pre_bs) # balances solved for their own state + bs = list(pre_bs) # balances solved for their own state for u in bs: try: pu = spy.Poly(polys[u], spy.Symbol(u)) @@ -152,7 +158,8 @@ def _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_fr while True: forbidden = {str(r) for u in bs for r in params[u]} | banned rest = [s for s in solve_states if s not in bs] - match = {} # rate -> balance, by augmenting paths + match = {} # rate -> balance, by augmenting paths + def augment(s, seen): for r in cand[s]: if r in forbidden or r in seen: @@ -162,12 +169,14 @@ def augment(s, seen): match[r] = s return True return False + for s in sorted(rest, key=lambda s: len(cand[s])): augment(s, set()) # ban the solve rate with the most partners among the chosen, then rematch chosen = set(match) - clash = sorted((r for r in chosen if partners.get(r, set()) & chosen), - key=lambda r: (-len(partners.get(r, ())), r)) + clash = sorted( + (r for r in chosen if partners.get(r, set()) & chosen), key=lambda r: (-len(partners.get(r, ())), r) + ) if clash: banned.add(clash[0]) continue @@ -184,8 +193,7 @@ def augment(s, seen): return None bs.extend(unmatched) # dependency order: a state-solved balance reads the other states it contains - deps = {u: {str(x) for x in polys[u].free_symbols if str(x) in state_set} & set(bs) - {u} - for u in bs} + deps = {u: {str(x) for x in polys[u].free_symbols if str(x) in state_set} & set(bs) - {u} for u in bs} order = [] while len(order) < len(bs): ready = [u for u in bs if u not in order and deps[u] <= set(order)] @@ -200,6 +208,7 @@ def augment(s, seen): rng = session.current().rng("restforward.basis", len(rest)) syms = set().union(*(polys[s].free_symbols for s in rest)) if rest else set() pt = {x: rng.randrange(2, Q - 1) for x in sorted(syms, key=str)} + def score(r): best = 2 for s in rest: @@ -209,16 +218,21 @@ def score(r): if spy.Symbol(s) in coef.free_symbols: best = min(best, 0 if coef.could_extract_minus_sign() else 1) return best - cols = sorted({r for s in rest for r in cand[s]} - forbidden, - key=lambda r: (score(r), sum(r in cand[s] for s in rest), r)) + + cols = sorted( + {r for s in rest for r in cand[s]} - forbidden, key=lambda r: (score(r), sum(r in cand[s] for s in rest), r) + ) col_vec = {} + def vec_of(r): if r not in col_vec: - col_vec[r] = [int(spy.Poly(polys[s], spy.Symbol(r)).nth(1).xreplace(pt)) % Q - if r in cand[s] else 0 for s in rest] + col_vec[r] = [ + int(spy.Poly(polys[s], spy.Symbol(r)).nth(1).xreplace(pt)) % Q if r in cand[s] else 0 for s in rest + ] return col_vec[r] + def pick_basis(col_order): - basis, chosen = [], [] # echelon rows (pivot, vector) mod Q + basis, chosen = [], [] # echelon rows (pivot, vector) mod Q for r in col_order: if partners.get(r, set()) & set(chosen): continue @@ -236,6 +250,7 @@ def pick_basis(col_order): if len(chosen) == len(rest): break return chosen + chosen = pick_basis(cols) # the partner rule can block the greedy order: shuffles within each preference class key_of = {r: score(r) for r in cols} @@ -251,8 +266,7 @@ def pick_basis(col_order): # the balances whose coefficient rows depend on the earlier ones rows, dep = [], [] for s in rest: - v = [int(spy.Poly(polys[s], spy.Symbol(r)).nth(1).xreplace(pt)) % Q - if r in cand[s] else 0 for r in cols] + v = [int(spy.Poly(polys[s], spy.Symbol(r)).nth(1).xreplace(pt)) % Q if r in cand[s] else 0 for r in cols] for piv, b in rows: if v[piv]: fct = v[piv] @@ -263,25 +277,32 @@ def pick_basis(col_order): continue inv = pow(v[piv], Q - 2, Q) rows.append((piv, [x * inv % Q for x in v])) - return ('dependent', dep) + return ("dependent", dep) return order, chosen -_forward_cache = {} +_forward_cache: dict = {} -def _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve=(), - held=()): +def _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve=(), held=()): """Cached prime-independent compile of the forward solve, or {'bad': reason} if not linear in the rates.""" state_solve = tuple(state_solve) held = set(held) - key = (tuple(model), tuple(state_names), tuple(param_names), tuple(sorted(forcings)), - tuple(solve_rates), state_solve, tuple(sorted(held))) + key = ( + tuple(model), + tuple(state_names), + tuple(param_names), + tuple(sorted(forcings)), + tuple(solve_rates), + state_solve, + tuple(sorted(held)), + ) c = _forward_cache.get(key) if c is not None: return c - (param_syms, solve_states, polys, _, _, gens0, jx_terms, jt_terms, - _, _, _, _) = _ss_compile(model, state_names, param_names, forcings, linear=False) + (param_syms, solve_states, polys, _, _, gens0, jx_terms, jt_terms, _, _, _, _) = _ss_compile( + model, state_names, param_names, forcings, linear=False + ) solve_set = set(solve_rates) r_syms = [spy.Symbol(r) for r in solve_rates] rgens = [th for th in param_syms if str(th) not in solve_set] + list(solve_states) @@ -292,10 +313,9 @@ def _forward_compile(model, state_names, param_names, forcings, solve_rates, sta pu = spy.Poly(spy.sympify(polys[idx_of[u]]), spy.Symbol(u)) c1, c0 = pu.nth(1).as_expr(), pu.nth(0).as_expr() if (c1.free_symbols | c0.free_symbols) - rgenset: - return {'bad': 'state-solved balance %s holds a solve rate' % u} + return {"bad": "state-solved balance %s holds a solve rate" % u} state_t.append((u, _poly_terms(c1, rgens), _poly_terms(c0, rgens))) - rate_rows = [i for i in range(len(solve_states)) - if str(solve_states[i]) not in set(state_solve) | held] + rate_rows = [i for i in range(len(solve_states)) if str(solve_states[i]) not in set(state_solve) | held] coef_t, const_t = [], [] for i in rate_rows: fexp = spy.sympify(polys[i]) @@ -303,22 +323,41 @@ def _forward_compile(model, state_names, param_names, forcings, solve_rates, sta for r in r_syms: dexp = spy.diff(fexp, r) if dexp.free_symbols - rgenset: - return {'bad': 'not linear in the chosen rates at %s' % str(solve_states[i])} + return {"bad": "not linear in the chosen rates at %s" % str(solve_states[i])} row.append(_poly_terms(dexp, rgens)) cexp = fexp.subs({r: spy.Integer(0) for r in r_syms}) if cexp.free_symbols - rgenset: - return {'bad': 'unsubstituted symbol in balance %s' % str(solve_states[i])} + return {"bad": "unsubstituted symbol in balance %s" % str(solve_states[i])} coef_t.append(row) const_t.append(_poly_terms(cexp, rgens)) - c = {'param_names': [str(s) for s in param_syms], 'solve_states': [str(s) for s in solve_states], - 'rgens': [str(g) for g in rgens], 'coef_t': coef_t, 'const_t': const_t, 'state_t': state_t, - 'jx_terms': jx_terms, 'jt_terms': jt_terms, 'gens': [str(g) for g in gens0]} + c = { + "param_names": [str(s) for s in param_syms], + "solve_states": [str(s) for s in solve_states], + "rgens": [str(g) for g in rgens], + "coef_t": coef_t, + "const_t": const_t, + "state_t": state_t, + "jx_terms": jx_terms, + "jt_terms": jt_terms, + "gens": [str(g) for g in gens0], + } _forward_cache[key] = c return c -def solve_forward_modular(model, state_names, param_names, state_vals, param_vals, prime, - forcings=None, solve_rates=None, keep_free=None, state_solve=None, held=None): +def solve_forward_modular( + model, + state_names, + param_names, + state_vals, + param_vals, + prime, + forcings=None, + solve_rates=None, + keep_free=None, + state_solve=None, + held=None, +): """Solve f = 0 over GF(prime) for a turnover subset of rates at given resting values, or {'ok': False, 'why'}.""" p = int(prime) model = _as_list(model) @@ -340,58 +379,66 @@ def solve_forward_modular(model, state_names, param_names, state_vals, param_val if solve_rates is None: plan = _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) if plan is None: - return {'ok': False, 'why': 'no complete forward rate matching'} + return {"ok": False, "why": "no complete forward rate matching"} state_solve, solve_rates = plan solve_rates = _as_list(solve_rates) c = _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve, held) - if 'bad' in c and picked: + if "bad" in c and picked: # the direct pick holds two rates of one product: use the planned matching plan = _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) if plan is not None: state_solve, solve_rates = plan - c = _forward_compile(model, state_names, param_names, forcings, solve_rates, - state_solve, held) - if 'bad' in c: - return {'ok': False, 'why': c['bad']} - solve_states = c['solve_states'] - n_r = len(c['coef_t']) + c = _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve, held) + if "bad" in c: + return {"ok": False, "why": c["bad"]} + solve_states = c["solve_states"] + n_r = len(c["coef_t"]) if len(solve_rates) != n_r: - return {'ok': False, 'why': 'rate/state count mismatch (%d rates, %d balances)' - % (len(solve_rates), n_r)} + return {"ok": False, "why": "rate/state count mismatch (%d rates, %d balances)" % (len(solve_rates), n_r)} + def cvfree(nm): return svd[nm] if nm in svd else (pvd[nm] if nm in pvd else 0) - rg_idx = {nm: k for k, nm in enumerate(c['rgens'])} - rgv = [cvfree(nm) for nm in c['rgens']] + + rg_idx = {nm: k for k, nm in enumerate(c["rgens"])} + rgv = [cvfree(nm) for nm in c["rgens"]] # state-solved balances first, each x = -c0/c1 at the values known so far - for u, c1_t, c0_t in c['state_t']: + for u, c1_t, c0_t in c["state_t"]: c1 = _eval_terms(c1_t, rgv, p) if c1 == 0: - return {'ok': False, 'why': 'vanishing state pivot mod p at %s' % u} + return {"ok": False, "why": "vanishing state pivot mod p at %s" % u} xu = (-_eval_terms(c0_t, rgv, p)) * pow(c1, p - 2, p) % p if xu == 0: - return {'ok': False, 'why': 'zero resting state %s' % u} + return {"ok": False, "why": "zero resting state %s" % u} svd[u] = xu rgv[rg_idx[u]] = xu - A = [[_eval_terms(c['coef_t'][i][j], rgv, p) for j in range(n_r)] for i in range(n_r)] - b = [[(-_eval_terms(c['const_t'][i], rgv, p)) % p] for i in range(n_r)] + A = [[_eval_terms(c["coef_t"][i][j], rgv, p) for j in range(n_r)] for i in range(n_r)] + b = [[(-_eval_terms(c["const_t"][i], rgv, p)) % p] for i in range(n_r)] X = _solve_mod(A, b, p) if X is None: - return {'ok': False, 'why': 'singular forward system mod p'} + return {"ok": False, "why": "singular forward system mod p"} rates_dict = {solve_rates[j]: int(X[j][0]) % p for j in range(len(solve_rates))} + def cvfull(nm): if nm in rates_dict: return rates_dict[nm] return svd[nm] if nm in svd else (pvd[nm] if nm in pvd else 0) - ptvals = [cvfull(nm) for nm in c['gens']] + + ptvals = [cvfull(nm) for nm in c["gens"]] keep = [i for i, s in enumerate(solve_states) if s not in held] held_idx = [i for i, s in enumerate(solve_states) if s in held] - df_jx = [[_eval_terms(c['jx_terms'][i][j], ptvals, p) for j in keep] for i in keep] - df_jt = {th: [_eval_terms(c['jt_terms'][th][i], ptvals, p) for i in keep] - for th in c['param_names']} + df_jx = [[_eval_terms(c["jx_terms"][i][j], ptvals, p) for j in keep] for i in keep] + df_jt = {th: [_eval_terms(c["jt_terms"][th][i], ptvals, p) for i in keep] for th in c["param_names"]} for hj in held_idx: - df_jt[solve_states[hj]] = [_eval_terms(c['jx_terms'][i][hj], ptvals, p) for i in keep] - return {'ok': True, 'rates': rates_dict, 'solve_rates': list(solve_rates), - 'state_solve': list(state_solve), - 'solve_states': list(solve_states), 'val_by': {s: cvfull(s) for s in solve_states}, - 'df_jx': df_jx, 'df_jt': df_jt, 'df_state_cols': [solve_states[j] for j in keep], - 'df_param_cols': list(c['param_names']) + [solve_states[j] for j in held_idx]} + df_jt[solve_states[hj]] = [_eval_terms(c["jx_terms"][i][hj], ptvals, p) for i in keep] + return { + "ok": True, + "rates": rates_dict, + "solve_rates": list(solve_rates), + "state_solve": list(state_solve), + "solve_states": list(solve_states), + "val_by": {s: cvfull(s) for s in solve_states}, + "df_jx": df_jx, + "df_jt": df_jt, + "df_state_cols": [solve_states[j] for j in keep], + "df_param_cols": list(c["param_names"]) + [solve_states[j] for j in held_idx], + } diff --git a/src/symident/sym/scaling.py b/src/symident/sym/scaling.py index 1f55439..911762e 100644 --- a/src/symident/sym/scaling.py +++ b/src/symident/sym/scaling.py @@ -73,10 +73,12 @@ def mons(terms): if e: a[idx[k]] = e elif k.free_symbols & zset: - raise InapplicableError('not a monomial in the coordinates: %s' % spy.Mul( - *[b ** e for b, e in powers])) + raise InapplicableError( + "not a monomial in the coordinates: %s" % spy.Mul(*[b**e for b, e in powers]) + ) out.setdefault(tuple(sorted(a.items())), a) return list(out.values()) + p, q = _expanded(expr) return mons(p), mons(q) @@ -118,14 +120,15 @@ def rec(e): be = _exp_atom(e) if be is not None: exps.append(rec(be[1])) - return spy.Dummy('exp') + return spy.Dummy("exp") if isinstance(e, _TRIG) or type(e) in _TRIG_RECIPROCAL: exps.append(rec(e.args[0])) - return spy.Dummy('trig') + return spy.Dummy("trig") if logs and isinstance(e, spy.log): exps.append(rec(e.args[0])) - return spy.Dummy('log') + return spy.Dummy("log") return e.func(*[rec(a) for a in e.args]) + return rec(_hyp_to_exp(expr)), exps @@ -139,7 +142,7 @@ def _power_atoms(exprs, states, frozen): continue if at.exp.free_symbols & states: continue - out[at] = spy.Symbol('_P%d_%s' % (len(out), at.base)) + out[at] = spy.Symbol("_P%d_%s" % (len(out), at.base)) return out @@ -159,9 +162,8 @@ def fresh(e, t): obs_new = [g for g in obs_functions if fresh(g, -1)] eq_new = [i for i in range(m) if fresh(diff_equations[i], i)] split = [_exp_split(e, logs) for e in obs_new + [diff_equations[i] for i in eq_new]] - obs_functions = ([s[0] for s in split[:len(obs_new)]] + - [u for s in split for u in s[1]]) - eq_split = {i: s[0] for i, s in zip(eq_new, split[len(obs_new):])} + obs_functions = [s[0] for s in split[: len(obs_new)]] + [u for s in split for u in s[1]] + eq_split = {i: s[0] for i, s in zip(eq_new, split[len(obs_new) :])} zkey = tuple(zvars) rows, keys = [], set() @@ -198,8 +200,7 @@ def _materialize_rows(rows, ncols): def _scaling_gens(rows, nz): """Primitive integer generators of the scaling kernel over the nz weight columns.""" basis = exact_nullspace(rows, nz) if rows else [] - cvecs = [[v[j] for j in range(nz)] for v in basis - if any(v[j] != 0 for j in range(nz))] + cvecs = [[v[j] for j in range(nz)] for v in basis if any(v[j] != 0 for j in range(nz))] gens = [] if cvecs: red, _ = spy.Matrix(cvecs).rref() @@ -256,33 +257,31 @@ def verify_scalings(scalings, tapes, shifts=()): scaled coordinate) is translated, not scaled: it may occur only in the constant equation and value of itself.""" lines = [] for t in tapes: - lines += _as_list(t.get('model_lines', [])) + _as_list(t.get('obs_lines', [])) - lines += _as_list(t.get('ver_ic', [])) + _as_list(t.get('ver_rest', [])) - lines += ['_ = %s' % e['value'] for e in _as_list(t.get('ver_ev', [])) + - _as_list(t.get('ver_t0', []))] - if t.get('ver_time'): - lines.append('_ = %s' % t['ver_time']) + lines += _as_list(t.get("model_lines", [])) + _as_list(t.get("obs_lines", [])) + lines += _as_list(t.get("ver_ic", [])) + _as_list(t.get("ver_rest", [])) + lines += ["_ = %s" % e["value"] for e in _as_list(t.get("ver_ev", [])) + _as_list(t.get("ver_t0", []))] + if t.get("ver_time"): + lines.append("_ = %s" % t["ver_time"]) _, parse = _make_local_parse(lines) def split(line): - lhs, rhs = _clean(line).split('=', 1) + lhs, rhs = _clean(line).split("=", 1) return lhs.strip(), spy.sympify(parse(rhs)) - checks = [] # (expression, target: state name, None for 0) + checks = [] # (expression, target: state name, None for 0) for t in tapes: - for l in _as_list(t.get('model_lines', [])) + _as_list(t.get('ver_ic', [])) + \ - _as_list(t.get('ver_rest', [])): - if '=' in l: + for l in _as_list(t.get("model_lines", [])) + _as_list(t.get("ver_ic", [])) + _as_list(t.get("ver_rest", [])): + if "=" in l: x, e = split(l) checks.append((e, x)) - for l in _as_list(t.get('obs_lines', [])): - if '=' in l: + for l in _as_list(t.get("obs_lines", [])): + if "=" in l: checks.append((split(l)[1], None)) - for ev in _as_list(t.get('ver_ev', [])) + _as_list(t.get('ver_t0', [])): - e = spy.sympify(parse(str(ev['value']))) - checks.append((e, None if str(ev['method']) == 'multiply' else str(ev['var']))) - if t.get('ver_time'): - checks.append((spy.sympify(parse(t['ver_time'])), None)) + for ev in _as_list(t.get("ver_ev", [])) + _as_list(t.get("ver_t0", [])): + e = spy.sympify(parse(str(ev["value"]))) + checks.append((e, None if str(ev["method"]) == "multiply" else str(ev["var"]))) + if t.get("ver_time"): + checks.append((spy.sympify(parse(t["ver_time"])), None)) # each distinct check once, with the symbols of the check; one free of the support has degree 0 checks = list(dict.fromkeys(checks)) syms = [{str(x) for x in e.free_symbols} for e, _ in checks] @@ -296,7 +295,7 @@ def split(line): for (e, target), es in zip(checks, syms): if not ok: break - if e == 0: # zero has every weight + if e == 0: # zero has every weight continue if es & moved: if target in moved and e.is_Symbol and str(e) == target: @@ -307,8 +306,7 @@ def split(line): if d is None or spy.expand(d - (w.get(target, 0) if target else 0)) != 0: ok = False if state.env("LIEDIAG"): - print('[liediag] scaling fails at %s -> %s: degree %s' % - (target, str(e)[:120], d), flush=True) + print("[liediag] scaling fails at %s -> %s: degree %s" % (target, str(e)[:120], d), flush=True) break out.append(ok) return out @@ -319,9 +317,9 @@ def _scaling_nonid(gens, znames, nz): non_id = [] for c in gens: comp = {znames[j]: c[j] for j in range(nz) if c[j] != 0} - non_id.append({'support': sorted(comp.keys()), - 'vector': {k: str(v) for k, v in comp.items()}, - 'type': 'scaling'}) + non_id.append( + {"support": sorted(comp.keys()), "vector": {k: str(v) for k, v in comp.items()}, "type": "scaling"} + ) return non_id @@ -329,11 +327,11 @@ def _scaling_gens_recast(gens, znames, nz, recast): """Generators of span(gens) with c_E = exp * c_base imposed, weights possibly symbolic in exp.""" if not gens: return [] - G = spy.Matrix(gens) # rows = basis vectors, cols = coords + G = spy.Matrix(gens) # rows = basis vectors, cols = coords idx = {nm: j for j, nm in enumerate(znames)} rel_rows = [] for rc in recast: - E, base, exp = str(rc['E']), str(rc['base']), str(rc['exp']) + E, base, exp = str(rc["E"]), str(rc["base"]), str(rc["exp"]) if E not in idx or base not in idx: continue exp_sym = spy.sympify(exp) @@ -342,15 +340,14 @@ def _scaling_gens_recast(gens, znames, nz, recast): rel_rows.append([G[i, j_e] - exp_sym * G[i, j_b] for i in range(G.rows)]) if not rel_rows: return [[spy.Integer(x) for x in g] for g in gens] - alphas = spy.Matrix(rel_rows).nullspace() # over Q(exp) + alphas = spy.Matrix(rel_rows).nullspace() # over Q(exp) out = [] for a in alphas: - v = [spy.together(sum(a[i] * G[i, j] for i in range(G.rows))) - for j in range(nz)] + v = [spy.together(sum(a[i] * G[i, j] for i in range(G.rows))) for j in range(nz)] # L = log(base) shifts by c_base*log(lam) under the scaling; the kernel above # leaves it at 0, the joint nullspace contains the shift for rc in recast: - base, L = str(rc['base']), str(rc.get('L')) + base, L = str(rc["base"]), str(rc.get("L")) if base in idx and L in idx: v[idx[L]] = v[idx[base]] # clear denominators so the weights are polynomial in the exponents @@ -364,8 +361,9 @@ def _scaling_gens_recast(gens, znames, nz, recast): return out -def scaling_symmetries_per_condition(per_cond_model, per_cond_obs, inputs=None, fixed=None, - extra_model=None, extra_obs=None): +def scaling_symmetries_per_condition( + per_cond_model, per_cond_obs, inputs=None, fixed=None, extra_model=None, extra_obs=None +): """Scalings whose state weights may differ between conditions, as {'params': {name: w}, 'states': [{state: w}]} with one state dict per condition and integer weights. @@ -382,25 +380,25 @@ def scaling_symmetries_per_condition(per_cond_model, per_cond_obs, inputs=None, return [] inputset, fixedset = set(_as_list(inputs)), set(_as_list(fixed)) local, parse = _make_local_parse([l for ls in per_cond_model + per_cond_obs + extra_model + extra_obs for l in ls]) - state_names = [_clean(l).split('=', 1)[0].strip() for l in per_cond_model[0]] + state_names = [_clean(l).split("=", 1)[0].strip() for l in per_cond_model[0]] state_syms = [local.get(nm, spy.Symbol(nm)) for nm in state_names] m = len(state_syms) systems, paramset = [], set() for c in range(K): rhs = {} for l in per_cond_model[c]: - lhs, expr = _clean(l).split('=', 1) + lhs, expr = _clean(l).split("=", 1) rhs[lhs.strip()] = spy.sympify(parse(expr)) if set(rhs) != set(state_names): return [] f = [rhs[nm] for nm in state_names] - g = [spy.sympify(parse(_clean(l).split('=', 1)[1])) for l in per_cond_obs[c]] + g = [spy.sympify(parse(_clean(l).split("=", 1)[1])) for l in per_cond_obs[c]] xf = [] for l in extra_model[c]: - lhs, expr = _clean(l).split('=', 1) + lhs, expr = _clean(l).split("=", 1) if lhs.strip() in state_names: xf.append((state_names.index(lhs.strip()), spy.sympify(parse(expr)))) - xg = [spy.sympify(parse(_clean(l).split('=', 1)[1])) for l in extra_obs[c]] + xg = [spy.sympify(parse(_clean(l).split("=", 1)[1])) for l in extra_obs[c]] for e in f + g + [e for _, e in xf] + xg: paramset |= set(e.free_symbols) systems.append((f, g, xf, xg)) @@ -461,13 +459,26 @@ def scaling_symmetries_per_condition(per_cond_model, per_cond_obs, inputs=None, scale = spy.ilcm(scale, spy.Rational(x).q) if sts is None: continue - out.append({'params': {str(params[j]): int(pv[j] * scale) for j in range(npar) if pv[j] != 0}, - 'states': [{state_names[i]: int(s[i] * scale) for i in range(m) if s[i] != 0} for s in sts]}) + out.append( + { + "params": {str(params[j]): int(pv[j] * scale) for j in range(npar) if pv[j] != 0}, + "states": [{state_names[i]: int(s[i] * scale) for i in range(m) if s[i] != 0} for s in sts], + } + ) return out -def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=None, - recast=None, logs=False, extra_model=None, extra_obs=None, powers=False): +def scaling_symmetries_multi( + per_cond_model, + per_cond_obs, + inputs=None, + fixed=None, + recast=None, + logs=False, + extra_model=None, + extra_obs=None, + powers=False, +): """Scaling symmetries common to every condition; `inputs` and `fixed` do not scale. With `powers`, a power of a coordinate with a free exponent has the weight of the exponent times that of the coordinate.""" per_cond_model = [_as_list(m) for m in per_cond_model] @@ -478,24 +489,22 @@ def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=No fixedset = set(_as_list(fixed)) K = len(per_cond_model) if K == 0: - return {'method': 'scaling', 'count': 0, 'non_identifiable': [], - 'coordinates': []} + return {"method": "scaling", "count": 0, "non_identifiable": [], "coordinates": []} - all_lines = [l for lines in per_cond_model + per_cond_obs + extra_model + extra_obs - for l in lines] + all_lines = [l for lines in per_cond_model + per_cond_obs + extra_model + extra_obs for l in lines] local, parse = _make_local_parse(all_lines) - state_names = [_clean(l).split('=', 1)[0].strip() for l in per_cond_model[0]] + state_names = [_clean(l).split("=", 1)[0].strip() for l in per_cond_model[0]] state_syms = [local.get(nm, spy.Symbol(nm)) for nm in state_names] per_f, per_g, paramset = [], [], set() for c in range(K): rhs = {} for l in per_cond_model[c]: - lhs, expr = _clean(l).split('=', 1) + lhs, expr = _clean(l).split("=", 1) rhs[lhs.strip()] = spy.sympify(parse(expr)) f = [rhs[nm] for nm in state_names] - g = [spy.sympify(parse(_clean(l).split('=', 1)[1])) for l in per_cond_obs[c]] + g = [spy.sympify(parse(_clean(l).split("=", 1)[1])) for l in per_cond_obs[c]] per_f.append(f) per_g.append(g) for e in f + g: @@ -504,12 +513,12 @@ def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=No for c in range(K): xf = [] for l in extra_model[c]: - lhs, expr = _clean(l).split('=', 1) + lhs, expr = _clean(l).split("=", 1) if lhs.strip() in state_names: e = spy.sympify(parse(expr)) xf.append((state_names.index(lhs.strip()), e)) paramset |= set(e.free_symbols) - xg = [spy.sympify(parse(_clean(l).split('=', 1)[1])) for l in extra_obs[c]] + xg = [spy.sympify(parse(_clean(l).split("=", 1)[1])) for l in extra_obs[c]] for e in xg: paramset |= set(e.free_symbols) per_xf.append(xf) @@ -518,24 +527,32 @@ def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=No paramset -= set(state_syms) paramset -= {local.get(nm, spy.Symbol(nm)) for nm in inputset} recast = list(_as_list(recast)) - powers = _power_atoms([e for f in per_f + per_g + per_xg for e in f] + - [e for xf in per_xf for _, e in xf], set(state_syms), inputset | fixedset) if powers else {} + powers = ( + _power_atoms( + [e for f in per_f + per_g + per_xg for e in f] + [e for xf in per_xf for _, e in xf], + set(state_syms), + inputset | fixedset, + ) + if powers + else {} + ) if powers: + def sub(e): return e.xreplace(powers) if e.has(*powers) else e + per_f = [[sub(e) for e in f] for f in per_f] per_g = [[sub(e) for e in g] for g in per_g] per_xf = [[(i, sub(e)) for i, e in xf] for xf in per_xf] per_xg = [[sub(e) for e in xg] for xg in per_xg] paramset |= set(powers.values()) - recast += [{'E': str(P), 'base': str(at.base), 'exp': str(at.exp)} for at, P in powers.items()] + recast += [{"E": str(P), "base": str(at.base), "exp": str(at.exp)} for at, P in powers.items()] params = sorted(paramset, key=spy.default_sort_key) # re-add free-exponent bases the recast eliminated, so _scaling_gens_recast can # impose c_E = exp*c_base on them for rc in recast: - b = local.get(str(rc['base']), spy.Symbol(str(rc['base']))) - if (b not in set(state_syms) and b not in params - and str(b) not in inputset and str(b) not in fixedset): + b = local.get(str(rc["base"]), spy.Symbol(str(rc["base"]))) + if b not in set(state_syms) and b not in params and str(b) not in inputset and str(b) not in fixedset: params.append(b) params = sorted(params, key=spy.default_sort_key) zvars = state_syms + params @@ -567,8 +584,10 @@ def sub(e): rows.extend(sparse) skipped += sk if skipped and state.env("LIEDIAG"): - print('[liediag] scaling_symmetries_multi: %d non-polynomial term(s) skipped ' - '(a scaling they would forbid may be over-reported)' % skipped) + print( + "[liediag] scaling_symmetries_multi: %d non-polynomial term(s) skipped " + "(a scaling they would forbid may be over-reported)" % skipped + ) dense = _materialize_rows(rows, nz) # a coordinate in a free exponent does not scale: base^e is a monomial only for e invariant in_exp = {str(x) for at in powers for x in at.exp.free_symbols} @@ -588,8 +607,13 @@ def sub(e): aux = {str(P) for P in powers.values()} if aux: for d in non_id: - d['vector'] = {k: v for k, v in d['vector'].items() if k not in aux} - d['support'] = [k for k in d['support'] if k not in aux] - non_id = [d for d in non_id if d['vector']] - return {'method': 'scaling', 'count': len(non_id), 'non_identifiable': non_id, - 'coordinates': [z for z in znames if z not in aux], 'skipped': skipped} + d["vector"] = {k: v for k, v in d["vector"].items() if k not in aux} + d["support"] = [k for k in d["support"] if k not in aux] + non_id = [d for d in non_id if d["vector"]] + return { + "method": "scaling", + "count": len(non_id), + "non_identifiable": non_id, + "coordinates": [z for z in znames if z not in aux], + "skipped": skipped, + } diff --git a/src/symident/sym/shared.py b/src/symident/sym/shared.py index f92915c..068449a 100644 --- a/src/symident/sym/shared.py +++ b/src/symident/sym/shared.py @@ -14,8 +14,26 @@ _SYM = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") # the arrays the kernel reads of a single-segment tape -_KERNEL_KEYS = ("op", "a", "b", "cnum", "cden", "state_slots", "f_out", "g_out", "ic_leaf", "ic_num", "ic_den", - "ic_op", "ic_a", "ic_b", "ic_cnum", "ic_cden", "ic_out", "ic_seed") +_KERNEL_KEYS = ( + "op", + "a", + "b", + "cnum", + "cden", + "state_slots", + "f_out", + "g_out", + "ic_leaf", + "ic_num", + "ic_den", + "ic_op", + "ic_a", + "ic_b", + "ic_cnum", + "ic_cden", + "ic_out", + "ic_seed", +) _LINE_KEYS = ("model_lines", "obs_lines", "ver_ic", "jet_f", "jet_g", "jet_ic") @@ -53,6 +71,7 @@ def _node(self, e, ph): def symbols(self, val): """The symbols with `val`: placeholder -> Fraction or symbol name; None for an expression that vanishes.""" + def go(n): k = n[0] if k == "s": @@ -67,8 +86,11 @@ def go(n): if k == "c": return set() if k == "f": - return {val[x] if x in val and isinstance(val[x], str) else x for x in n[1] - if not (x in val and not isinstance(val[x], str))} + return { + val[x] if x in val and isinstance(val[x], str) else x + for x in n[1] + if not (x in val and not isinstance(val[x], str)) + } parts = [go(x) for x in n[1]] if k == "*": if any(p is None for p in parts): @@ -76,6 +98,7 @@ def go(n): return set().union(*parts) live = [p for p in parts if p is not None] return set().union(*live) if live else None + return go(self.tree) @@ -151,14 +174,24 @@ def shared_tape_compile(compile_fn, kw): if any(isinstance(v, str) and v in vals and vals[v][c] != v for v in pval[c].values()): return None t_subs = {k: (ph[k] if k in ph else _text(vals[k][0])) for k in keys} - t_obs = [_IDENT.sub(lambda m: ph.get(m.group(0), m.group(0)) if m.group(0) in obs_ids else m.group(0), line) - for line in obs[0]] - kw1 = dict(kw, condition_subs=[t_subs], condition_ic0=[dict(kw["condition_ic0"][0])], - condition_obs=[t_obs], observation=t_obs, - fixed=list(kw.get("fixed") or []) + sorted(ph.values()), - keep_coords=list(kw.get("keep_coords") or []) + value_syms, - seg_equilibrate=[False], condition_events=[[]], condition_t0_events=[[]], - condition_rest_subs=[{}], condition_times=None) + t_obs = [ + _IDENT.sub(lambda m: ph.get(m.group(0), m.group(0)) if m.group(0) in obs_ids else m.group(0), line) + for line in obs[0] + ] + kw1 = dict( + kw, + condition_subs=[t_subs], + condition_ic0=[dict(kw["condition_ic0"][0])], + condition_obs=[t_obs], + observation=t_obs, + fixed=list(kw.get("fixed") or []) + sorted(ph.values()), + keep_coords=list(kw.get("keep_coords") or []) + value_syms, + seg_equilibrate=[False], + condition_events=[[]], + condition_t0_events=[[]], + condition_rest_subs=[{}], + condition_times=None, + ) out = compile_fn(**kw1) if not out.get("ok") or len(out.get("tapes") or []) != 1: return None @@ -197,6 +230,7 @@ def shared_tape_compile(compile_fn, kw): def sub(lines): return [pat.sub(lambda m: txt[m.group(0)], str(x)) for x in lines] + for key in _LINE_KEYS: if tpl.get(key) is not None: t[key] = sub(tpl[key]) @@ -277,8 +311,9 @@ def _scaling_groups(tpl, pval): continue if not all(b.is_Symbol and e.is_Integer for b, e in pw.items()): return None - terms.append((ei, Fraction(int(c.p), int(c.q)) if c.is_Rational else None, - {str(b): int(e) for b, e in pw.items()})) + terms.append( + (ei, Fraction(int(c.p), int(c.q)) if c.is_Rational else None, {str(b): int(e) for b, e in pw.items()}) + ) if any(c is None for _, c, _ in terms): return None # the terms of every expression without placeholders, which a renamed term may meet @@ -292,6 +327,7 @@ def _scaling_groups(tpl, pval): def pattern(val): return tuple((nm, ("Z" if v == 0 else "N") if isinstance(v, Fraction) else v) for nm, v in sorted(val.items())) + meets = {} out, canon = {}, {} for c, val in enumerate(pval): @@ -323,14 +359,17 @@ def pattern(val): for b, e in terms[ti][2].items(): v = val.get(b) if isinstance(v, Fraction): - x *= v ** e + x *= v**e tot += x if tot == 0: vanish.append((gi, ())) key = (pat, tuple(vanish)) if key not in out: - canon[key] = val if meets[pat] else \ - {nm: (Fraction(1) if isinstance(v, Fraction) and v != 0 else v) for nm, v in val.items()} + canon[key] = ( + val + if meets[pat] + else {nm: (Fraction(1) if isinstance(v, Fraction) and v != 0 else v) for nm, v in val.items()} + ) out.setdefault(key, []).append(c) return list(out.values()), [canon[k] for k in out] @@ -366,12 +405,14 @@ def _reciprocals_free_of(tpl, base, nl, slots): def _template_exprs(tpl): """The right-hand sides, observables and initial values of the template as SymPy expressions, None where they do not parse.""" + def rhs(lines): out = {} for line in lines or []: x, e = str(line).split("=", 1) out[x.strip()] = spy.sympify(e) return out + try: f = rhs(tpl.get("jet_f") or tpl.get("model_lines")) g = [spy.sympify(str(x)) for x in tpl.get("jet_g") or []] @@ -410,7 +451,7 @@ def _reach(f_tr, g_tr, ic_tr, val): syms |= s if x in dist: for y in s: - if dist[x] < out.get(y, 10 ** 9): + if dist[x] < out.get(y, 10**9): out[y] = dist[x] return out, syms @@ -432,6 +473,13 @@ def kernel_tapes(tapes): first[key] = i out.append(t) continue - out.append({"base": j, "leaf_slot": t["leaf_slot"], "leaf_src": t["leaf_src"], "leaf_num": t["leaf_num"], - "leaf_den": t["leaf_den"]}) + out.append( + { + "base": j, + "leaf_slot": t["leaf_slot"], + "leaf_src": t["leaf_src"], + "leaf_num": t["leaf_num"], + "leaf_den": t["leaf_den"], + } + ) return out diff --git a/src/symident/sym/steady.py b/src/symident/sym/steady.py index ec582c8..de6af24 100644 --- a/src/symident/sym/steady.py +++ b/src/symident/sym/steady.py @@ -11,12 +11,12 @@ from .msolve import _solve_states_msolve from .parse import _as_list, _build_symbol_table, _clean, _function_aliases, _make_local_parse, _make_parse -_ss_modular_cache = {} +_ss_modular_cache: dict = {} # compiled t0 event value/derivative term lists keyed by the event tuple and the # parameter order -_event_compile_cache = {} +_event_compile_cache: dict = {} # test seam: force the per-point solve @@ -35,7 +35,7 @@ def _solve_states_fast(dps, solve_states, p, on_branch=None, accept=None): dps0 = dps dps = [dict(d) for d in dps] rem_idx = set(range(nv)) - elim = [] # (var_index, expr dict poly over remaining vars) + elim = [] # (var_index, expr dict poly over remaining vars) progress = True while progress and rem_idx: progress = False @@ -43,17 +43,18 @@ def _solve_states_fast(dps, solve_states, p, on_branch=None, accept=None): d = dps[eqi] if d is None or not d: continue - present = sorted((i for i in rem_idx if any(m[i] for m in d)), - key=lambda i: names[i]) # match the symbolic order + present = sorted( + (i for i in rem_idx if any(m[i] for m in d)), key=lambda i: names[i] + ) # match the symbolic order if not present: continue picked = None for i in present: - if max(m[i] for m in d) != 1: # degree in var i must be 1 + if max(m[i] for m in d) != 1: # degree in var i must be 1 continue c1 = 0 ok = True - for m in d: # coeff of var_i^1 must be const + for m in d: # coeff of var_i^1 must be const if m[i] == 1: if any(m[k] for k in range(nv) if k != i): ok = False @@ -62,7 +63,7 @@ def _solve_states_fast(dps, solve_states, p, on_branch=None, accept=None): if not ok or c1 % p == 0: continue inv = pow(c1 % p, p - 2, p) - c0 = {m: c for m, c in d.items() if m[i] == 0} # var_i^0 part + c0 = {m: c for m, c in d.items() if m[i] == 0} # var_i^0 part expr = {m: (c * (-inv)) % p for m, c in c0.items()} expr = {m: c for m, c in expr.items() if c} picked = (i, expr) @@ -87,7 +88,7 @@ def _solve_states_fast(dps, solve_states, p, on_branch=None, accept=None): return _solve_states_msolve(dps0, solve_states, p, on_branch, accept) val_by_id = {i: int(sol[solve_states[i]]) % p for i in coupled_idx} - for i, expr in reversed(elim): # resolve eliminated vars numerically, latest first + for i, expr in reversed(elim): # resolve eliminated vars numerically, latest first acc = 0 for m, c in expr.items(): t = c @@ -114,8 +115,9 @@ def branch_note(polys, states, at, p): _CONJUGATE[key] = _conjugate(polys, states, {k: v for k, v in at.items() if k not in set(states)}) conj = _CONJUGATE[key] if conj is True: - return head + ", all conjugate over Q(theta) (the eliminant is irreducible), so the one taken has the " \ - "rank of each" + return ( + head + ", all conjugate over Q(theta) (the eliminant is irreducible), so the one taken has the rank of each" + ) if conj is False: return head + ", the first is taken; the eliminant factors over Q at a point, the factor is not named" return head + ", the first is taken; the factor over Q is not determined" @@ -145,8 +147,13 @@ def pin_branch(model, state_names, param_names, forcings, held, at, p): if ses is None: return try: - c = _ss_compile(_as_list(model), _as_list(state_names), _as_list(param_names), set(_as_list(forcings)), - tuple(sorted(held or ()))) + c = _ss_compile( + _as_list(model), + _as_list(state_names), + _as_list(param_names), + set(_as_list(forcings)), + tuple(sorted(held or ())), + ) except SYMPY_FAILS as exc: sympy_fail(exc) return @@ -193,7 +200,7 @@ def _split_balances(polys, states): # per model, whether the interior resting roots are conjugate -_CONJUGATE = {} +_CONJUGATE: dict = {} def _conjugate(polys, states, pars): @@ -230,32 +237,42 @@ def _conjugate(polys, states, pars): def _compile_t0events(events, param_names): """Value and parameter-derivative term lists of each t0 event, keyed by event tuple and parameter order.""" - key = (tuple((str(e['var']), str(e['value']), str(e['method'])) for e in events), - tuple(param_names)) + key = (tuple((str(e["var"]), str(e["value"]), str(e["method"])) for e in events), tuple(param_names)) compiled = _event_compile_cache.get(key) if compiled is not None: return compiled param_syms = [spy.Symbol(nm) for nm in param_names] - eloc = _build_symbol_table([str(e['value']) for e in events] + list(param_names)) + eloc = _build_symbol_table([str(e["value"]) for e in events] + list(param_names)) eloc.update(_function_aliases()) eparse = _make_parse(eloc) compiled = [] for evt in events: - val = spy.sympify(eparse(str(evt['value']))) + val = spy.sympify(eparse(str(evt["value"]))) duals = {} for nm in param_names: d = spy.diff(val, spy.Symbol(nm)) duals[nm] = None if d == 0 else _poly_terms(d, param_syms) - compiled.append({'var': str(evt['var']), 'method': str(evt['method']), - 'val_t': _poly_terms(val, param_syms), 'duals': duals}) + compiled.append( + { + "var": str(evt["var"]), + "method": str(evt["method"]), + "val_t": _poly_terms(val, param_syms), + "duals": duals, + } + ) _event_compile_cache[key] = compiled return compiled def _ss_compile(model, state_names, param_names, forcings, held_state_names=(), linear=True): """Memoized prime-independent compile of f = 0 for the modular solve; `held_state_names` act as parameters.""" - key = (tuple(model), tuple(state_names), tuple(param_names), tuple(sorted(forcings)), - tuple(sorted(held_state_names))) + key = ( + tuple(model), + tuple(state_names), + tuple(param_names), + tuple(sorted(forcings)), + tuple(sorted(held_state_names)), + ) cached = _ss_modular_cache.get(key) if cached is not None: return cached @@ -265,22 +282,31 @@ def _ss_compile(model, state_names, param_names, forcings, held_state_names=(), _ss_base_cache[key] = base if not linear: return base - (param_syms, solve_states, polys, Jx, Jt, gens, jx_terms, jt_terms, poly_bi, _gl, _lt, - point_plan) = base + (param_syms, solve_states, polys, Jx, Jt, gens, jx_terms, jt_terms, poly_bi, _gl, _lt, point_plan) = base generic_linear, lin_terms = _compile_linear_plan(polys, solve_states, param_syms) if point_plan is not None: point_states, point_params, held_syms, point_poly_bi, keep_polys = point_plan - point_generic_linear, point_lin_terms = _compile_linear_plan( - keep_polys, point_states, point_params) - point_plan = (point_states, point_params, held_syms, point_poly_bi, - point_generic_linear, point_lin_terms) - cached = (param_syms, solve_states, polys, Jx, Jt, gens, jx_terms, jt_terms, - poly_bi, generic_linear, lin_terms, point_plan) + point_generic_linear, point_lin_terms = _compile_linear_plan(keep_polys, point_states, point_params) + point_plan = (point_states, point_params, held_syms, point_poly_bi, point_generic_linear, point_lin_terms) + cached = ( + param_syms, + solve_states, + polys, + Jx, + Jt, + gens, + jx_terms, + jt_terms, + poly_bi, + generic_linear, + lin_terms, + point_plan, + ) _ss_modular_cache[key] = cached return cached -_ss_base_cache = {} +_ss_base_cache: dict = {} def _ss_base(model, state_names, param_names, forcings, held_state_names): @@ -289,9 +315,9 @@ def _ss_base(model, state_names, param_names, forcings, held_state_names): rhs_by_name = {} for raw in model: line = _clean(raw) - if '=' not in line: + if "=" not in line: continue - lhs, rhs = line.split('=', 1) + lhs, rhs = line.split("=", 1) rhs_by_name[lhs.strip()] = parse(rhs) state_syms = [spy.Symbol(nm) for nm in state_names] param_syms = [spy.Symbol(nm) for nm in param_names] @@ -312,10 +338,8 @@ def _ss_base(model, state_names, param_names, forcings, held_state_names): for th in param_syms: if th in fs_sym[i]: Jt[str(th)][i] = spy.diff(fi, th) - jx_terms = [[_poly_terms(Jx[i, j], gens) for j in range(n_sc)] - for i in range(n_sc)] - jt_terms = {str(th): [_poly_terms(Jt[str(th)][i], gens) for i in range(n_sc)] - for th in param_syms} + jx_terms = [[_poly_terms(Jx[i, j], gens) for j in range(n_sc)] for i in range(n_sc)] + jt_terms = {str(th): [_poly_terms(Jt[str(th)][i], gens) for i in range(n_sc)] for th in param_syms} poly_bi = [_bipoly(pl, list(solve_states), list(param_syms)) for pl in polys] # held states are a moiety pivot set (detection.cq), so their own # equations are exactly the dependent rows of f = 0 @@ -328,11 +352,10 @@ def _ss_base(model, state_names, param_names, forcings, held_state_names): keep_polys = [polys[i] for i, s in enumerate(solve_states) if str(s) not in held_set] point_poly_bi = [_bipoly(pl, list(point_states), list(point_params)) for pl in keep_polys] point_plan = (point_states, point_params, held_syms, point_poly_bi, keep_polys) - return (param_syms, solve_states, polys, Jx, Jt, gens, jx_terms, jt_terms, - poly_bi, None, None, point_plan) + return (param_syms, solve_states, polys, Jx, Jt, gens, jx_terms, jt_terms, poly_bi, None, None, point_plan) -_NAMES = {} +_NAMES: dict = {} def _names(cached): @@ -348,22 +371,29 @@ def _names(cached): return hit[1] -def resting_kind(model, state_names, param_names, param_vals, prime, forcings=None, - held_states=None): +def resting_kind(model, state_names, param_names, param_vals, prime, forcings=None, held_states=None): """How the resting state depends on the parameters: "rational", "core" (solved by a resultant) or "msolve".""" state_names, param_names, p = _as_list(state_names), _as_list(param_names), int(prime) held_states = {str(k): int(v) % p for k, v in (held_states or {}).items()} - cached = _ss_compile(_as_list(model), state_names, param_names, set(_as_list(forcings)), - tuple(sorted(held_states.keys()))) + cached = _ss_compile( + _as_list(model), state_names, param_names, set(_as_list(forcings)), tuple(sorted(held_states.keys())) + ) param_syms, solve_states, poly_bi, generic_linear, point_plan = ( - cached[0], cached[1], cached[8], cached[9], cached[11]) + cached[0], + cached[1], + cached[8], + cached[9], + cached[11], + ) snm = _names(cached) if point_plan is not None: point_states, point_params, _, point_poly_bi, point_generic_linear = point_plan[:5] if point_generic_linear: return "rational" - vals = [(held_states[snm[th]] if snm[th] in held_states - else int(param_vals.get(snm[th], 0)) % p) for th in point_params] + vals = [ + (held_states[snm[th]] if snm[th] in held_states else int(param_vals.get(snm[th], 0)) % p) + for th in point_params + ] dps, nv = [_eval_bipoly_dict(b, vals, p) for b in point_poly_bi], len(point_states) else: if generic_linear: @@ -374,9 +404,19 @@ def resting_kind(model, state_names, param_names, param_vals, prime, forcings=No return "core" if red is not None and len(red[3]) <= 2 and len(red[2]) == len(red[3]) else "msolve" -def solve_steady_state_modular(model, state_names, param_names, param_vals, prime, - forcings=None, t0events=None, recast=None, l_vals=None, joint_mode=False, - held_states=None): +def solve_steady_state_modular( + model, + state_names, + param_names, + param_vals, + prime, + forcings=None, + t0events=None, + recast=None, + l_vals=None, + joint_mode=False, + held_states=None, +): """Point on the interior component of f = 0 over GF(prime) with the sensitivities of the point: {'ok', 'xstar', 'dx'}.""" model = _as_list(model) @@ -386,20 +426,21 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim p = int(prime) held_states = {str(k): int(v) % p for k, v in (held_states or {}).items()} - cached = _ss_compile(model, state_names, param_names, forcings, - tuple(sorted(held_states.keys()))) - (param_syms, solve_states, polys, _, _, _, jx_terms, jt_terms, poly_bi, - generic_linear, lin_terms, point_plan) = cached + cached = _ss_compile(model, state_names, param_names, forcings, tuple(sorted(held_states.keys()))) + (param_syms, solve_states, polys, _, _, _, jx_terms, jt_terms, poly_bi, generic_linear, lin_terms, point_plan) = ( + cached + ) snm = _names(cached) paramvals = [int(param_vals.get(snm[th], 0)) % p for th in param_syms] if point_plan is not None: # held pivot states act as parameters; solve the square reduced system - (point_states, point_params, _, point_poly_bi, - point_generic_linear, point_lin_terms) = point_plan - ppvals = [(held_states[snm[th]] if snm[th] in held_states - else int(param_vals.get(snm[th], 0)) % p) for th in point_params] + (point_states, point_params, _, point_poly_bi, point_generic_linear, point_lin_terms) = point_plan + ppvals = [ + (held_states[snm[th]] if snm[th] in held_states else int(param_vals.get(snm[th], 0)) % p) + for th in point_params + ] sub = None if point_generic_linear and not _SS_FORCE_POINT: sub = {} @@ -414,17 +455,19 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim hit = [] keep = tuple(pl for s, pl in zip(solve_states, polys) if snm[s] not in held_states) pars = dict(zip(point_params, ppvals)) - sub, fail = _solve_states_fast(dps, list(point_states), p, hit.append, - _pinned(keep, tuple(point_states), pars, p)) + sub, fail = _solve_states_fast( + dps, list(point_states), p, hit.append, _pinned(keep, tuple(point_states), pars, p) + ) if fail is not None: return fail if hit: - session.note("branches", branch_note(keep, tuple(point_states), - {**pars, **{s: int(sub[s]) for s in point_states}}, p)) + session.note( + "branches", + branch_note(keep, tuple(point_states), {**pars, **{s: int(sub[s]) for s in point_states}}, p), + ) sol = {} for s in solve_states: - sol[s] = (spy.Integer(held_states[snm[s]]) if snm[s] in held_states - else spy.Integer(int(sub[s]) % p)) + sol[s] = spy.Integer(held_states[snm[s]]) if snm[s] in held_states else spy.Integer(int(sub[s]) % p) else: # fast path: each state is a compiled rational function of the parameters, # evaluated in integer arithmetic; a vanishing pivot denominator mod p (None) @@ -442,24 +485,26 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim dps = [_eval_bipoly_dict(bip, paramvals, p) for bip in poly_bi] hit = [] pars = dict(zip(param_syms, paramvals)) - sol, fail = _solve_states_fast(dps, list(solve_states), p, hit.append, - _pinned(tuple(polys), tuple(solve_states), pars, p)) + sol, fail = _solve_states_fast( + dps, list(solve_states), p, hit.append, _pinned(tuple(polys), tuple(solve_states), pars, p) + ) if fail is not None: return fail if hit: - session.note("branches", branch_note(tuple(polys), tuple(solve_states), - {**pars, **{s: int(sol[s]) for s in solve_states}}, p)) + session.note( + "branches", + branch_note( + tuple(polys), tuple(solve_states), {**pars, **{s: int(sol[s]) for s in solve_states}}, p + ), + ) n_s = len(solve_states) val_by = {snm[s]: int(sol[s]) % p for s in solve_states} s_idx = {snm[s]: i for i, s in enumerate(solve_states)} # point in gens order (params then solve-states), already reduced mod p - ptvals = [int(param_vals.get(snm[th], 0)) % p for th in param_syms] + \ - [val_by[snm[s]] for s in solve_states] - jt_by = {snm[th]: [_eval_terms(jt_terms[snm[th]][i], ptvals, p) for i in range(n_s)] - for th in param_syms} - Jxeff = [[_eval_terms(jx_terms[i][j], ptvals, p) for j in range(n_s)] - for i in range(n_s)] + ptvals = [int(param_vals.get(snm[th], 0)) % p for th in param_syms] + [val_by[snm[s]] for s in solve_states] + jt_by = {snm[th]: [_eval_terms(jt_terms[snm[th]][i], ptvals, p) for i in range(n_s)] for th in param_syms} + Jxeff = [[_eval_terms(jx_terms[i][j], ptvals, p) for j in range(n_s)] for i in range(n_s)] # resting Jacobian df_rest for the joint determining system (tangency # df_rest . xi = 0 in uneliminated (x, theta) coordinates), snapshot before the @@ -474,8 +519,7 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim df_jt = {str(th): [jt_by[str(th)][i] for i in keep_idx] for th in param_syms} for hj in held_idx: df_jt[str(solve_states[hj])] = [Jxeff[i][hj] for i in keep_idx] - df_param_cols = [str(th) for th in param_syms] + \ - [str(solve_states[hj]) for hj in held_idx] + df_param_cols = [str(th) for th in param_syms] + [str(solve_states[hj]) for hj in held_idx] else: df_jx = [list(row) for row in Jxeff] df_jt = {nm: list(col) for nm, col in jt_by.items()} @@ -484,9 +528,15 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim if joint_mode: # joint mode needs only val_by and df_rest; a singular dual solve would reject a good point - return {'ok': True, 'state_names': list(state_names), 'val_by': dict(val_by), - 'df_jx': df_jx, 'df_jt': df_jt, 'df_state_cols': df_state_cols, - 'df_param_cols': df_param_cols} + return { + "ok": True, + "state_names": list(state_names), + "val_by": dict(val_by), + "df_jx": df_jx, + "df_jt": df_jt, + "df_state_cols": df_state_cols, + "df_param_cols": df_param_cols, + } # power/Hill recast: a normal entry holds E = base^exp generic, chain rule into base # and exponent; an inverted entry solves for E and takes the duals of base and @@ -495,8 +545,8 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim if recast: l_vals = l_vals or {} for rc in recast: - E, L, base, exp = rc['E'], rc['L'], rc['base'], rc['exp'] - inverted = bool(rc.get('inverted')) + E, L, base, exp = rc["E"], rc["L"], rc["base"], rc["exp"] + inverted = bool(rc.get("inverted")) E0 = val_by[E] if E in val_by else int(param_vals.get(E, 0)) % p L0 = int(l_vals.get(L, 0)) % p base0 = val_by[base] if base in val_by else int(param_vals.get(base, 0)) % p @@ -514,19 +564,27 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim jt_by[base] = [(jt_by[base][i] + j_e[i] * d_ebase) % p for i in range(n_s)] if exp in jt_by: jt_by[exp] = [(jt_by[exp][i] + j_e[i] * d_eexp) % p for i in range(n_s)] - recast_out.append({'E': E, 'L': L, 'base': base, 'exp': exp, - 'inverted': inverted, 'E0': E0, 'L0': L0, - 'base0': base0, 'expv': expv}) + recast_out.append( + { + "E": E, + "L": L, + "base": base, + "exp": exp, + "inverted": inverted, + "E0": E0, + "L0": L0, + "base0": base0, + "expv": expv, + } + ) # solve Jxeff * dx = -Jt for every parameter column at once over GF(p) params_l = [str(th) for th in param_syms] - B = [[(-jt_by[params_l[j]][i]) % p for j in range(len(params_l))] - for i in range(n_s)] + B = [[(-jt_by[params_l[j]][i]) % p for j in range(len(params_l))] for i in range(n_s)] X = _solve_mod(Jxeff, B, p) if X is None: - return {'ok': False, 'why': 'singular jacobian mod p'} - dx_by = {params_l[j]: [X[i][j] % p for i in range(n_s)] - for j in range(len(params_l))} + return {"ok": False, "why": "singular jacobian mod p"} + dx_by = {params_l[j]: [X[i][j] % p for i in range(n_s)] for j in range(len(params_l))} # assemble in the full state order; held states stay at 0 with no duals xstar = [val_by.get(nm, 0) for nm in state_names] @@ -539,11 +597,11 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim # partner (gen) and L: a normal entry derives them from dx[base], an inverted # one from dx[E]. gen is E for a normal entry and base for an inverted one. for rc in recast_out: - E, L, base, exp = rc['E'], rc['L'], rc['base'], rc['exp'] - E0, L0, base0, expv = rc['E0'], rc['L0'], rc['base0'], rc['expv'] + E, L, base, exp = rc["E"], rc["L"], rc["base"], rc["exp"] + E0, L0, base0, expv = rc["E0"], rc["L0"], rc["base0"], rc["expv"] g_d = {} l_d = {} - if not rc['inverted']: + if not rc["inverted"]: bi = s_idx.get(base) binv = pow(base0, p - 2, p) if base0 % p else 0 d_ebase = expv * E0 % p * binv % p @@ -552,20 +610,19 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim dxb = dx_by[nm][bi] if (bi is not None and nm in dx_by) else 0 g_d[nm] = (d_ebase * dxb + (d_eexp if nm == exp else 0)) % p l_d[nm] = binv * dxb % p - rc['gen'], rc['gen0'] = E, E0 + rc["gen"], rc["gen0"] = E, E0 else: ei = s_idx.get(E) xe = pow(expv, p - 2, p) if expv % p else 0 einv = pow(E0, p - 2, p) if E0 % p else 0 for nm in param_names: d_e = dx_by[nm][ei] if (ei is not None and nm in dx_by) else 0 - g_d[nm] = (base0 * xe % p * einv % p * d_e - - (base0 * L0 % p * xe if nm == exp else 0)) % p + g_d[nm] = (base0 * xe % p * einv % p * d_e - (base0 * L0 % p * xe if nm == exp else 0)) % p l_d[nm] = (xe * einv % p * d_e - (L0 * xe if nm == exp else 0)) % p - rc['gen'], rc['gen0'] = base, base0 - rc['gen_dual'] = g_d - rc['l_dual'] = l_d - for k in ('E', 'base', 'exp', 'E0', 'base0', 'expv'): + rc["gen"], rc["gen0"] = base, base0 + rc["gen_dual"] = g_d + rc["l_dual"] = l_d + for k in ("E", "base", "exp", "E0", "base0", "expv"): rc.pop(k, None) # compose the t0 events onto the seed (value mod p and parameter-duals) @@ -573,30 +630,39 @@ def solve_steady_state_modular(model, state_names, param_names, param_vals, prim if events: idx_of_state = {nm: i for i, nm in enumerate(state_names)} for evt in _compile_t0events(events, list(param_names)): - X = evt['var'] + X = evt["var"] if X not in idx_of_state: continue i = idx_of_state[X] - v0 = _eval_terms(evt['val_t'], paramvals, p) - vdu = {nm: (_eval_terms(evt['duals'][nm], paramvals, p) - if evt['duals'][nm] is not None else 0) - for nm in param_names} - meth = evt['method'] - if meth == 'replace': + v0 = _eval_terms(evt["val_t"], paramvals, p) + vdu = { + nm: (_eval_terms(evt["duals"][nm], paramvals, p) if evt["duals"][nm] is not None else 0) + for nm in param_names + } + meth = evt["method"] + if meth == "replace": xstar[i] = v0 for nm in param_names: dx[nm][i] = vdu[nm] - elif meth == 'add': + elif meth == "add": xstar[i] = (xstar[i] + v0) % p for nm in param_names: dx[nm][i] = (dx[nm][i] + vdu[nm]) % p - elif meth == 'multiply': + elif meth == "multiply": old = xstar[i] oldd = {nm: dx[nm][i] for nm in param_names} xstar[i] = old * v0 % p for nm in param_names: dx[nm][i] = (old * vdu[nm] + v0 * oldd[nm]) % p - return {'ok': True, 'xstar': xstar, 'dx': dx, 'state_names': list(state_names), - 'recast': recast_out, - 'df_jx': df_jx, 'df_jt': df_jt, 'df_state_cols': df_state_cols, - 'df_param_cols': df_param_cols, 'val_by': dict(val_by)} + return { + "ok": True, + "xstar": xstar, + "dx": dx, + "state_names": list(state_names), + "recast": recast_out, + "df_jx": df_jx, + "df_jt": df_jt, + "df_state_cols": df_state_cols, + "df_param_cols": df_param_cols, + "val_by": dict(val_by), + } diff --git a/src/symident/sym/supportlift.py b/src/symident/sym/supportlift.py index 9484c8d..2fbdbc9 100644 --- a/src/symident/sym/supportlift.py +++ b/src/symident/sym/supportlift.py @@ -102,8 +102,11 @@ def _ansatz(S, reads, readers, level): ms += [((j, 1),) for j in near] if level >= 2: nb = [i] + near - ms += [((a, 2),) if a == b else tuple(sorted(((a, 1), (b, 1)), key=lambda t: str(t[0]))) - for k, a in enumerate(nb) for b in nb[k:]] + ms += [ + ((a, 2),) if a == b else tuple(sorted(((a, 1), (b, 1)), key=lambda t: str(t[0]))) + for k, a in enumerate(nb) + for b in nb[k:] + ] out[i] = list(dict.fromkeys(ms)) return out @@ -175,6 +178,7 @@ def flux(m): for j, e in m: r = (r + e * V(self.F[j]) % p * mono(m) % p * _inverse(V(j), p)) % p return r + out = [] for ident in self.identities(S): kind, l, f, ins = ident @@ -207,8 +211,13 @@ def solve(self, S, mons, p, seed): unknowns = [(i, m) for i in sorted(S, key=str) for m in mons[i]] cols = {u: k for k, u in enumerate(unknowns)} U = len(unknowns) - width = max((sum(len(mons[i]) for i in ins) + (len(mons[l]) if kind == "F" and l in S else 0) - for kind, l, _, ins in self.identities(S)), default=0) + width = max( + ( + sum(len(mons[i]) for i in ins) + (len(mons[l]) if kind == "F" and l in S else 0) + for kind, l, _, ins in self.identities(S) + ), + default=0, + ) V = _Residues(set(self.F), width + _EXTRA_POINTS, p, seed) blocks = [] for ident, block, b in self.rows(S, mons, cols, V): @@ -222,13 +231,13 @@ def solve(self, S, mons, p, seed): if not rr["rank"]: continue G = np.zeros((rr["rank"], U + 1), dtype=np.int64) - G[:, ks] = rr["R"][:rr["rank"], :-1] - G[:, U] = rr["R"][:rr["rank"], -1] + G[:, ks] = rr["R"][: rr["rank"], :-1] + G[:, U] = rr["R"][: rr["rank"], -1] blocks.append(G) if not blocks: return {}, V rr = rref_modp(np.concatenate(blocks, axis=0), p) - piv = [int(c) for c in rr["piv"][:rr["rank"]]] + piv = [int(c) for c in rr["piv"][: rr["rank"]]] if U in piv: return None, V return {unknowns[c]: int(rr["R"][r, U]) % p for r, c in enumerate(piv) if int(rr["R"][r, U]) % p}, V @@ -264,8 +273,7 @@ def exact(self, S, mons, sol, V1): out = {} for u in keys: k3 = second[u] * pow(a3, -1, p2) % p2 - q = _rational_reconstruct((k1[u] + p1 * ((k3 - k1[u]) * pow(p1, -1, p2) % p2)) % (p1 * p2), - p1 * p2) + q = _rational_reconstruct((k1[u] + p1 * ((k3 - k1[u]) * pow(p1, -1, p2) % p2)) % (p1 * p2), p1 * p2) if q is None: break out[u] = q * c @@ -312,7 +320,7 @@ def _entry(self, ident, u, sub): i, m = u if kind == "x0": return self._at_x0(m) if l == i else spy.Integer(0) - mono = spy.Mul(*[j ** e for j, e in m]) + mono = spy.Mul(*[j**e for j, e in m]) e = self.d(f, i) * mono if i in f.free_symbols else spy.Integer(0) if kind == "F" and l == i and m: e -= sum((self.F[j] * spy.diff(mono, j) for j, _ in m), spy.Integer(0)) @@ -341,8 +349,13 @@ def support_lift(field, regime, ic_lines, states): except SYMPY_FAILS as exc: sympy_fail(exc) return None - if not F or not theta or set(theta) & set(F) or any(v.free_symbols & set(F) for v in theta.values()) \ - or any(e.free_symbols & set(F) for e in x0.values()): + if ( + not F + or not theta + or set(theta) & set(F) + or any(v.free_symbols & set(F) for v in theta.values()) + or any(e.free_symbols & set(F) for e in x0.values()) + ): return None pb = _Problem(theta, F, obs, x0) S = {x for x in F if pb.reads[x] & pb.moved or (x in x0 and x0[x].free_symbols & pb.moved)} @@ -373,7 +386,7 @@ def _lifted(field, vals): """`field` with the state components sum c m of the solution {(state, monomial): c}.""" comp = {} for (i, m), c in vals.items(): - comp[i] = comp.get(i, spy.Integer(0)) + c * spy.Mul(*[j ** e for j, e in m]) + comp[i] = comp.get(i, spy.Integer(0)) + c * spy.Mul(*[j**e for j, e in m]) out = dict(field) for i, e in comp.items(): if e != 0: diff --git a/src/symident/sym/switching.py b/src/symident/sym/switching.py index 5d6c1d6..0bf0ad2 100644 --- a/src/symident/sym/switching.py +++ b/src/symident/sym/switching.py @@ -12,8 +12,23 @@ _SWITCHY = re.compile(r"\b(piecewise|ifelse|Heaviside|max|min|pmax|pmin)\s*\(|[<>!&|=]") _SIGNY = re.compile(r"\b(abs|sign)\s*\(") -_BIN = {"||": 1, "|": 1, "&&": 2, "&": 2, "<": 4, ">": 4, "<=": 4, ">=": 4, "==": 4, "!=": 4, - "+": 5, "-": 5, "*": 6, "/": 6, "^": 8} +_BIN = { + "||": 1, + "|": 1, + "&&": 2, + "&": 2, + "<": 4, + ">": 4, + "<=": 4, + ">=": 4, + "==": 4, + "!=": 4, + "+": 5, + "-": 5, + "*": 6, + "/": 6, + "^": 8, +} TIME = spy.Symbol("time") # pi and Euler's number in a model with switches, as fixed symbols CONSTS = {spy.pi: spy.Symbol("si_pi"), spy.E: spy.Symbol("si_e")} @@ -68,16 +83,14 @@ def __init__(self, positive, namer=None, states=()): def is_pos(self, name): """Whether the coordinate `name` is declared positive.""" - return self.positive is True or (self.positive not in (False, None) and - name in self.positive) + return self.positive is True or (self.positive not in (False, None) and name in self.positive) def _assume(self, e): rep = {} for s in e.free_symbols: if s in self.ind: continue - rep[s] = spy.Dummy(s.name, positive=True) if self.is_pos(s.name) else \ - spy.Dummy(s.name, real=True) + rep[s] = spy.Dummy(s.name, positive=True) if self.is_pos(s.name) else spy.Dummy(s.name, real=True) return e.xreplace(rep) def sign_of(self, e): @@ -145,8 +158,7 @@ def indicator(self, e): """The indicator of e > 0 in the H_j; the boundary e = 0 has measure zero.""" e = spy.sympify(e) if e.free_symbols & set(self.ind): - raise InapplicableError(f"a condition on a switched expression ({to_str(e)}) is not " - "supported") + raise InapplicableError(f"a condition on a switched expression ({to_str(e)}) is not supported") s = self.sign_of(e) if s is not None: if self.positive is True and {str(x) for x in e.free_symbols} & self.states: @@ -184,8 +196,7 @@ def binary(self, op, a, b): # unless a - b vanishes identically, equality holds on a set of measure zero eq = spy.Integer(1 if self.sign_of(a - b) == 0 else 0) return _Bool(eq if op == "==" else 1 - eq) - return {"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b, - "/": lambda: a / b, "^": lambda: a ** b}[op]() + return {"+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b, "/": lambda: a / b, "^": lambda: a**b}[op]() def _extreme(self, args, sign): args = [_val(a) for a in args] @@ -371,28 +382,38 @@ def namer(k): nm += "_" used.add(nm) return nm + sw = Switches(pos, namer, states=f) F = {k: sw.parse(v) for k, v in f.items()} Gs = [{k: sw.parse(v) for k, v in x.items()} for x in gl] if sw.by_default: - warnings.warn("the default positive=True decides the sign of " + ", ".join(dict.fromkeys(sw.by_default)) + - ", which holds a state, and removes the switch; pass `positive` without that state to keep " - "the switch", stacklevel=4) + warnings.warn( + "the default positive=True decides the sign of " + + ", ".join(dict.fromkeys(sw.by_default)) + + ", which holds a state, and removes the switch; pass `positive` without that state to keep " + "the switch", + stacklevel=4, + ) root_of = [] for e in roots: h = sw.indicator(sw.parse(str(e["root"]))) hit = [j for j, s in enumerate(sw.ind) if s in h.free_symbols] - single = len(hit) == 1 and (spy.expand(h - sw.ind[hit[0]]) == 0 or - spy.expand(h - 1 + sw.ind[hit[0]]) == 0) + single = len(hit) == 1 and (spy.expand(h - sw.ind[hit[0]]) == 0 or spy.expand(h - 1 + sw.ind[hit[0]]) == 0) if not single: - raise InapplicableError(f"the root {e['root']} of an event is not one switching surface; " - "give the event a root that changes sign on a single surface") + raise InapplicableError( + f"the root {e['root']} of an event is not one switching surface; " + "give the event a root that changes sign on a single surface" + ) root_of.append({"event": e, "surface": hit[0]}) if not sw.funcs: if any(_SWITCHY.search(str(e)) for e in exprs): - return {"hybrid": False, "f": {k: to_str(v) for k, v in F.items()}, - "g": [{k: to_str(v) for k, v in x.items()} or None for x in Gs] - if obs_list else ({k: to_str(v) for k, v in Gs[0].items()} or None)} + return { + "hybrid": False, + "f": {k: to_str(v) for k, v in F.items()}, + "g": [{k: to_str(v) for k, v in x.items()} or None for x in Gs] + if obs_list + else ({k: to_str(v) for k, v in Gs[0].items()} or None), + } return None sw.consts = CONSTS sw.funcs = [q.xreplace(CONSTS) for q in sw.funcs] diff --git a/src/symident/sym/symbolic.py b/src/symident/sym/symbolic.py index cd33f62..7379e0f 100644 --- a/src/symident/sym/symbolic.py +++ b/src/symident/sym/symbolic.py @@ -12,20 +12,33 @@ def _lie_deriv(h, states, rhs): return sum(spy.diff(h, states[i]) * rhs[i] for i in range(len(states))) -def observability_sympy_multi(model, observation, condition_subs=None, condition_ic0=None, - fixed=None, parameters=None, condition_obs=None, condition_rest_subs=None): +def observability_sympy_multi( + model, + observation, + condition_subs=None, + condition_ic0=None, + fixed=None, + parameters=None, + condition_obs=None, + condition_rest_subs=None, +): """Pure-symbolic multi-condition observability, the exact cross-check of the modular multi-condition engine.""" + def as_l(v): return list(v) if isinstance(v, (list, tuple)) else ([] if v is None else [v]) + model = [str(l) for l in as_l(model)] observation = [str(l) for l in as_l(observation)] condition_subs = [dict(c) for c in as_l(condition_subs)] or [{}] condition_ic0 = [dict(c) for c in as_l(condition_ic0)] K = len(condition_subs) condition_obs = list(condition_obs) if condition_obs else [] - obs_per_cond = [[str(l) for l in as_l(condition_obs[c])] - if (c < len(condition_obs) and condition_obs[c] is not None) - else observation for c in range(K)] + obs_per_cond = [ + [str(l) for l in as_l(condition_obs[c])] + if (c < len(condition_obs) and condition_obs[c] is not None) + else observation + for c in range(K) + ] all_lines = model + observation + as_l(parameters) for o in obs_per_cond: @@ -37,15 +50,13 @@ def as_l(v): variables, diff_equations, _ = _read_equations(model, parse) obs_fun_per = [_read_equations(o, parse)[1] for o in obs_per_cond] - fixed_names = set(str(s) for s in - [local.get(nm, spy.Symbol(nm)) for nm in as_l(fixed)]) + fixed_names = set(str(s) for s in [local.get(nm, spy.Symbol(nm)) for nm in as_l(fixed)]) # constant (u' = 0) states are dropped; their per-condition value is baked # into condition_subs, so they enter f/g as substituted constants is_const = [spy.sympify(e) == 0 for e in diff_equations] S = [variables[i] for i in range(len(variables)) if not is_const[i]] - Srhs = [spy.sympify(diff_equations[i]) for i in range(len(variables)) - if not is_const[i]] + Srhs = [spy.sympify(diff_equations[i]) for i in range(len(variables)) if not is_const[i]] def pval(s): return spy.sympify(parse(str(s))) @@ -53,8 +64,7 @@ def pval(s): # per-condition substituted dynamics/observation and initial state per_cond = [] for c in range(K): - subs_map = {local.get(str(k), spy.Symbol(str(k))): pval(v) - for k, v in condition_subs[c].items()} + subs_map = {local.get(str(k), spy.Symbol(str(k))): pval(v) for k, v in condition_subs[c].items()} ic0 = condition_ic0[c] if c < len(condition_ic0) else {} f_c = [e.subs(subs_map) for e in Srhs] g_c = [spy.sympify(e).subs(subs_map) for e in obs_fun_per[c]] @@ -70,22 +80,27 @@ def pval(s): # a state is a free coordinate iff the state symbol survives in the initial value in # some condition; parameters are all remaining free symbols; both minus `fixed` - free_states = [X for X in S - if any(X in ic_c[X].free_symbols for (_, _, ic_c) in per_cond)] + free_states = [X for X in S if any(X in ic_c[X].free_symbols for (_, _, ic_c) in per_cond)] paramset = set() - for (f_c, g_c, ic_c) in per_cond: + for f_c, g_c, ic_c in per_cond: for e in list(f_c) + list(g_c) + list(ic_c.values()): paramset |= set(spy.sympify(e).free_symbols) paramset -= set(S) params = sorted(paramset, key=spy.default_sort_key) - z = [X for X in free_states if str(X) not in fixed_names] + \ - [s for s in params if str(s) not in fixed_names] + z = [X for X in free_states if str(X) not in fixed_names] + [s for s in params if str(s) not in fixed_names] znames = [str(s) for s in z] nz = len(z) if nz == 0: - return {'ok': True, 'rank': 0, 'dim': 0, 'lie_order': 0, - 'non_identifiable': [], 'identifiable': True, 'coordinates': []} + return { + "ok": True, + "rank": 0, + "dim": 0, + "lie_order": 0, + "non_identifiable": [], + "identifiable": True, + "coordinates": [], + } # per Lie order, each condition's rows d/dz[L_{f_c}^order g_c at ic_c]; stop at # full rank or after two orders without rank gain, counted only past the @@ -94,7 +109,7 @@ def pval(s): first_ord = [min([r[nm] for r in reach_per if nm in r] or [-1]) for nm in znames] lo0 = max([k for k in first_ord if k >= 0] or [0]) rows = [] - jets = [list(g_c) for (f_c, g_c, ic_c) in per_cond] # order 0: the observables + jets = [list(g_c) for (f_c, g_c, ic_c) in per_cond] # order 0: the observables def next_order(): for ci, (f_c, _g_c, _ic_c) in enumerate(per_cond): @@ -103,8 +118,9 @@ def next_order(): def add_rows(): for ci, (_f_c, _g_c, ic_c) in enumerate(per_cond): for h in jets[ci]: - he = spy.sympify(h).subs(ic_c) # evaluate at x(0) = ic_c + he = spy.sympify(h).subs(ic_c) # evaluate at x(0) = ic_c rows.append([spy.diff(he, zj) for zj in z]) + prev, flat, order = -1, 0, 0 while True: add_rows() @@ -135,17 +151,36 @@ def add_rows(): v = [spy.cancel(vec[i]) for i in range(nz)] vecs.append(v) nz_i = [i for i in range(nz) if v[i] != 0] - non_id.append({'support': sorted(znames[i] for i in nz_i), - 'vector': {znames[i]: str(v[i]) for i in nz_i}, - 'type': 'general', 'closed_form': True}) - out = {'ok': True, 'rank': int(rank), 'dim': int(nz), 'lie_order': int(order), - 'non_identifiable': non_id, 'identifiable': bool(rank >= nz), 'coordinates': znames, - 'lie_certified': cert["order"] is not None or rank >= nz, 'lie_certificate': cert["why"]} + non_id.append( + { + "support": sorted(znames[i] for i in nz_i), + "vector": {znames[i]: str(v[i]) for i in nz_i}, + "type": "general", + "closed_form": True, + } + ) + out = { + "ok": True, + "rank": int(rank), + "dim": int(nz), + "lie_order": int(order), + "non_identifiable": non_id, + "identifiable": bool(rank >= nz), + "coordinates": znames, + "lie_certified": cert["order"] is not None or rank >= nz, + "lie_certificate": cert["why"], + } # with the order certified, a vector that annihilates the rows identically is a symmetry if cert["order"] is not None and non_id and kernel_exact(rows, vecs, z): for d in non_id: - d['exact'] = True - out['rank_proven'], out['rank_proof'] = len(non_id), "Lie order proven sufficient, exact kernel" - out['systems'] = [([f"{X} = {e}" for X, e in zip(S, f_c)], [f"_y{i} = {e}" for i, e in enumerate(g_c)], - [f"{X} = {ic_c[X]}" for X in S]) for (f_c, g_c, ic_c) in per_cond] + d["exact"] = True + out["rank_proven"], out["rank_proof"] = len(non_id), "Lie order proven sufficient, exact kernel" + out["systems"] = [ + ( + [f"{X} = {e}" for X, e in zip(S, f_c)], + [f"_y{i} = {e}" for i, e in enumerate(g_c)], + [f"{X} = {ic_c[X]}" for X in S], + ) + for (f_c, g_c, ic_c) in per_cond + ] return out diff --git a/src/symident/sym/tape.py b/src/symident/sym/tape.py index b150b4f..ac1df2d 100644 --- a/src/symident/sym/tape.py +++ b/src/symident/sym/tape.py @@ -56,6 +56,7 @@ class StartPow(spy.Function): """base^n of a state that starts at 0, which the kernel expands in t and (c t^k)^n.""" + nargs = 2 @@ -64,7 +65,7 @@ def _start_powers(per_cond, S, fixed_names, blocked): base^c0 * StartPow(base, n)^c, and None; or (None, why) where such a power is not supported.""" states = {str(X) for X in S} exps, at_zero, at_other = {}, set(), set() - for (f_c, g_c, ic_c, _f_ss) in per_cond: + for f_c, g_c, ic_c, _f_ss in per_cond: for e in list(f_c) + list(g_c): for pw in spy.sympify(e).atoms(spy.Pow): if pw.exp.is_number or not pw.base.is_Symbol or str(pw.base) not in states: @@ -80,26 +81,34 @@ def _start_powers(per_cond, S, fixed_names, blocked): return per_cond, None mixed = sorted(at_zero & at_other) if mixed: - return None, ('the state %s starts at 0 in one condition and not in another, and a free power of it ' - 'is expanded differently at a start of 0; analyze the conditions separately' % mixed[0]) + return None, ( + "the state %s starts at 0 in one condition and not in another, and a free power of it " + "is expanded differently at a start of 0; analyze the conditions separately" % mixed[0] + ) sym_of, owner = {}, {} for b in sorted(at_zero): ns = set() for ex in exps[b]: cn = _power_exponent(ex) if cn is None or not (cn[0].is_Integer and cn[0] >= 0 and cn[1].is_Integer and cn[1] > 0): - return None, ('the power %s^(%s) of a state that starts at 0 is supported as %s^(c0 + c*n) with ' - 'integers c0 >= 0, c > 0 and a parameter n' % (b, ex, b)) + return None, ( + "the power %s^(%s) of a state that starts at 0 is supported as %s^(c0 + c*n) with " + "integers c0 >= 0, c > 0 and a parameter n" % (b, ex, b) + ) ns.add(cn[2]) if len(ns) > 1: - return None, 'the state %s starts at 0 and has powers with several free exponents' % b + return None, "the state %s starts at 0 and has powers with several free exponents" % b n = ns.pop() if str(n) in fixed_names or str(n) in states: - return None, ('the exponent %s of the state %s, which starts at 0, must be a coordinate, ' - 'not a fixed value or a state' % (n, b)) + return None, ( + "the exponent %s of the state %s, which starts at 0, must be a coordinate, " + "not a fixed value or a state" % (n, b) + ) if n in owner: - return None, ('the free exponent %s is the exponent of %s and %s, which both start at 0; ' - 'their powers are not independent functions of t' % (n, owner[n], b)) + return None, ( + "the free exponent %s is the exponent of %s and %s, which both start at 0; " + "their powers are not independent functions of t" % (n, owner[n], b) + ) owner[n] = b sym_of[b] = n @@ -108,10 +117,14 @@ def repl(pw): if pw.exp.is_number or str(pw.base) not in sym_of: return pw c0, c, n = _power_exponent(pw.exp) - return pw.base ** c0 * StartPow(pw.base, n) ** c + return pw.base**c0 * StartPow(pw.base, n) ** c + return spy.sympify(e).replace(lambda x: x.is_Pow, repl) - return [([sub(e) for e in f_c], [sub(e) for e in g_c], ic_c, [sub(e) for e in f_ss]) - for (f_c, g_c, ic_c, f_ss) in per_cond], None + + return [ + ([sub(e) for e in f_c], [sub(e) for e in g_c], ic_c, [sub(e) for e in f_ss]) + for (f_c, g_c, ic_c, f_ss) in per_cond + ], None def _emit_tape_shared(fexpr, gexpr, slot_of, base, allow_sqrt=False): @@ -209,16 +222,16 @@ def _compose_t0_events(ic_map, t0evs, pval, subs_map): """Apply a segment's t0 events in place: x0 = E(x_ss), f = 0 stays on x_ss, values see the pre-event states.""" pre = dict(ic_map) for e in t0evs or []: - Xv = spy.Symbol(str(e['var'])) + Xv = spy.Symbol(str(e["var"])) if Xv not in ic_map: continue - val = spy.sympify(pval(e['value'])).subs(subs_map).xreplace(pre) - meth = str(e['method']) - if meth == 'replace': + val = spy.sympify(pval(e["value"])).subs(subs_map).xreplace(pre) + meth = str(e["method"]) + if meth == "replace": ic_map[Xv] = val - elif meth == 'add': + elif meth == "add": ic_map[Xv] = ic_map[Xv] + val - elif meth == 'multiply': + elif meth == "multiply": ic_map[Xv] = ic_map[Xv] * val return ic_map @@ -226,6 +239,7 @@ def _compose_t0_events(ic_map, t0evs, pval, subs_map): def _lie_reach(f_c, g_c, S, ic_c, evs, f_ss=None): """{name: order}: structural first Lie order at which each symbol can enter one segment's output jets.""" import collections + Sstr = [str(X) for X in S] rhs = {} for i, X in enumerate(Sstr): @@ -250,7 +264,7 @@ def _lie_reach(f_c, g_c, S, ic_c, evs, f_ss=None): out = dict(dist) def lower(name, k): - if k < out.get(name, 10 ** 9): + if k < out.get(name, 10**9): out[name] = k for X, e in dict(ic_c).items(): @@ -258,9 +272,9 @@ def lower(name, k): for s in spy.sympify(e).free_symbols: lower(str(s), dist[str(X)]) for ev in evs or []: - X = str(ev['var']) + X = str(ev["var"]) if X in dist: - for s in spy.sympify(ev['value']).free_symbols: + for s in spy.sympify(ev["value"]).free_symbols: lower(str(s), dist[X]) if f_ss is not None: reached = [dist[X] for X in Sstr if X in dist] @@ -272,7 +286,6 @@ def lower(name, k): return out - def _distinct(exprs): """The expressions without repetitions, in their order.""" seen_id, seen = set(), set() @@ -301,34 +314,43 @@ def f(x): if v is None: v = memo[x] = str(x) return v + return f def _zero_powers(e, positive): """0^n replaced by 0 where the exponent n is positive on the declared domain.""" + def pos(x): - sub = {v: spy.Symbol(str(v), positive=True) for v in x.free_symbols - if positive is True or str(v) in set(positive or ())} + sub = { + v: spy.Symbol(str(v), positive=True) + for v in x.free_symbols + if positive is True or str(v) in set(positive or ()) + } return bool(x.xreplace(sub).is_positive) + e = spy.sympify(e) if not any(p.base == 0 for p in e.atoms(spy.Pow)): return e - return e.replace(lambda x: x.is_Pow and x.base == 0 and not x.exp.is_number and pos(x.exp), - lambda x: spy.Integer(0)) + return e.replace( + lambda x: x.is_Pow and x.base == 0 and not x.exp.is_number and pos(x.exp), lambda x: spy.Integer(0) + ) def _unmarked(e, S): """`e` with every pre_state() symbol as the state of S it stands for.""" sym_of = {str(x): x for x in S} - return e.xreplace({x: sym_of.get(nm, spy.Symbol(nm)) for x in e.free_symbols - if (nm := pre_state_name(x)) is not None}) + return e.xreplace( + {x: sym_of.get(nm, spy.Symbol(nm)) for x in e.free_symbols if (nm := pre_state_name(x)) is not None} + ) def _reads_states(e, S): """Whether e holds exp(), log() or a non-integer power of an expression in the states S.""" e, states = spy.sympify(e), set(S) - return any(a.free_symbols & states for a in e.atoms(spy.exp, spy.log, spy.Pow) - if not (a.is_Pow and a.exp.is_Integer)) + return any( + a.free_symbols & states for a in e.atoms(spy.exp, spy.log, spy.Pow) if not (a.is_Pow and a.exp.is_Integer) + ) def _power_events(ev_per, power_recast, S): @@ -339,40 +361,77 @@ def _power_events(ev_per, power_recast, S): evs = list(evs) bases = {} for e in evs: - b = sym_of.get(str(e['var']), spy.Symbol(str(e['var']))) + b = sym_of.get(str(e["var"]), spy.Symbol(str(e["var"]))) cur = bases.get(b, b) - v = spy.sympify(e['value']) - bases[b] = {'replace': v, 'add': cur + v, 'multiply': cur * v}[str(e['method'])] - moved = [rc for rc in power_recast if sym_of.get(rc['base']) in bases] + v = spy.sympify(e["value"]) + bases[b] = {"replace": v, "add": cur + v, "multiply": cur * v}[str(e["method"])] + moved = [rc for rc in power_recast if sym_of.get(rc["base"]) in bases] for rc in moved: - evs.append({'var': rc['E'], 'method': 'replace', - 'value': spy.exp(spy.Symbol(rc['exp']) * spy.log(bases[sym_of[rc['base']]]))}) - for L in dict.fromkeys(rc['L'] for rc in moved): - rc = next(r for r in moved if r['L'] == L) - evs.append({'var': L, 'method': 'replace', 'value': spy.log(bases[sym_of[rc['base']]])}) + evs.append( + { + "var": rc["E"], + "method": "replace", + "value": spy.exp(spy.Symbol(rc["exp"]) * spy.log(bases[sym_of[rc["base"]]])), + } + ) + for L in dict.fromkeys(rc["L"] for rc in moved): + rc = next(r for r in moved if r["L"] == L) + evs.append({"var": L, "method": "replace", "value": spy.log(bases[sym_of[rc["base"]]])}) out.append(evs) return out -def compile_observability_tape_multi(model, observation, condition_subs, condition_ic0, - fixed=None, parameters=None, equilibrate=False, forcings=None, - seg_equilibrate=None, condition_events=None, - condition_t0_events=None, joint_steady_state=False, - joint_fixed_states=None, held_state_params=None, - condition_obs=None, condition_times=None, - keep_coords=None, condition_rest_subs=None, const_states=None, - positive=True, condition_chain=None): +def compile_observability_tape_multi( + model, + observation, + condition_subs, + condition_ic0, + fixed=None, + parameters=None, + equilibrate=False, + forcings=None, + seg_equilibrate=None, + condition_events=None, + condition_t0_events=None, + joint_steady_state=False, + joint_fixed_states=None, + held_state_params=None, + condition_obs=None, + condition_times=None, + keep_coords=None, + condition_rest_subs=None, + const_states=None, + positive=True, + condition_chain=None, +): """Per-condition observability tapes over shared coordinates, without `const_states`, or {'ok': False, ...}.""" if not state.env("NOSHARED"): - shared = shared_tape_compile(compile_observability_tape_multi, dict( - model=model, observation=observation, condition_subs=condition_subs, condition_ic0=condition_ic0, - fixed=fixed, parameters=parameters, equilibrate=equilibrate, forcings=forcings, - seg_equilibrate=seg_equilibrate, condition_events=condition_events, - condition_t0_events=condition_t0_events, joint_steady_state=joint_steady_state, - joint_fixed_states=joint_fixed_states, held_state_params=held_state_params, - condition_obs=condition_obs, condition_times=condition_times, keep_coords=keep_coords, - condition_rest_subs=condition_rest_subs, const_states=const_states, positive=positive, - condition_chain=condition_chain)) + shared = shared_tape_compile( + compile_observability_tape_multi, + dict( + model=model, + observation=observation, + condition_subs=condition_subs, + condition_ic0=condition_ic0, + fixed=fixed, + parameters=parameters, + equilibrate=equilibrate, + forcings=forcings, + seg_equilibrate=seg_equilibrate, + condition_events=condition_events, + condition_t0_events=condition_t0_events, + joint_steady_state=joint_steady_state, + joint_fixed_states=joint_fixed_states, + held_state_params=held_state_params, + condition_obs=condition_obs, + condition_times=condition_times, + keep_coords=keep_coords, + condition_rest_subs=condition_rest_subs, + const_states=const_states, + positive=positive, + condition_chain=condition_chain, + ), + ) if shared is not None: return shared _s = _str_memo() @@ -392,9 +451,10 @@ def compile_observability_tape_multi(model, observation, condition_subs, conditi # missing/None entries of `condition_obs` fall back to `observation` condition_obs = list(condition_obs) if condition_obs else [] - obs_per_cond = [_as_list(condition_obs[c]) if (c < len(condition_obs) and - condition_obs[c] is not None) - else observation for c in range(K)] + obs_per_cond = [ + _as_list(condition_obs[c]) if (c < len(condition_obs) and condition_obs[c] is not None) else observation + for c in range(K) + ] extra = [] for d in condition_subs: @@ -403,8 +463,7 @@ def compile_observability_tape_multi(model, observation, condition_subs, conditi for d in condition_ic0: for k, v in dict(d).items(): extra += [_s(k), _s(v)] - all_lines = (model + observation + [l for o in obs_per_cond for l in o] + - _as_list(parameters) + extra) + all_lines = model + observation + [l for o in obs_per_cond for l in o] + _as_list(parameters) + extra # symbol collection is order-insensitive and conditions repeat the same # trafo/IC strings, so tokenize each distinct line once all_lines = list(dict.fromkeys(all_lines)) @@ -413,8 +472,7 @@ def compile_observability_tape_multi(model, observation, condition_subs, conditi variables, diff_equations, _ = _read_equations(model, parse) obs_read = [_read_equations(o, parse) for o in obs_per_cond] obs_vars_per = [r[0] for r in obs_read] - fixed_names = set(_s(s) for s in - [local.get(nm, spy.Symbol(nm)) for nm in _as_list(fixed)]) + fixed_names = set(_s(s) for s in [local.get(nm, spy.Symbol(nm)) for nm in _as_list(fixed)]) # held-variable moieties (equilibrate without reduce_cq): each pivot state's resting # value is a shared initial-value parameter (held_map), so in joint mode the moiety # freedom lands on a reported parameter, not a per-condition state column @@ -422,11 +480,12 @@ def compile_observability_tape_multi(model, observation, condition_subs, conditi held_map = {_s(k): spy.Symbol(_s(v)) for k, v in held_state_params.items()} held_param_syms = [spy.Symbol(_s(v)) for v in held_state_params.values()] - is_const = [spy.sympify(e) == 0 and (const_states is None or _s(variables[i]) in set(const_states)) - for i, e in enumerate(diff_equations)] + is_const = [ + spy.sympify(e) == 0 and (const_states is None or _s(variables[i]) in set(const_states)) + for i, e in enumerate(diff_equations) + ] S = [variables[i] for i in range(len(variables)) if not is_const[i]] - Srhs = [spy.sympify(diff_equations[i]) for i in range(len(variables)) - if not is_const[i]] + Srhs = [spy.sympify(diff_equations[i]) for i in range(len(variables)) if not is_const[i]] n_s = len(S) parse_cache = {} @@ -474,7 +533,7 @@ def zero_powers(e): return r per_cond = [] - subs_per = [] # each condition's substitution map, aligned with per_cond + subs_per = [] # each condition's substitution map, aligned with per_cond for c in range(K): subs_map = {} for k, v in dict(condition_subs[c]).items(): @@ -513,11 +572,16 @@ def hyp(e): if r is None: r = hyp_cache[e] = _hyp_to_exp(e) return r - per_cond = [([hyp(e) for e in f_c], - [hyp(_strip_log_obs(e)) for e in g_c], - {k: hyp(v) for k, v in ic_c.items()}, - [hyp(e) for e in f_ss]) - for (f_c, g_c, ic_c, f_ss) in per_cond] + + per_cond = [ + ( + [hyp(e) for e in f_c], + [hyp(_strip_log_obs(e)) for e in g_c], + {k: hyp(v) for k, v in ic_c.items()}, + [hyp(e) for e in f_ss], + ) + for (f_c, g_c, ic_c, f_ss) in per_cond + ] # log-parametrized parameters: one that occurs only as base^(c*theta) is replaced # by the rational coordinate X = base^theta, and the report maps X back to theta @@ -525,12 +589,13 @@ def hyp(e): condition_times = condition_times or [] ev_exprs = [] for c in range(K): - for e in (list(condition_events[c]) if c < len(condition_events) else []): - ev_exprs.append(subs_memo(pval(e['value']), subs_per[c])) + for e in list(condition_events[c]) if c < len(condition_events) else []: + ev_exprs.append(subs_memo(pval(e["value"]), subs_per[c])) if c < len(condition_times) and condition_times[c] is not None: ev_exprs.append(subs_memo(pval(condition_times[c]), subs_per[c])) - lp_exprs = [e for (f_c, g_c, ic_c, f_ss) in per_cond - for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss)] + lp_exprs = [ + e for (f_c, g_c, ic_c, f_ss) in per_cond for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss) + ] # the distinct expressions: the searches below do not depend on repetitions lp_all = list(dict.fromkeys(lp_exprs + ev_exprs)) lp_base = _detect_log_params(lp_all, set(S)) @@ -541,31 +606,44 @@ def hyp(e): taken |= {_s(x) for x in spy.sympify(e).free_symbols} lp = {} for t, b in lp_base.items(): - nm = 'exp_%s' % t + nm = "exp_%s" % t while nm in taken: - nm += '_' + nm += "_" taken.add(nm) lp[t] = (spy.Symbol(nm), b, lp_den[t]) lp_sub = _log_param_sub(lp) if lp: - per_cond = [([lp_sub(e) for e in f_c], [lp_sub(e) for e in g_c], - {k: lp_sub(v) for k, v in ic_c.items()}, [lp_sub(e) for e in f_ss]) - for (f_c, g_c, ic_c, f_ss) in per_cond] + per_cond = [ + ( + [lp_sub(e) for e in f_c], + [lp_sub(e) for e in g_c], + {k: lp_sub(v) for k, v in ic_c.items()}, + [lp_sub(e) for e in f_ss], + ) + for (f_c, g_c, ic_c, f_ss) in per_cond + ] for t, (X, _b, _L) in lp.items(): if _s(t) in fixed_names: fixed_names.add(_s(X)) - log_params = [{'X': _s(X), 'theta': _s(t), 'base': 'E' if b ** spy.Rational(1, L) == spy.E - else _s(b ** spy.Rational(1, L))} - for t, (X, b, L) in sorted(lp.items(), key=lambda kv: _s(kv[0]))] + log_params = [ + {"X": _s(X), "theta": _s(t), "base": "E" if b ** spy.Rational(1, L) == spy.E else _s(b ** spy.Rational(1, L))} + for t, (X, b, L) in sorted(lp.items(), key=lambda kv: _s(kv[0])) + ] # each condition's later events and segment start time, in the leaves - ev_per = [[{'var': _s(e['var']), 'method': _s(e['method']), - 'value': lp_sub(subs_memo(pval(e['value']), subs_per[c]))} - for e in (list(condition_events[c]) if c < len(condition_events) else [])] - for c in range(K)] - tm_per = [lp_sub(subs_memo(pval(condition_times[c]), subs_per[c])) - if c < len(condition_times) and condition_times[c] is not None else None - for c in range(K)] + ev_per = [ + [ + {"var": _s(e["var"]), "method": _s(e["method"]), "value": lp_sub(subs_memo(pval(e["value"]), subs_per[c]))} + for e in (list(condition_events[c]) if c < len(condition_events) else []) + ] + for c in range(K) + ] + tm_per = [ + lp_sub(subs_memo(pval(condition_times[c]), subs_per[c])) + if c < len(condition_times) and condition_times[c] is not None + else None + for c in range(K) + ] # power/Hill recast: base^exp with a parameter exponent becomes a state E with # E' = exp*E*base'/base plus L = log(base), so f stays rational; E is held generic @@ -574,15 +652,17 @@ def hyp(e): power_recast = [] inv_solve_name = {} per_cond = _split_power_bases(per_cond) - per_cond, why = _start_powers(per_cond, S, fixed_names, - equilibrate or any(ev_per) or any(t is not None for t in tm_per) or - any(condition_t0_events or [])) + per_cond, why = _start_powers( + per_cond, + S, + fixed_names, + equilibrate or any(ev_per) or any(t is not None for t in tm_per) or any(condition_t0_events or []), + ) if why is not None: - return {'ok': False, 'why': why} + return {"ok": False, "why": why} pairs = _detect_power_atoms(per_cond, S) if pairs is None: - return {'ok': False, 'nonrational': - ['unsupported power form: base must be a symbol and exponent c*param']} + return {"ok": False, "nonrational": ["unsupported power form: base must be a symbol and exponent c*param"]} if pairs: S, per_cond, power_recast = _apply_power_recast(pairs, S, per_cond) ev_per = _power_events(ev_per, power_recast, S[:n_s]) @@ -593,37 +673,45 @@ def hyp(e): # stay generic real_set = {_s(X) for X in S[:n_real]} bare_syms = set() - for (_f, _g, _ic, ss_r) in per_cond: + for _f, _g, _ic, ss_r in per_cond: for e in ss_r[:n_real]: bare_syms |= spy.fraction(spy.together(e))[0].free_symbols for rc in power_recast: - rc['inverted'] = (rc['base'] in real_set - and spy.Symbol(rc['base']) not in bare_syms) + rc["inverted"] = rc["base"] in real_set and spy.Symbol(rc["base"]) not in bare_syms by_base = {} for rc in power_recast: - by_base.setdefault(rc['base'], []).append(rc) + by_base.setdefault(rc["base"], []).append(rc) for base, group in by_base.items(): - if group[0]['inverted'] and len(group) > 1: - return {'ok': False, 'nonrational': - ['free exponent base %s has multiple independent ' - 'powers with no linear turnover term' % base]} - inv_solve_name = {rc['base']: rc['E'] - for rc in power_recast if rc['inverted']} + if group[0]["inverted"] and len(group) > 1: + return { + "ok": False, + "nonrational": [ + "free exponent base %s has multiple independent powers with no linear turnover term" % base + ], + } + inv_solve_name = {rc["base"]: rc["E"] for rc in power_recast if rc["inverted"]} else: # transient: no steady-state solve, so nothing is inverted for rc in power_recast: - rc['inverted'] = False + rc["inverted"] = False def any_in(pred): # conditions and segments repeat the same expressions: each distinct one is tested once - return any(pred(e) for e in _distinct( - [e for (f_c, g_c, ic_c, _) in per_cond for e in list(f_c) + list(g_c) + list(ic_c.values())] + - [e['value'] for evs in ev_per for e in evs] + [t for t in tm_per if t is not None])) + return any( + pred(e) + for e in _distinct( + [e for (f_c, g_c, ic_c, _) in per_cond for e in list(f_c) + list(g_c) + list(ic_c.values())] + + [e["value"] for evs in ev_per for e in evs] + + [t for t in tm_per if t is not None] + ) + ) def taken_names(): taken = {_s(x) for x in S} | set(fixed_names) | {_s(X) for X, *_ in lp.values()} - for e in _distinct([e for (f_c, g_c, ic_c, f_ss) in per_cond - for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss)] + list(lp_all)): + for e in _distinct( + [e for (f_c, g_c, ic_c, f_ss) in per_cond for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss)] + + list(lp_all) + ): taken |= {_s(x) for x in spy.sympify(e).free_symbols} return taken @@ -638,73 +726,104 @@ def taken_names(): evs = list(condition_t0_events[c]) if condition_t0_events and c < len(condition_t0_events) else [] if not seg_eq[c] or not evs: continue - evs = [{'var': _s(e['var']), 'method': _s(e['method']), - 'value': lp_sub(subs_memo(pval(e['value']), subs_per[c]))} for e in evs] + evs = [ + {"var": _s(e["var"]), "method": _s(e["method"]), "value": lp_sub(subs_memo(pval(e["value"]), subs_per[c]))} + for e in evs + ] if power_recast: evs = _power_events([evs], power_recast, S)[0] - if any(_reads_states(e['value'], S) for e in evs): + if any(_reads_states(e["value"], S) for e in evs): ev_per[c] = [dict(e, t0=True) for e in evs] + list(ev_per[c]) t0_moved[c] = True # a chain that starts at rest starts at the seeded coordinates: held pivots at their # parameters, forcings and forced-zero states at zero rest_recast = bool(equilibrate and any(seg_eq) and joint_steady_state) - if any(seg_eq) and joint_steady_state and (any(t0_moved) or any( - _reads_states(e['value'], S) for evs in ev_per for e in evs) or - any_in(_has_trig) or any_in(_has_exp) or any_in(_has_func)): + if ( + any(seg_eq) + and joint_steady_state + and ( + any(t0_moved) + or any(_reads_states(e["value"], S) for evs in ev_per for e in evs) + or any_in(_has_trig) + or any_in(_has_exp) + or any_in(_has_func) + ) + ): jfs = set(joint_fixed_states or []) - per_cond = [(f_c, g_c, {**ic_c, **{_s(X): (held_map[_s(X)] if _s(X) in held_map else spy.Integer(0)) - for X in S if _s(X) in held_map or _s(X) in forcings - or _s(X) in jfs}}, f_ss) if seg_eq[c] else (f_c, g_c, ic_c, f_ss) - for c, (f_c, g_c, ic_c, f_ss) in enumerate(per_cond)] + per_cond = [ + ( + f_c, + g_c, + { + **ic_c, + **{ + _s(X): (held_map[_s(X)] if _s(X) in held_map else spy.Integer(0)) + for X in S + if _s(X) in held_map or _s(X) in forcings or _s(X) in jfs + }, + }, + f_ss, + ) + if seg_eq[c] + else (f_c, g_c, ic_c, f_ss) + for c, (f_c, g_c, ic_c, f_ss) in enumerate(per_cond) + ] trig_recast = None # states the recasts add; at rest each starts at the value of the leaf, and the resting model # holds the same leaves (rest_recast) n_core = len(S) if any_in(_has_trig): - trig_recast = _apply_trig_recast(S, per_cond, ev_per, tm_per, taken_names(), condition_chain, - at_rest=rest_recast) - if 'why' in trig_recast: - return {'ok': False, 'why': trig_recast['why']} - S, per_cond = trig_recast['S'], trig_recast['per_cond'] - ev_per, tm_per = trig_recast['ev_per'], trig_recast['tm_per'] + trig_recast = _apply_trig_recast( + S, per_cond, ev_per, tm_per, taken_names(), condition_chain, at_rest=rest_recast + ) + if "why" in trig_recast: + return {"ok": False, "why": trig_recast["why"]} + S, per_cond = trig_recast["S"], trig_recast["per_cond"] + ev_per, tm_per = trig_recast["ev_per"], trig_recast["tm_per"] n_s = len(S) - fixed_names |= set(trig_recast['consts']) + fixed_names |= set(trig_recast["consts"]) # exponentials: auxiliary states and generic exponential leaves (_apply_exp_recast) exp_recast = None - if rest_recast and any(a.base.is_Rational and a.base > 0 and a.base != 1 and not a.exp.is_number - and not (a.exp.free_symbols & set(S)) - for (_f, _g, _ic, f_ss) in per_cond for e in f_ss for a in spy.sympify(e).atoms(spy.Pow)): + if rest_recast and any( + a.base.is_Rational and a.base > 0 and a.base != 1 and not a.exp.is_number and not (a.exp.free_symbols & set(S)) + for (_f, _g, _ic, f_ss) in per_cond + for e in f_ss + for a in spy.sympify(e).atoms(spy.Pow) + ): # detection.numbase joins the number into a base of the same power or holds it as a constant - return {'ok': False, 'why': 'equilibrate does not support a power b^x of a positive rational number b ' - 'in the resting model; write it as a power of a parameter'} + return { + "ok": False, + "why": "equilibrate does not support a power b^x of a positive rational number b " + "in the resting model; write it as a power of a parameter", + } if any_in(_has_exp): - exp_recast = _apply_exp_recast(S, per_cond, ev_per, tm_per, taken_names(), condition_chain, - at_rest=rest_recast) - if 'why' in exp_recast: - return {'ok': False, 'why': exp_recast['why']} - S, per_cond = exp_recast['S'], exp_recast['per_cond'] - ev_per, tm_per = exp_recast['ev_per'], exp_recast['tm_per'] + exp_recast = _apply_exp_recast(S, per_cond, ev_per, tm_per, taken_names(), condition_chain, at_rest=rest_recast) + if "why" in exp_recast: + return {"ok": False, "why": exp_recast["why"]} + S, per_cond = exp_recast["S"], exp_recast["per_cond"] + ev_per, tm_per = exp_recast["ev_per"], exp_recast["tm_per"] n_s = len(S) - fixed_names |= set(exp_recast['consts']) + fixed_names |= set(exp_recast["consts"]) if trig_recast is not None: exp_recast = _merge_recast(trig_recast, exp_recast) func_recast = None if any_in(_has_func): - func_recast = _apply_func_recast(S, per_cond, ev_per, tm_per, taken_names(), condition_chain, - at_rest=rest_recast) - if 'why' in func_recast: - return {'ok': False, 'why': func_recast['why']} - S, per_cond = func_recast['S'], func_recast['per_cond'] - ev_per, tm_per = func_recast['ev_per'], func_recast['tm_per'] + func_recast = _apply_func_recast( + S, per_cond, ev_per, tm_per, taken_names(), condition_chain, at_rest=rest_recast + ) + if "why" in func_recast: + return {"ok": False, "why": func_recast["why"]} + S, per_cond = func_recast["S"], func_recast["per_cond"] + ev_per, tm_per = func_recast["ev_per"], func_recast["tm_per"] n_s = len(S) - fixed_names |= set(func_recast['consts']) + fixed_names |= set(func_recast["consts"]) if func_recast is not None: exp_recast = _merge_recast(exp_recast, func_recast) if any_in(lambda e: spy.sympify(e).has(spy.pi, spy.E)): const_recast = _apply_const_recast(S, per_cond, ev_per, tm_per, taken_names()) - per_cond, ev_per, tm_per = const_recast['per_cond'], const_recast['ev_per'], const_recast['tm_per'] - fixed_names |= set(const_recast['consts']) + per_cond, ev_per, tm_per = const_recast["per_cond"], const_recast["ev_per"], const_recast["tm_per"] + fixed_names |= set(const_recast["consts"]) exp_recast = _merge_recast(exp_recast, const_recast) rest_aux = {_s(X) for X in S[n_core:]} if rest_recast else set() rest_inverted = {} @@ -714,14 +833,14 @@ def taken_names(): eq_ss = [f_ss for c, (_f, _g, _ic, f_ss) in enumerate(per_cond) if seg_eq[c]] jfs = set(joint_fixed_states or []) leaves_of = {} - for W, z, _e in exp_recast['rel']: + for W, z, _e in exp_recast["rel"]: leaves_of.setdefault(z, []).append(W) taken_w = set(inv_solve_name.values()) # the balances the resting solve keeps: held pivots, forcings and states at zero are no unknowns - lines = [i for i in range(n_real) if _s(S[i]) not in forcings and _s(S[i]) not in jfs - and _s(S[i]) not in held_map] - reads = [set().union(*[{_s(x) for x in spy.sympify(f_ss[i]).free_symbols} for f_ss in eq_ss]) - for i in lines] + lines = [ + i for i in range(n_real) if _s(S[i]) not in forcings and _s(S[i]) not in jfs and _s(S[i]) not in held_map + ] + reads = [set().union(*[{_s(x) for x in spy.sympify(f_ss[i]).free_symbols} for f_ss in eq_ss]) for i in lines] def matched(unknowns): # the size of a maximum matching of the balances to the unknowns they read @@ -735,7 +854,9 @@ def augment(k, seen): owner[u] = k return True return False + return sum(augment(k, set()) for k in range(len(lines))) + unknowns = [_s(S[i]) for i in lines] size = matched(unknowns) for nm in sorted(unknowns, key=lambda n: (len(leaves_of.get(n, ())), n)): @@ -753,33 +874,46 @@ def augment(k, seen): break inv_solve_name.update(rest_inverted) # a leaf of a resting state is one coordinate, shared by the conditions, so their resting states must agree - in_leaves = sorted({z for _W, z, _e in exp_recast['rel'] if z in {_s(X) for X in S[:n_real]}}) + in_leaves = sorted({z for _W, z, _e in exp_recast["rel"] if z in {_s(X) for X in S[:n_real]}}) if in_leaves and len({tuple(f_ss[:n_real]) for f_ss in eq_ss}) > 1: - return {'ok': False, 'why': 'equilibrate does not support conditions with different resting models ' - 'when a state at rest (%s) enters a non-rational term; give the steady state through `trafo` ' - 'or analyze the conditions with the same resting model together' % ', '.join(in_leaves)} + return { + "ok": False, + "why": "equilibrate does not support conditions with different resting models " + "when a state at rest (%s) enters a non-rational term; give the steady state through `trafo` " + "or analyze the conditions with the same resting model together" % ", ".join(in_leaves), + } if rest_recast: # a root of the states left in the resting model has no leaf - roots = sorted({str(a) for (_f, _g, _ic, f_ss) in per_cond for e in f_ss for a in _func_atoms(e) - if _func_arg(a).free_symbols & set(S)}) + roots = sorted( + { + str(a) + for (_f, _g, _ic, f_ss) in per_cond + for e in f_ss + for a in _func_atoms(e) + if _func_arg(a).free_symbols & set(S) + } + ) if roots: - return {'ok': False, 'why': 'equilibrate does not support the non-integer power %s of an expression ' - 'in the states in the resting model; give the steady state through `trafo` or start from ' - 'free initial values' % roots[0].replace('**', '^')} + return { + "ok": False, + "why": "equilibrate does not support the non-integer power %s of an expression " + "in the states in the resting model; give the steady state through `trafo` or start from " + "free initial values" % roots[0].replace("**", "^"), + } if any(t0_moved): condition_t0_events = [list(x) for x in condition_t0_events] for c in range(K): if t0_moved[c]: - condition_t0_events[c] = [e for e in ev_per[c] if e.get('t0')] - ev_per[c] = [e for e in ev_per[c] if not e.get('t0')] + condition_t0_events[c] = [e for e in ev_per[c] if e.get("t0")] + ev_per[c] = [e for e in ev_per[c] if not e.get("t0")] nonrational = [] - rat_ok = set() # deduped exprs recur across conditions; check each once + rat_ok = set() # deduped exprs recur across conditions; check each once def _rat(e): if e in rat_ok: return True - ok = _is_rational_expr(e.xreplace({a: spy.Symbol('_start_pow') for a in e.atoms(StartPow)})) + ok = _is_rational_expr(e.xreplace({a: spy.Symbol("_start_pow") for a in e.atoms(StartPow)})) if ok: rat_ok.add(e) return ok @@ -787,15 +921,15 @@ def _rat(e): for c, (f_c, g_c, ic_c, _f_ss) in enumerate(per_cond): for X, e in zip(S, f_c): if not _rat(e): - nonrational.append('d%s/dt = %s' % (X, e)) + nonrational.append("d%s/dt = %s" % (X, e)) for y, e in zip(obs_vars_per[c], g_c): if not _rat(e): - nonrational.append('%s = %s' % (y, e)) + nonrational.append("%s = %s" % (y, e)) for X in S: if not (_rat(ic_c[_s(X)]) or _is_sqrt_rational(ic_c[_s(X)])): - nonrational.append('%s(0) = %s' % (X, ic_c[_s(X)])) + nonrational.append("%s(0) = %s" % (X, ic_c[_s(X)])) if nonrational: - return {'ok': False, 'nonrational': nonrational} + return {"ok": False, "nonrational": nonrational} # a state has a free initial-value leaf when the initial value still contains the # state symbol (possibly under a dose); equilibrate-seeded states have none @@ -807,8 +941,7 @@ def _rat(e): if joint_steady_state: jfs = set(joint_fixed_states or []) for X in S: - if (_s(X) not in forcings and _s(X) not in jfs - and _s(X) not in held_map and _s(X) not in rest_aux): + if _s(X) not in forcings and _s(X) not in jfs and _s(X) not in held_map and _s(X) not in rest_aux: free_state[_s(X)] = True continue # equilibrate-seeded: no state is a free coordinate (unless joint) for X in S: @@ -821,12 +954,12 @@ def _rat(e): event_vals = [] for c in range(K): evs = list(condition_events[c]) if c < len(condition_events) else [] - event_vals.append([lp_sub(spy.sympify(pval(e['value']))) for e in evs]) + event_vals.append([lp_sub(spy.sympify(pval(e["value"]))) for e in evs]) # f_ss is included so parameters the perturbed dynamics drop still count paramset = set() - seen_ps = set() # deduped exprs recur across conditions; walk each once - for (f_c, g_c, ic_c, f_ss) in per_cond: + seen_ps = set() # deduped exprs recur across conditions; walk each once + for f_c, g_c, ic_c, f_ss in per_cond: for e in list(f_c) + list(g_c) + list(ic_c.values()) + list(f_ss): if e in seen_ps: continue @@ -837,14 +970,14 @@ def _rat(e): paramset |= set(e.free_symbols) for evs in ev_per: for e in evs: - paramset |= set(_unmarked(spy.sympify(e['value']), S).free_symbols) + paramset |= set(_unmarked(spy.sympify(e["value"]), S).free_symbols) for c in range(K): if t0_moved[c]: for e in condition_t0_events[c]: - paramset |= set(spy.sympify(e['value']).free_symbols) + paramset |= set(spy.sympify(e["value"]).free_symbols) if exp_recast is not None: by_name = {_s(x): x for x in paramset} - for rl in exp_recast['rel']: + for rl in exp_recast["rel"]: paramset |= set(rl[2].free_symbols) paramset.add(by_name.get(rl[1], spy.Symbol(rl[1]))) # a segment's left boundary may sit at a time given in the parameters @@ -852,24 +985,26 @@ def _rat(e): if tm is not None and c < K: paramset |= set(lp_sub(pval(tm)).free_symbols) paramset -= set(S) - paramset |= set(held_param_syms) # held-variable initial-value parameters + paramset |= set(held_param_syms) # held-variable initial-value parameters # coordinates a trafo absorbed stay coordinates paramset |= {local.get(_s(n), spy.Symbol(_s(n))) for n in _as_list(keep_coords)} # one coordinate per name: a leaf read off a relation by name is the leaf with its assumptions - params = sorted({_s(x): x for x in sorted(paramset, key=lambda x: (_s(x), bool(x.assumptions0)))}.values(), - key=spy.default_sort_key) + params = sorted( + {_s(x): x for x in sorted(paramset, key=lambda x: (_s(x), bool(x.assumptions0)))}.values(), + key=spy.default_sort_key, + ) # a base seen only under a free exponent vanished into the recast atom; re-added, the # recast relation ties it, and the co-scaling of the base is reported as an exact scaling if power_recast: known = set(_s(s) for s in S) | set(_s(s) for s in params) | set(forcings) for rc in power_recast: - if rc['base'] not in known: - params.append(spy.Symbol(rc['base'])) - known.add(rc['base']) + if rc["base"] not in known: + params.append(spy.Symbol(rc["base"])) + known.add(rc["base"]) # so does an exponent seen only there, which the relation E = base^n ties as well - if rc['exp'] not in known and rc['exp'] not in fixed_names: - params.append(spy.Symbol(rc['exp'])) - known.add(rc['exp']) + if rc["exp"] not in known and rc["exp"] not in fixed_names: + params.append(spy.Symbol(rc["exp"])) + known.add(rc["exp"]) params = sorted(params, key=spy.default_sort_key) free_states = [X for X in S if free_state[_s(X)]] @@ -883,9 +1018,9 @@ def _rat(e): tapes = [] reach_cache = {} # structural Lie reach per (model, initial values, events) - emit_cache = {} # (f_c, g_c, obs names) recur across segments/conditions + emit_cache = {} # (f_c, g_c, obs names) recur across segments/conditions ss_sol_cache = {} # linear resting-state solutions, keyed on the f_ss tuple - ic_cache = {} # emitted IC tapes, keyed on the seed-expression tuple + ic_cache = {} # emitted IC tapes, keyed on the seed-expression tuple e_num = {spy.E: spy.exp(1, evaluate=False)} lines_memo = {} @@ -896,6 +1031,7 @@ def lines_expr(e): x = spy.sympify(e).xreplace(e_num) r = lines_memo[e] = str(x.replace(lambda y: isinstance(y, StartPow), lambda y: y.args[0] ** y.args[1])) return r + for c, (f_c, g_c, ic_c, f_ss) in enumerate(per_cond): subs_map = subs_per[c] ekey = (tuple(f_c), tuple(g_c), tuple(_s(v) for v in obs_vars_per[c])) @@ -904,12 +1040,12 @@ def lines_expr(e): try: emitted = _emit_tape_shared(f_c, g_c, slot_of, base) except _NotRationalError: - return {'ok': False} + return {"ok": False} # this segment's substituted model as lines for the scaling peel, # exponentials kept f0, g0 = scal_per_cond[c][0], scal_per_cond[c][1] - m_lines = ['%s = %s' % (_s(scal_s[i]), lines_expr(f0[i])) for i in range(len(scal_s))] - o_lines = ['%s = %s' % (_s(obs_vars_per[c][j]), lines_expr(g0[j])) for j in range(len(g0))] + m_lines = ["%s = %s" % (_s(scal_s[i]), lines_expr(f0[i])) for i in range(len(scal_s))] + o_lines = ["%s = %s" % (_s(obs_vars_per[c][j]), lines_expr(g0[j])) for j in range(len(g0))] cached = (emitted, m_lines, o_lines) emit_cache[ekey] = cached (op, a, b, cnum, cden, outslots), m_lines, o_lines = cached @@ -917,35 +1053,54 @@ def lines_expr(e): # structural first Lie order of every symbol in this segment's jets; the # saturation counts no flat step before it (a readout behind a transit chain is # flat at rank 0 until the chain has filled) - reach_key = (ekey, tuple(sorted((_s(k), _s(v)) for k, v in ic_c.items())), - tuple((_s(e['var']), _s(e['value'])) for e in ev_per[c]), - bool(seg_eq[c])) + reach_key = ( + ekey, + tuple(sorted((_s(k), _s(v)) for k, v in ic_c.items())), + tuple((_s(e["var"]), _s(e["value"])) for e in ev_per[c]), + bool(seg_eq[c]), + ) reach = reach_cache.get(reach_key) if reach is None: - reach = _lie_reach(f_c, g_c, S, ic_c, - [dict(e, value=_unmarked(spy.sympify(e['value']), S)) for e in ev_per[c]], - f_ss if seg_eq[c] else None) + reach = _lie_reach( + f_c, + g_c, + S, + ic_c, + [dict(e, value=_unmarked(spy.sympify(e["value"]), S)) for e in ev_per[c]], + f_ss if seg_eq[c] else None, + ) reach_cache[reach_key] = reach tape = { - 'op': op, 'a': a, 'b': b, 'cnum': cnum, 'cden': cden, - 'state_slots': [n_leaves + i for i in range(n_s)], - 'f_out': f_out, - 'g_out': outslots[n_s:n_s + len(g_c)], - 'ic_leaf': [-1] * n_s, 'ic_num': ['0'] * n_s, 'ic_den': ['1'] * n_s, - 'model_lines': m_lines, - 'obs_lines': o_lines, + "op": op, + "a": a, + "b": b, + "cnum": cnum, + "cden": cden, + "state_slots": [n_leaves + i for i in range(n_s)], + "f_out": f_out, + "g_out": outslots[n_s : n_s + len(g_c)], + "ic_leaf": [-1] * n_s, + "ic_num": ["0"] * n_s, + "ic_den": ["1"] * n_s, + "model_lines": m_lines, + "obs_lines": o_lines, # initial values, boundary events and start time, for verify_scalings() - 'ver_ic': ['%s = %s' % (_s(X), _s(ic_c[_s(X)])) for X in S if _s(X) in ic_c], - 'ver_ev': [{'var': _s(e['var']), 'method': _s(e['method']), - 'value': _s(e.get('plain', e['value']))} for e in ev_per[c]], - 'ver_t0': [{'var': _s(e['var']), 'method': _s(e['method']), - 'value': _s(e['value'])} for e in - (condition_t0_events[c] if condition_t0_events and - c < len(condition_t0_events) else [])], - 'ver_time': '' if tm_per[c] is None else _s(tm_per[c]), + "ver_ic": ["%s = %s" % (_s(X), _s(ic_c[_s(X)])) for X in S if _s(X) in ic_c], + "ver_ev": [ + {"var": _s(e["var"]), "method": _s(e["method"]), "value": _s(e.get("plain", e["value"]))} + for e in ev_per[c] + ], + "ver_t0": [ + {"var": _s(e["var"]), "method": _s(e["method"]), "value": _s(e["value"])} + for e in (condition_t0_events[c] if condition_t0_events and c < len(condition_t0_events) else []) + ], + "ver_time": "" if tm_per[c] is None else _s(tm_per[c]), # the resting model of a start at rest, which a scaling must leave invariant as well - 'ver_rest': ['%s = %s' % (_s(scal_s[i]), spy.sympify(e).xreplace(e_num)) - for i, e in enumerate(scal_per_cond[c][3])] if seg_eq[c] else [], + "ver_rest": [ + "%s = %s" % (_s(scal_s[i]), spy.sympify(e).xreplace(e_num)) for i, e in enumerate(scal_per_cond[c][3]) + ] + if seg_eq[c] + else [], } if seg_eq[c] and joint_steady_state: # joint mode: each non-forcing state is an identity leaf seeded to x*; @@ -953,25 +1108,38 @@ def lines_expr(e): jfs = set(joint_fixed_states or []) # held pivots seed from their parameter (held_map), forcings and forced-zero # states from 0 - ic_map = {X: (held_map[_s(X)] if _s(X) in held_map - else ic_c[_s(X)] if _s(X) in rest_aux - else X if (_s(X) not in forcings and _s(X) not in jfs) - else spy.Integer(0)) for X in S} + ic_map = { + X: ( + held_map[_s(X)] + if _s(X) in held_map + else ic_c[_s(X)] + if _s(X) in rest_aux + else X + if (_s(X) not in forcings and _s(X) not in jfs) + else spy.Integer(0) + ) + for X in S + } # t0 events act on the pre-event coordinate x_ss (seeded from val_by); # the IC tape holds x0 = E(x_ss) with chain-rule duals - _compose_t0_events(ic_map, condition_t0_events[c] - if condition_t0_events and c < len(condition_t0_events) - else [], pval, subs_map) + _compose_t0_events( + ic_map, + condition_t0_events[c] if condition_t0_events and c < len(condition_t0_events) else [], + pval, + subs_map, + ) try: ic_op, ic_a, ic_b, ic_cnum, ic_cden, ic_out = _emit_tape_shared( - [ic_map[X] for X in S], [], leaf_slot, n_leaves) + [ic_map[X] for X in S], [], leaf_slot, n_leaves + ) except _NotRationalError: - return {'ok': False} - tape.update({'ic_op': ic_op, 'ic_a': ic_a, 'ic_b': ic_b, 'ic_cnum': ic_cnum, - 'ic_cden': ic_cden, 'ic_out': ic_out}) - tape['constraint_model'] = [ - '%s = %s' % (inv_solve_name.get(_s(S[i]), _s(S[i])), - spy.sympify(f_ss[i])) for i in range(n_real)] + return {"ok": False} + tape.update( + {"ic_op": ic_op, "ic_a": ic_a, "ic_b": ic_b, "ic_cnum": ic_cnum, "ic_cden": ic_cden, "ic_out": ic_out} + ) + tape["constraint_model"] = [ + "%s = %s" % (inv_solve_name.get(_s(S[i]), _s(S[i])), spy.sympify(f_ss[i])) for i in range(n_real) + ] elif seg_eq[c]: # equilibrate-seeded first segment: a generically linear resting state (no # recast) is solved symbolically and emitted as an IC tape; otherwise it is @@ -982,37 +1150,47 @@ def lines_expr(e): if sskey in ss_sol_cache: ss_sol = ss_sol_cache[sskey] else: - solve_s = [S[i] for i in range(n_real) - if _s(S[i]) not in forcings] - fss_polys = [spy.expand(spy.fraction(spy.together( - spy.sympify(f_ss[i])))[0]) - for i in range(n_real) if _s(S[i]) not in forcings] + solve_s = [S[i] for i in range(n_real) if _s(S[i]) not in forcings] + fss_polys = [ + spy.expand(spy.fraction(spy.together(spy.sympify(f_ss[i])))[0]) + for i in range(n_real) + if _s(S[i]) not in forcings + ] ss_sol = _linear_solution(fss_polys, solve_s) ss_sol_cache[sskey] = ss_sol if ss_sol is not None: # recast coordinates (beyond n_real) stay generic; forcings and # dead states stay 0 - ic_map = {X: (ss_sol[X] if X in ss_sol - else X if i >= n_real else spy.Integer(0)) - for i, X in enumerate(S)} + ic_map = { + X: (ss_sol[X] if X in ss_sol else X if i >= n_real else spy.Integer(0)) for i, X in enumerate(S) + } # t0 events compose onto the resting state - _compose_t0_events(ic_map, condition_t0_events[c] - if condition_t0_events and - c < len(condition_t0_events) else [], - pval, subs_map) + _compose_t0_events( + ic_map, + condition_t0_events[c] if condition_t0_events and c < len(condition_t0_events) else [], + pval, + subs_map, + ) try: ic_op, ic_a, ic_b, ic_cnum, ic_cden, ic_out = _emit_tape_shared( - [ic_map[X] for X in S], [], leaf_slot, n_leaves) - ss_ic = {'ic_op': ic_op, 'ic_a': ic_a, 'ic_b': ic_b, - 'ic_cnum': ic_cnum, 'ic_cden': ic_cden, 'ic_out': ic_out} + [ic_map[X] for X in S], [], leaf_slot, n_leaves + ) + ss_ic = { + "ic_op": ic_op, + "ic_a": ic_a, + "ic_b": ic_b, + "ic_cnum": ic_cnum, + "ic_cden": ic_cden, + "ic_out": ic_out, + } except _NotRationalError: ss_ic = None if ss_ic is not None: tape.update(ss_ic) else: - tape['constraint_model'] = [ - '%s = %s' % (inv_solve_name.get(_s(S[i]), _s(S[i])), - spy.sympify(f_ss[i])) for i in range(n_real)] + tape["constraint_model"] = [ + "%s = %s" % (inv_solve_name.get(_s(S[i]), _s(S[i])), spy.sympify(f_ss[i])) for i in range(n_real) + ] else: # IC tape: seed each state from the initial-value expression in the # leaves (free initial values, z coordinates, doses, resets). @@ -1020,67 +1198,74 @@ def lines_expr(e): ic_emitted = ic_cache.get(ickey) if ic_emitted is None: try: - ic_emitted = _emit_tape_shared(list(ickey), [], leaf_slot, - n_leaves, allow_sqrt=True) + ic_emitted = _emit_tape_shared(list(ickey), [], leaf_slot, n_leaves, allow_sqrt=True) except _NotRationalError: - return {'ok': False} + return {"ok": False} ic_cache[ickey] = ic_emitted ic_op, ic_a, ic_b, ic_cnum, ic_cden, ic_out = ic_emitted - tape.update({'ic_op': ic_op, 'ic_a': ic_a, 'ic_b': ic_b, - 'ic_cnum': ic_cnum, 'ic_cden': ic_cden, 'ic_out': ic_out}) + tape.update( + {"ic_op": ic_op, "ic_a": ic_a, "ic_b": ic_b, "ic_cnum": ic_cnum, "ic_cden": ic_cden, "ic_out": ic_out} + ) # the symbolic jets of this segment, for jet_generator(): dynamics, # observables and initial values over the leaves; a power of a state at 0 has no # Taylor jets if not any(e.has(StartPow) for e in list(f_c) + list(g_c)): - tape['jet_f'] = ['%s = %s' % (_s(S[i]), _s(f_c[i])) for i in range(n_s)] - tape['jet_g'] = [_s(e) for e in g_c] - tape['jet_ic'] = ['%s = %s' % (_s(X), _s(ic_c[_s(X)])) for X in S] + tape["jet_f"] = ["%s = %s" % (_s(S[i]), _s(f_c[i])) for i in range(n_s)] + tape["jet_g"] = [_s(e) for e in g_c] + tape["jet_ic"] = ["%s = %s" % (_s(X), _s(ic_c[_s(X)])) for X in S] # a later segment's boundary events, and whether the segment start time is free of # the coordinates (the jets of a moving boundary need the time shift too) - tape['jet_ev'] = [{'var': _s(e['var']), 'method': _s(e['method']), - 'value': _s(e.get('plain', e['value']))} for e in ev_per[c]] - tape['jet_time_fixed'] = bool(tm_per[c] is None or - not spy.sympify(tm_per[c]).free_symbols) + tape["jet_ev"] = [ + {"var": _s(e["var"]), "method": _s(e["method"]), "value": _s(e.get("plain", e["value"]))} + for e in ev_per[c] + ] + tape["jet_time_fixed"] = bool(tm_per[c] is None or not spy.sympify(tm_per[c]).free_symbols) # events at this segment's left boundary, applied by the kernel to the # propagated state; their values as an order-0 tape over the leaves evs = ev_per[c] if evs: idx_of_state = {_s(X): i for i, X in enumerate(S)} - method_code = {'replace': 0, 'add': 1, 'multiply': 2} - keep = [e for e in evs if _s(e['var']) in idx_of_state] + method_code = {"replace": 0, "add": 1, "multiply": 2} + keep = [e for e in evs if _s(e["var"]) in idx_of_state] if keep: - vals = [e['value'] for e in keep] + vals = [e["value"] for e in keep] # values over the leaves and the states just before the event; a marked value # reads those states as pre_state() and initial values by their names - marked = any(e.get('marked') for e in keep) - state_slot = {(_s(pre_state(nm)) if marked else nm): n_leaves + i - for nm, i in idx_of_state.items()} + marked = any(e.get("marked") for e in keep) + state_slot = {(_s(pre_state(nm)) if marked else nm): n_leaves + i for nm, i in idx_of_state.items()} ev_slot = dict(leaf_slot, **state_slot) try: - ev_op, ev_a, ev_b, ev_cnum, ev_cden, ev_o = _emit_tape_shared( - [], vals, ev_slot, n_leaves + n_s) + ev_op, ev_a, ev_b, ev_cnum, ev_cden, ev_o = _emit_tape_shared([], vals, ev_slot, n_leaves + n_s) except _NotRationalError: - return {'ok': False} - tape.update({ - 'ev_op': ev_op, 'ev_a': ev_a, 'ev_b': ev_b, 'ev_cnum': ev_cnum, - 'ev_cden': ev_cden, 'ev_out': ev_o, - 'ev_var_idx': [idx_of_state[_s(e['var'])] for e in keep], - 'ev_state_slots': 1, - 'ev_leaf_only': [not ({str(x) for x in spy.sympify(v).free_symbols} & set(state_slot)) - for v in vals], - 'ev_method': [method_code[_s(e['method'])] for e in keep]}) + return {"ok": False} + tape.update( + { + "ev_op": ev_op, + "ev_a": ev_a, + "ev_b": ev_b, + "ev_cnum": ev_cnum, + "ev_cden": ev_cden, + "ev_out": ev_o, + "ev_var_idx": [idx_of_state[_s(e["var"])] for e in keep], + "ev_state_slots": 1, + "ev_leaf_only": [ + not ({str(x) for x in spy.sympify(v).free_symbols} & set(state_slot)) for v in vals + ], + "ev_method": [method_code[_s(e["method"])] for e in keep], + } + ) # the segment's left boundary time as an order-0 tape: the value sets the gap # lengths, the duals hold a time that depends on the coordinates if tm_per[c] is not None: tv = tm_per[c] try: - tm_op, tm_a, tm_b, tm_cnum, tm_cden, tm_o = _emit_tape_shared( - [], [tv], leaf_slot, n_leaves) + tm_op, tm_a, tm_b, tm_cnum, tm_cden, tm_o = _emit_tape_shared([], [tv], leaf_slot, n_leaves) except _NotRationalError: - return {'ok': False} - tape.update({'tm_op': tm_op, 'tm_a': tm_a, 'tm_b': tm_b, 'tm_cnum': tm_cnum, - 'tm_cden': tm_cden, 'tm_out': tm_o}) - tape['_reach'] = reach + return {"ok": False} + tape.update( + {"tm_op": tm_op, "tm_a": tm_a, "tm_b": tm_b, "tm_cnum": tm_cnum, "tm_cden": tm_cden, "tm_out": tm_o} + ) + tape["_reach"] = reach tapes.append(tape) z_state_names = [_s(X) for X in free_states if _s(X) not in fixed_names] @@ -1089,61 +1274,68 @@ def lines_expr(e): z_slots = [leaf_slot[nm] for nm in znames] # per tape, the first Lie order at which each coordinate can enter (-1: never) for t in tapes: - r = t.pop('_reach', None) or {} - t['lie_reach'] = [int(r.get(nm, -1)) for nm in znames] + r = t.pop("_reach", None) or {} + t["lie_reach"] = [int(r.get(nm, -1)) for nm in znames] out = { - 'ok': True, - 'tapes': tapes, - 'n_leaves': n_leaves, - 'n_states': n_s, - 'z_slots': z_slots, - 'znames': znames, - 'leaf_names': leaf_names, - 'log_params': log_params, + "ok": True, + "tapes": tapes, + "n_leaves": n_leaves, + "n_states": n_s, + "z_slots": z_slots, + "znames": znames, + "leaf_names": leaf_names, + "log_params": log_params, } if exp_recast is not None: # relation rows dW = W log(r) d(tau/L): one tape output per (W, leaf) pair - rel = exp_recast['rel'] + rel = exp_recast["rel"] try: r_op, r_a, r_b, r_cnum, r_cden, r_out = _emit_tape_shared( - [rl[2] for rl in rel], [], leaf_slot, n_leaves, allow_sqrt=True) + [rl[2] for rl in rel], [], leaf_slot, n_leaves, allow_sqrt=True + ) except _NotRationalError: - return {'ok': False, 'why': 'an exponent that is not rational is not ' - 'supported by engine="modular"; try engine="symbolic"'} - out['exp_relation'] = {'W': [rl[0] for rl in rel], 'z': [rl[1] for rl in rel], - 'op': r_op, 'a': r_a, 'b': r_b, 'cnum': r_cnum, - 'cden': r_cden, 'out': r_out} - out['exp_atoms'] = exp_recast['atoms'] - out['exp_back'] = {'names': list(exp_recast['back'].keys()), - 'values': list(exp_recast['back'].values())} - out['exp_codim'] = exp_recast['codim'] + return { + "ok": False, + "why": 'an exponent that is not rational is not supported by engine="modular"; try engine="symbolic"', + } + out["exp_relation"] = { + "W": [rl[0] for rl in rel], + "z": [rl[1] for rl in rel], + "op": r_op, + "a": r_a, + "b": r_b, + "cnum": r_cnum, + "cden": r_cden, + "out": r_out, + } + out["exp_atoms"] = exp_recast["atoms"] + out["exp_back"] = {"names": list(exp_recast["back"].keys()), "values": list(exp_recast["back"].values())} + out["exp_codim"] = exp_recast["codim"] if equilibrate: - out['equilibrate'] = True - out['state_names'] = [_s(X) for X in S] - out['param_names'] = [_s(s) for s in params] - out['forcings'] = sorted(forcings) - out['real_state_names'] = [inv_solve_name.get(_s(X), _s(X)) - for X in S[:n_real]] - out['power_recast'] = power_recast - out['held_state_params'] = held_state_params - out['rest_aux'] = sorted(rest_aux) - out['rest_inverted'] = rest_inverted + out["equilibrate"] = True + out["state_names"] = [_s(X) for X in S] + out["param_names"] = [_s(s) for s in params] + out["forcings"] = sorted(forcings) + out["real_state_names"] = [inv_solve_name.get(_s(X), _s(X)) for X in S[:n_real]] + out["power_recast"] = power_recast + out["held_state_params"] = held_state_params + out["rest_aux"] = sorted(rest_aux) + out["rest_inverted"] = rest_inverted if joint_steady_state: - out['joint_steady_state'] = True + out["joint_steady_state"] = True # state z-columns (the free states that entered znames), for the joint # system to seed on-manifold and stack the df constraint rows - out['z_state_names'] = z_state_names + out["z_state_names"] = z_state_names elif power_recast: # transient free exponent: E and L are free-initial-value leaves; the analysis # stacks the recast relation rows and reports in real states + parameters - out['recast_transient'] = True - out['state_names'] = [_s(X) for X in S] - out['param_names'] = [_s(s) for s in params] - out['forcings'] = sorted(forcings) - out['real_state_names'] = [_s(X) for X in S[:n_real]] - out['power_recast'] = power_recast + out["recast_transient"] = True + out["state_names"] = [_s(X) for X in S] + out["param_names"] = [_s(s) for s in params] + out["forcings"] = sorted(forcings) + out["real_state_names"] = [_s(X) for X in S[:n_real]] + out["power_recast"] = power_recast # the recast atom coordinates (E and L), auxiliary to the physical report - out['recast_atom_names'] = ([rc['E'] for rc in power_recast] + - sorted(set(rc['L'] for rc in power_recast))) + out["recast_atom_names"] = [rc["E"] for rc in power_recast] + sorted(set(rc["L"] for rc in power_recast)) return out diff --git a/src/symident/sym/taylor.py b/src/symident/sym/taylor.py index 766d755..0b46eba 100644 --- a/src/symident/sym/taylor.py +++ b/src/symident/sym/taylor.py @@ -39,6 +39,7 @@ def _recip(b, n, p): def _root(a, q, n, p): """The q-th root of the series a from the smaller square or the unique odd root of a[0], then q A B' = A' B.""" from ..gfp import sqrt_mod + a0 = a[0] % p if q == 2: r = sqrt_mod(a0, p) @@ -114,7 +115,7 @@ def output_series(f, observables, point, order, p): x = {s: _const(point[s], order, p) for s in states} for k in range(order - 1): env = dict(point) - env.update({s: x[s][:k + 1] for s in states}) + env.update({s: x[s][: k + 1] for s in states}) memo = {} for s in states: c = _eval(f[s], env, k + 1, p, memo)[k] diff --git a/tests/spec_util.py b/tests/spec_util.py index da07b75..0d4af2c 100644 --- a/tests/spec_util.py +++ b/tests/spec_util.py @@ -21,9 +21,26 @@ def kwargs_of(spec): """Keyword arguments of symmetry_detection from a spec.""" s = {snake(k): v for k, v in spec.items()} kw = {} - for k in ("f", "g", "trafo", "conditions", "events", "reactions", "totals", "parameters", - "fixed", "forcings", "free_initial", "equilibrate", "reduce_cq", "reconstruct", - "verify", "positive", "sym_engine", "cores"): + for k in ( + "f", + "g", + "trafo", + "conditions", + "events", + "reactions", + "totals", + "parameters", + "fixed", + "forcings", + "free_initial", + "equilibrate", + "reduce_cq", + "reconstruct", + "verify", + "positive", + "sym_engine", + "cores", + ): if k in s and s[k] is not None: kw[k] = s[k] if "gauge_preference" in s: @@ -32,22 +49,25 @@ def kwargs_of(spec): if s.get("method") == "scaling": kw["scalings_only"] = True if s.get("control"): - c = {snake(k): (math.inf if v == "Inf" else v) for k, v in s["control"].items() - if k not in ("certifyPoly", "certifyPolyDeg", "timeout")} + c = { + snake(k): (math.inf if v == "Inf" else v) + for k, v in s["control"].items() + if k not in ("certifyPoly", "certifyPolyDeg", "timeout") + } kw["control"] = reconst_control(**c) return kw def env_of(g): """Environment switches of a spec under the SYMIDENT_ prefix.""" - return {"SYMIDENT_" + k.split("_SYM_", 1)[1]: str(v) for k, v in (g.get("env") or {}).items() - if str(v) and "_SYM_" in k} + return { + "SYMIDENT_" + k.split("_SYM_", 1)[1]: str(v) for k, v in (g.get("env") or {}).items() if str(v) and "_SYM_" in k + } def options_of(g): """state.options() of a spec.""" - return {snake(k.rsplit(".", 1)[-1]): v for k, v in (g.get("options") or {}).items() - if v is not None} + return {snake(k.rsplit(".", 1)[-1]): v for k, v in (g.get("options") or {}).items() if v is not None} def load(path): @@ -58,12 +78,22 @@ def load(path): def obj_of(o): syms = [] for d in o["symmetries"]: - syms.append({"type": d["type"], "generator": d.get("generator"), "weights": d.get("weights"), - "support": d.get("support") or list((d.get("generator") or {}).keys()), - "degree": d.get("degree")}) - return {"method": o.get("method"), "identifiable": o.get("identifiable"), "gauge": o.get("gauge"), - "info": {"coordinates": o["info"].get("coordinates"), - "model_exprs": o["info"].get("modelExprs")}, "symmetries": syms} + syms.append( + { + "type": d["type"], + "generator": d.get("generator"), + "weights": d.get("weights"), + "support": d.get("support") or list((d.get("generator") or {}).keys()), + "degree": d.get("degree"), + } + ) + return { + "method": o.get("method"), + "identifiable": o.get("identifiable"), + "gauge": o.get("gauge"), + "info": {"coordinates": o["info"].get("coordinates"), "model_exprs": o["info"].get("modelExprs")}, + "symmetries": syms, + } def kw_of(a): diff --git a/tests/test_certificates.py b/tests/test_certificates.py index 97ba44d..8e25d95 100644 --- a/tests/test_certificates.py +++ b/tests/test_certificates.py @@ -9,24 +9,38 @@ def _rotation(value, method="replace"): # the observable moves only in the segment that an event value reading a state starts - return si.Model({"A": "u*D", "D": "-k*A*u", "B": "c*(1 - u)", "u": "0"}, {"y": "A"}, - trafo={"A": "0", "D": "0", "B": "0", "u": "0"}, - events=[{"var": "u", "time": 0, "value": "0", "method": "replace"}, - {"var": "A", "time": 5, "value": value, "method": method}, - {"var": "u", "time": 5, "value": "1", "method": "replace"}]) + return si.Model( + {"A": "u*D", "D": "-k*A*u", "B": "c*(1 - u)", "u": "0"}, + {"y": "A"}, + trafo={"A": "0", "D": "0", "B": "0", "u": "0"}, + events=[ + {"var": "u", "time": 0, "value": "0", "method": "replace"}, + {"var": "A", "time": 5, "value": value, "method": method}, + {"var": "u", "time": 5, "value": "1", "method": "replace"}, + ], + ) def _moving_gap(): - return si.Model({"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, {"y": "s*x"}, - trafo={"w": "0", "v": "0", "u": "0"}, - events=[{"var": "u", "time": 0, "value": "0", "method": "replace"}, - {"var": "u", "time": "tau", "value": "1", "method": "replace"}]) + return si.Model( + {"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, + {"y": "s*x"}, + trafo={"w": "0", "v": "0", "u": "0"}, + events=[ + {"var": "u", "time": 0, "value": "0", "method": "replace"}, + {"var": "u", "time": "tau", "value": "1", "method": "replace"}, + ], + ) def _sum_after_dose(): # a direction that no scaling proves, behind a gap - return si.Model({"x": "-k*x"}, {"y": "(a + b)*x"}, trafo={"x": "1"}, - events=[{"var": "x", "time": 2, "value": "1", "method": "add"}]) + return si.Model( + {"x": "-k*x"}, + {"y": "(a + b)*x"}, + trafo={"x": "1"}, + events=[{"var": "x", "time": 2, "value": "1", "method": "add"}], + ) def test_an_event_value_that_reads_a_state_keeps_the_lie_certificate_sound(): @@ -39,6 +53,7 @@ def test_an_event_value_that_reads_a_state_keeps_the_lie_certificate_sound(): def test_a_certified_order_below_the_scanned_rank_keeps_the_scan(monkeypatch): import symident.detection.observability.analysis as an + monkeypatch.setattr(an, "lie_certificate", lambda segs, *a, **k: [1] * len(segs)) r = si.detect(_rotation("B + d", "add")) assert (r.rank, r.dim) == (2, 3) @@ -48,6 +63,7 @@ def test_a_certified_order_below_the_scanned_rank_keeps_the_scan(monkeypatch): def test_the_affine_space_after_an_event_is_a_basis(): from symident.detection.fields import event_space + p = PRIMES[0] V = np.array([[1, 1, 0], [0, 1, 0]], dtype=np.int64) # a replace by a value that reads no state resets the target @@ -77,6 +93,7 @@ def test_a_used_gap_bound_is_at_least_the_rank(): def test_a_rank_above_the_gap_bound_certifies_nothing(monkeypatch): import symident.detection.gapcert as gc + monkeypatch.setattr(gc, "gap_bound", lambda *a, **k: {"bound": 1, "why": None, "terms": 0.0}) r = si.detect(_sum_after_dose()) assert r.info["gap_certified"] is False @@ -86,10 +103,12 @@ def test_a_rank_above_the_gap_bound_certifies_nothing(monkeypatch): CERTIFIED = [ ({"A": "-k1*A", "B": "k1*A - k2*B"}, {"y": "s*B"}, {"A": "A0", "B": "0"}), ({"x": "th"}, {"y": "x^5"}, {"x": "0"}), - ({"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, {"y": "x2"}, - {"x1": "1", "x2": "0", "x3": "0"}), - ({"x1": "a - (d + f)*x1", "x2": "b - (d + f)*x2", "f": "-c*f"}, {"y": "x1 + x2"}, - {"x1": "a/d", "x2": "b/d", "f": "1"}), + ({"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, {"y": "x2"}, {"x1": "1", "x2": "0", "x3": "0"}), + ( + {"x1": "a - (d + f)*x1", "x2": "b - (d + f)*x2", "f": "-c*f"}, + {"y": "x1 + x2"}, + {"x1": "a/d", "x2": "b/d", "f": "1"}, + ), ] @@ -102,11 +121,17 @@ def test_certified_orders_have_an_error_bound(f, g, trafo): def test_a_verified_rank_includes_the_order_bound(): f = {"A": "k1 - d1*A + kx*X", "B": "k2*A - d2*B", "X": "kp*plasmid - dx*X"} - rest = [{"X": f"kp*{u}/dx", "A": f"(k1 + kx*kp*{u}/dx)/d1", "B": f"k2*(k1 + kx*kp*{u}/dx)/(d1*d2)", - "plasmid": str(u)} for u in (0, 1)] - m = si.Model(f, {"yA": "s*(A + X)", "yB": "B"}, trafo=rest, - conditions={"rows": ["ctrl", "oe"], "cols": {"dose": [1, 1]}}, - events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}]) + rest = [ + {"X": f"kp*{u}/dx", "A": f"(k1 + kx*kp*{u}/dx)/d1", "B": f"k2*(k1 + kx*kp*{u}/dx)/(d1*d2)", "plasmid": str(u)} + for u in (0, 1) + ] + m = si.Model( + f, + {"yA": "s*(A + X)", "yB": "B"}, + trafo=rest, + conditions={"rows": ["ctrl", "oe"], "cols": {"dose": [1, 1]}}, + events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}], + ) r = si.detect(m, reconstruct=True) st, ob = r.info["rank_status"], r.info["order_bound"] assert st["status"] == "verified" and ob is not None and ob > 0 @@ -116,8 +141,12 @@ def test_a_verified_rank_includes_the_order_bound(): def test_a_free_exponent_of_a_positive_state_keeps_the_order_bound(): - m = si.Model({"x": "v0 + b*v1 - V*x^n/(K^n + x^n)", "z": "V*x^n/(K^n + x^n) - e*z"}, {"y": "s*z"}, - trafo={"x": "x0", "z": "z0"}, positive=True) + m = si.Model( + {"x": "v0 + b*v1 - V*x^n/(K^n + x^n)", "z": "V*x^n/(K^n + x^n) - e*z"}, + {"y": "s*z"}, + trafo={"x": "x0", "z": "z0"}, + positive=True, + ) r = si.detect(m, reconstruct=True) assert r.info["lie_certified"] and r.info["order_bound"] is not None and r.info["order_bound_why"] is None assert r.info["rank_status"]["status"] == "proven" @@ -127,6 +156,7 @@ def test_a_free_exponent_of_a_positive_state_keeps_the_order_bound(): def test_a_start_at_rest_certifies_its_orders_modulo_the_verification_prime(monkeypatch): from symident.detection.observability.joint import JointSystem from symident.gfp import verify_prime + m = si.Model({"x": "k1 - k2*x*z", "z": "k3 - k4*z"}, {"y": "s*x"}) r = si.detect(m, equilibrate=True) assert r.info["order_bound_why"] is None and 0 < r.info["order_bound"] < 1e-5 @@ -134,6 +164,7 @@ def test_a_start_at_rest_certifies_its_orders_modulo_the_verification_prime(monk def none_at_q(self, point, p, ci): return None if p == verify_prime() else orig(self, point, p, ci) + monkeypatch.setattr(JointSystem, "solve_direct", none_at_q) r = si.detect(m, equilibrate=True) assert r.info["order_bound"] is None @@ -144,6 +175,7 @@ def test_the_order_bound_multiplies_by_the_resting_points_drawn(monkeypatch): from symident.detection.observability.analysis import Analysis from symident.detection.observability.joint import JointSystem from symident.gfp import verify_prime + m = si.Model({"x": "k1 - k2*x*z", "z": "k3 - k4*z"}, {"y": "s*x"}) r0 = si.detect(m, equilibrate=True) assert r0.info["order_draws"] == 1 and r0.info["order_bound"] > 0 @@ -160,6 +192,7 @@ def solve_direct(self, point, p, ci): misses["left"] -= 1 return None return solve(self, point, p, ci) + monkeypatch.setattr(Analysis, "_cert_segments", cert_segments) monkeypatch.setattr(JointSystem, "solve_direct", solve_direct) r = si.detect(m, equilibrate=True) @@ -169,6 +202,7 @@ def solve_direct(self, point, p, ci): def test_each_term_of_the_order_bound_multiplies_by_the_points_drawn_for_it(): from symident.detection.fields import _sz_term + deg = {"mds": [(2, 1, [(1, 2)]), (1, 2, [(1, 1)])], "d0s": [1, 2]} one = _sz_term(deg, 4, 5) # without outputs only the closure stops remain @@ -181,6 +215,7 @@ def test_each_term_of_the_order_bound_multiplies_by_the_points_drawn_for_it(): def test_the_degree_on_a_resting_variety_multiplies_by_the_bezout_numbers(): from symident.detection.bound import balance_degrees, rest_identity_degree + assert balance_degrees(["-d*x**2 + (kb - d*K + v)*x + kb*K", "k*x - c*z"]) == (6, 3) assert balance_degrees([]) == (1, 0) assert balance_degrees(["exp(a)*x - b"]) is None @@ -208,6 +243,7 @@ def test_a_known_input_leaves_its_jets_out_of_the_certificate(): def test_verification_points_are_uniform_modulo_q(): from symident import session from symident.gfp import uniform_point + q = 1000000007 with session.opened({}): pts = np.concatenate([uniform_point(1000, q, seed=s) for s in range(4)]) @@ -218,6 +254,7 @@ def test_verification_points_are_uniform_modulo_q(): def test_initial_values_enter_the_degree_over_their_common_denominator(): from symident.detection.bound import _model_degrees + md = _model_degrees((("x", "-k*x"), ("z", "-k*z")), (("y", "x + z"),), (("x", "1/b"), ("z", "1/d"))) assert md[3] == 2 @@ -225,6 +262,7 @@ def test_initial_values_enter_the_degree_over_their_common_denominator(): def test_a_unit_fill_is_checked_at_the_verification_points(monkeypatch): import symident.detection.observability.analysis as an from symident.detection.observability.reconstruct import Reconstruction + monkeypatch.setattr(Reconstruction, "run", lambda self: []) m = si.Model({"x": "-k*x", "z": "-a*z"}, {"y": "x"}, trafo={"x": "1", "z": "1"}) ctrl = si.reconst_control(exact_proof=False) @@ -238,6 +276,7 @@ def test_a_unit_fill_is_checked_at_the_verification_points(monkeypatch): def test_a_homotopy_direction_is_checked_at_two_points(monkeypatch): import symident.detection.observability.homotopy as hm + passed = [] orig = hm.in_kernel @@ -245,9 +284,13 @@ def counted(*a, **k): ok = orig(*a, **k) passed.extend([1] if ok else []) return ok + monkeypatch.setattr(hm, "in_kernel", counted) - m = si.Model({"x": "v*u*x/(K + x) + kb - d*x", "z": "k*x - c*z"}, {"y": "s*z"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = si.Model( + {"x": "v*u*x/(K + x) + kb - d*x", "z": "k*x - c*z"}, + {"y": "s*z"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) r = si.detect(m, equilibrate=True, reconstruct=True, control=si.reconst_control(homotopy=True)) hom = [s for s in r.symmetries if (s.route or "").startswith("homotopy")] assert len(hom) == 2 and len(passed) >= 2 * len(hom) @@ -255,8 +298,13 @@ def counted(*a, **k): def test_a_skipped_verification_point_widens_the_bound(monkeypatch): import symident.detection.verify as vf - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "s*x2"}, - trafo={"x1": "D", "x2": "0"}, conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + {"y": "s*x2"}, + trafo={"x1": "D", "x2": "0"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) with si.switches(NOFIELDS=True): r0 = si.detect(m, reconstruct=True) orig, calls = vf._in_nullspace_at, [] @@ -264,6 +312,7 @@ def test_a_skipped_verification_point_widens_the_bound(monkeypatch): def skip_first(*a, **k): calls.append(1) return None if len(calls) == 1 else orig(*a, **k) + monkeypatch.setattr(vf, "_in_nullspace_at", skip_first) with si.switches(NOFIELDS=True): r1 = si.detect(m, reconstruct=True) @@ -276,6 +325,7 @@ def skip_first(*a, **k): def _has_msolve(): from symident.sym.msolve import MsolveMissingError, _msolve_binary + try: _msolve_binary() except MsolveMissingError: @@ -301,6 +351,7 @@ def test_balances_without_a_resting_state_raise_with_an_error_bound(): from symident.errors import InputError from symident.sym.restcheck import modular_decision + # z rests at k3/k4, where the balance of x is k1 - k2*k3/k4, nonzero for generic values m = si.Model({"x": "k1 - k2*z", "z": "k3 - k4*z"}, {"y": "s*x"}) with pytest.raises(InputError, match="error bound"): diff --git a/tests/test_chain_rows.py b/tests/test_chain_rows.py index b300418..38ea061 100644 --- a/tests/test_chain_rows.py +++ b/tests/test_chain_rows.py @@ -26,9 +26,17 @@ def chain_kernel(self, idx, point, p, Nt, Mtot, threads, zs=None): o = kernel(self, idx, point, p, Nt, Mtot, threads, zs) zs = self.z_slots if zs is None else np.asarray(zs, dtype=np.int64) cols = self.chain_columns(idx, zs) - d = _core.sym_obs_null_chain([self.chain_tapes(idx)], self.n_leaves, self.n_states, - zs if cols is None else zs[cols], np.asarray(point, dtype=np.int64), p, - int(Nt), int(Mtot), 1) + d = _core.sym_obs_null_chain( + [self.chain_tapes(idx)], + self.n_leaves, + self.n_states, + zs if cols is None else zs[cols], + np.asarray(point, dtype=np.int64), + p, + int(Nt), + int(Mtot), + 1, + ) _same(o, cx.embed_columns(d, cols, len(zs))) seen["kernels"] += 1 seen["orders"].add((len(idx), int(Mtot))) @@ -37,8 +45,16 @@ def chain_kernel(self, idx, point, p, Nt, Mtot, threads, zs=None): def chain_rows(self, idx, point, p, Nt, Mtot, threads, zs, cols): e = rows(self, idx, point, p, Nt, Mtot, threads, zs, cols) if e is not None and e["ranks"] is not None: - r = _core.sym_obs_chain_rank_profile(self.chain_tapes(idx), self.n_leaves, self.n_states, - zs if cols is None else zs[cols], point, p, e["Nt"], 1) + r = _core.sym_obs_chain_rank_profile( + self.chain_tapes(idx), + self.n_leaves, + self.n_states, + zs if cols is None else zs[cols], + point, + p, + e["Nt"], + 1, + ) np.testing.assert_array_equal(np.asarray(r["ranks"]), e["ranks"]) seen["profiles"] += 1 return e @@ -51,11 +67,13 @@ def chain_rows(self, idx, point, p, Nt, Mtot, threads, zs, cols): def test_kept_rows_give_the_kernels_of_events_and_single_segments(checked): # two conditions with a dose, one without: chains of two segments and of one segment, a scaling and a # gap order past 0 - model = si.Model({"x": "-k1*x + u", "y": "k2*x - k3*y", "u": "-k4*u"}, {"obs": "s*y"}, - trafo=[{"x": "0", "y": "0", "u": "u0"}, {"x": "0", "y": "0", "u": "u0"}, - {"x": "x0", "y": "0", "u": "0"}], - conditions={"rows": ["a", "b", "c"], "cols": {"dose": [1, 2, 0]}}, - events=[{"var": "x", "time": 1, "value": "dose", "method": "add", "cond": [0, 1]}]) + model = si.Model( + {"x": "-k1*x + u", "y": "k2*x - k3*y", "u": "-k4*u"}, + {"obs": "s*y"}, + trafo=[{"x": "0", "y": "0", "u": "u0"}, {"x": "0", "y": "0", "u": "u0"}, {"x": "x0", "y": "0", "u": "0"}], + conditions={"rows": ["a", "b", "c"], "cols": {"dose": [1, 2, 0]}}, + events=[{"var": "x", "time": 1, "value": "dose", "method": "add", "cond": [0, 1]}], + ) r = si.detect(model) assert checked["kernels"] > 0 and checked["profiles"] > 0 assert {n for n, _ in checked["orders"]} == {1, 2} @@ -63,14 +81,19 @@ def test_kept_rows_give_the_kernels_of_events_and_single_segments(checked): def test_rows_of_a_lower_order_are_a_selection(): - model = si.Model({"x": "-k1*x*y", "y": "k1*x*y - k2*y"}, {"obs": "y"}, trafo={"x": "x0", "y": "y0"}, - events=[{"var": "x", "time": 2, "value": "1", "method": "add"}]) + model = si.Model( + {"x": "-k1*x*y", "y": "k1*x*y - k2*y"}, + {"obs": "y"}, + trafo={"x": "x0", "y": "y0"}, + events=[{"var": "x", "time": 2, "value": "1", "method": "add"}], + ) calls = {} orig = _core.sym_obs_null_chain def spy_null_chain(chains, *a, **k): calls["args"] = (chains, a) return orig(chains, *a, **k) + try: _core.sym_obs_null_chain = spy_null_chain si.detect(model) @@ -83,6 +106,7 @@ def spy_null_chain(chains, *a, **k): assert e["plain"] for nt in (3, 7, 12): sel, ssel = np.asarray(e["tag"]) <= nt, np.asarray(e["stag"]) <= nt - o = _core.sym_chain_reduce(np.asarray(e["rows"])[sel], np.asarray(e["srows"])[ssel], len(zs), - int(e["N"]), p) + o = _core.sym_chain_reduce( + np.asarray(e["rows"])[sel], np.asarray(e["srows"])[ssel], len(zs), int(e["N"]), p + ) _same(o, _core.sym_obs_null_chain([chain], nl, ns, zs, point, p, nt, M, 1)) diff --git a/tests/test_detect.py b/tests/test_detect.py index 54acb42..39a91a7 100644 --- a/tests/test_detect.py +++ b/tests/test_detect.py @@ -37,8 +37,10 @@ def detect(odes=None, observables=None, **kw): def network(*reactions): """Reaction network from (educts, products, rate) triples; "" or "0" is no species.""" + def side(s): return [x.strip() for x in s.split("+") if x.strip() not in ("", "0")] + species = [] for ed, pr, _ in reactions: for s in side(ed) + side(pr): @@ -101,13 +103,18 @@ def generator_strings(res): def chain(): - return network(("", "A", "kin"), ("A", "B", "k1 * A"), ("B", "C", "k2 * B"), - ("C", "D", "k3 * C"), ("D", "", "k4 * D")) + return network( + ("", "A", "kin"), ("A", "B", "k1 * A"), ("B", "C", "k2 * B"), ("C", "D", "k3 * C"), ("D", "", "k4 * D") + ) def hill_michaelis(): - return network(("0", "FB", "k_pr_FB"), ("FB", "0", "d_FB * FB"), - ("0", "x", "k_pr_x * K^n / (K^n + FB^n)"), ("x", "0", "d_x * x")) + return network( + ("0", "FB", "k_pr_FB"), + ("FB", "0", "d_FB * FB"), + ("0", "x", "k_pr_x * K^n / (K^n + FB^n)"), + ("x", "0", "d_x * x"), + ) def pool_model(): @@ -193,8 +200,7 @@ def test_reconstruct_deep_chain(): def test_fixed_parameter_removes_symmetry(): free = detect(reactions=canonical(), observables={"Aobs": "alpha * A"}, reconstruct=True) - fixed = detect(reactions=canonical(), observables={"Aobs": "alpha * A"}, reconstruct=True, - fixed=["alpha"]) + fixed = detect(reactions=canonical(), observables={"Aobs": "alpha * A"}, reconstruct=True, fixed=["alpha"]) assert fixed.dim == free.dim - 1 assert len(fixed.symmetries) < len(free.symmetries) assert "alpha" not in supports(fixed) @@ -210,9 +216,14 @@ def test_steady_state_initial_condition(): def test_pre_equilibrated_known_dose(): def ident(method): - return detect({"x": "b - a*x"}, {"y": "s*x"}, trafo={"x": "b/a"}, - events=[event("x", 0, "dose", method)], - conditions=grid(["stim"], dose=[2])).identifiable + return detect( + {"x": "b - a*x"}, + {"y": "s*x"}, + trafo={"x": "b/a"}, + events=[event("x", 0, "dose", method)], + conditions=grid(["stim"], dose=[2]), + ).identifiable + # an absolute dose fixes the scale, a relative one does not assert ident("replace") is True assert ident("add") is True @@ -226,8 +237,15 @@ def ident(method): def test_dose_on_a_state_under_a_free_exponent(time): # an add event on a state analyzed in log coordinates jumps the logarithm and every power of the state def run(value, fixed=("D",)): - return detect(_FREE_POWER, {"y": "X/V"}, trafo={"X": "B*V"}, events=[event("X", time, value, "add")], - fixed=list(fixed), reconstruct=True) + return detect( + _FREE_POWER, + {"y": "X/V"}, + trafo={"X": "B*V"}, + events=[event("X", time, value, "add")], + fixed=list(fixed), + reconstruct=True, + ) + r = run("D") assert (r.rank, r.dim, r.identifiable) == (4, 4, True) r = run("D*V") @@ -246,8 +264,10 @@ def test_dose_on_a_state_under_a_free_exponent_with_a_free_initial_value(): @pytest.mark.parametrize("time", [0, 2]) def test_dose_at_rest_on_a_state_under_a_free_exponent(time): def run(value, method="add"): - return detect(_FREE_POWER, {"y": "X/V"}, events=[event("X", time, value, method)], fixed=["D"], - equilibrate=True) + return detect( + _FREE_POWER, {"y": "X/V"}, events=[event("X", time, value, method)], fixed=["D"], equilibrate=True + ) + r = run("D") assert (r.rank, r.dim, r.identifiable) == (4, 4, True) r = run("D*V") @@ -278,8 +298,13 @@ def test_initial_value_with_an_offset_on_a_state_under_a_free_exponent(): def test_event_value_reads_the_state_at_the_event(): # exp() of a state in a later event value is the exponential of the state at the event, not at the start - r = detect({"x": "-a*x", "z": "-b*z"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}, - events=[event("x", 1, "exp(z)")], reconstruct=True) + r = detect( + {"x": "-a*x", "z": "-b*z"}, + {"y": "x"}, + trafo={"x": "x0", "z": "z0"}, + events=[event("x", 1, "exp(z)")], + reconstruct=True, + ) assert (r.rank, r.dim) == (3, 4) and dirset(r) == ["b+z0"] @@ -292,8 +317,13 @@ def test_dose_on_a_state_inside_a_trigonometric_function(value, method): @pytest.mark.parametrize("fn", ["sin", "cos"]) def test_trigonometric_event_value_reads_the_state_at_the_event(fn): - r = detect({"x": "-a*x", "z": "-b*z"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}, - events=[event("x", 1, f"{fn}(z)")], reconstruct=True) + r = detect( + {"x": "-a*x", "z": "-b*z"}, + {"y": "x"}, + trafo={"x": "x0", "z": "z0"}, + events=[event("x", 1, f"{fn}(z)")], + reconstruct=True, + ) assert (r.rank, r.dim) == (3, 4) and dirset(r) == ["b+z0"] @@ -304,8 +334,7 @@ def test_equilibrate_matches_explicit_steady_state(): assert res.dim == 3 # every direction is a null direction of grad(s*b/a) in (a, b, s) vals = {"a": 2, "b": 3, "s": 5} - grad = {"a": -vals["s"] * vals["b"] / vals["a"] ** 2, "b": vals["s"] / vals["a"], - "s": vals["b"] / vals["a"]} + grad = {"a": -vals["s"] * vals["b"] / vals["a"] ** 2, "b": vals["s"] / vals["a"], "s": vals["b"] / vals["a"]} for d in res.symmetries: v = tangent(d, vals, ["a", "b", "s"]) assert sum(grad[k] * v[k] for k in grad) == pytest.approx(0, abs=1e-9) @@ -333,8 +362,13 @@ def test_equilibrate_ignores_state_trafo(): def test_equilibrate_t0_dose(): - res = detect({"x": "b - a*x"}, {"y": "s*x"}, equilibrate=True, - events=[event("x", 0, "dose", "replace")], conditions=grid(["stim"], dose=[2])) + res = detect( + {"x": "b - a*x"}, + {"y": "s*x"}, + equilibrate=True, + events=[event("x", 0, "dose", "replace")], + conditions=grid(["stim"], dose=[2]), + ) assert res.identifiable is True assert res.rank == 3 res0 = detect({"x": "b - a*x"}, {"y": "s*x"}, equilibrate=True) @@ -358,15 +392,22 @@ def test_a_reversible_net_rate_drains_neither_side(): assert _zero_states([[-1, 1]], ["A", "B"], ["(kf * A - kb * B)*(1)"], [])[0] == [] assert _zero_states([[-1, 1]], ["A", "B"], ["(Vf*A - Vr*B)/(1 + A + B)"], [])[0] == [] assert sorted(_zero_states([[-1, 1], [0, -1]], ["A", "B"], ["kf*A - kb*B", "kd*B"], [])[0]) == ["A", "B"] - m = si.Model({"A": "-(kf*A - kb*B)", "B": "kf*A - kb*B"}, {"y": "A"}, equilibrate=True, reduce_cq=True, - reactions={"species": ["A", "B"], "smatrix": [[-1, 1]], "rates": ["kf*A - kb*B"]}, - totals={"T": "A + B"}, trafo={"kf": "kf", "kb": "kb", "T": "4"}) + m = si.Model( + {"A": "-(kf*A - kb*B)", "B": "kf*A - kb*B"}, + {"y": "A"}, + equilibrate=True, + reduce_cq=True, + reactions={"species": ["A", "B"], "smatrix": [[-1, 1]], "rates": ["kf*A - kb*B"]}, + totals={"T": "A + B"}, + trafo={"kf": "kf", "kb": "kb", "T": "4"}, + ) res = si.detect(m, cores=1) assert res.rank == 1 and [sorted(d["support"]) for d in res.symmetries] == [["kb", "kf"]] def test_a_drained_reaction_with_several_reactants_forces_no_zero(): from symident.detection.core import _ode_zeros + # a drained reaction with two reactants rests where one of them is zero assert _zero_states([[-1, -1]], ["A", "B"], ["k*A*B"], [])[0] == [] assert _ode_zeros({"A": "-k*A*B", "B": "-k*A*B"}, [])[0] == [] @@ -384,16 +425,17 @@ def test_a_resting_branch_is_named_and_analyzed(): assert "A = 0" in b and "B = 0" in b # the branch taken is analyzed like the explicit model of that branch assert "B" in r.info["coordinates"] - explicit = detect(reactions=rx, observables=obs, inputs=["u", "w"], events=ev, conditions=cg, - trafo={"A": "0"}) + explicit = detect(reactions=rx, observables=obs, inputs=["u", "w"], events=ev, conditions=cg, trafo={"A": "0"}) assert (r.rank, r.dim) == (explicit.rank, explicit.dim) def test_recast_arguments_without_declared_sign_are_noted(): # the rank is generic: an argument without declared sign gives the same result and a note - for kw, pos in [(dict(f={"x": "-k*x"}, g={"y": "log(K)*x"}), ["k", "x"]), - (dict(f={"x": "-k*x^n"}, g={"y": "x"}), ["k", "n"]), - (dict(f={"x": "-k*x"}, g={"y": "x"}, trafo={"x": "sqrt(a)"}), ["k", "x"])]: + for kw, pos in [ + (dict(f={"x": "-k*x"}, g={"y": "log(K)*x"}), ["k", "x"]), + (dict(f={"x": "-k*x^n"}, g={"y": "x"}), ["k", "n"]), + (dict(f={"x": "-k*x"}, g={"y": "x"}, trafo={"x": "sqrt(a)"}), ["k", "x"]), + ]: free = detect(kw["f"], kw["g"], trafo=kw.get("trafo"), positive=pos) signed = detect(kw["f"], kw["g"], trafo=kw.get("trafo"), positive=True) assert (free.rank, free.dim) == (signed.rank, signed.dim) @@ -411,6 +453,7 @@ def test_an_event_scaling_is_an_exact_scaling_without_reconstruct(): def test_a_peeled_scaling_is_exact_only_when_the_whole_model_proves_it(monkeypatch): import symident.detection.observability.analysis as an + monkeypatch.setattr(an, "exact_scaling_set", lambda multi, fixed: []) # with the proofs by lifts off, only the scalings of the whole model make a peeled scaling exact with si.switches(NOFIELDS=True): @@ -420,18 +463,37 @@ def test_a_peeled_scaling_is_exact_only_when_the_whole_model_proves_it(monkeypat def test_condition_zero_state_held_at_zero(): # the equilibrate verdict matches the explicit steady state given per condition - rx = network(("", "A", "k1"), ("A", "", "d1*A"), ("", "B", "k2*A"), ("B", "", "d2*B"), - ("", "X", "kp*plasmid"), ("X", "", "dx*X"), ("", "A", "kx*X")) + rx = network( + ("", "A", "k1"), + ("A", "", "d1*A"), + ("", "B", "k2*A"), + ("B", "", "d2*B"), + ("", "X", "kp*plasmid"), + ("X", "", "dx*X"), + ("", "A", "kx*X"), + ) g = {"yA": "s*(A + X)", "yB": "B"} ev = [event("A", 0, "dose", "add")] - eq = detect(reactions=rx, observables=g, conditions=grid(["ctrl", "oe"], plasmid=[0, 1], dose=[1, 1]), - events=ev, equilibrate=True, reduce_cq=True) + eq = detect( + reactions=rx, + observables=g, + conditions=grid(["ctrl", "oe"], plasmid=[0, 1], dose=[1, 1]), + events=ev, + equilibrate=True, + reduce_cq=True, + ) def ss(pl): - return {"X": f"kp*{pl}/dx", "A": f"(k1 + kx*kp*{pl}/dx)/d1", - "B": f"k2*(k1 + kx*kp*{pl}/dx)/(d1*d2)", "plasmid": str(pl)} - ex = detect(reactions=rx, observables=g, trafo=[ss(0), ss(1)], events=ev, - conditions=grid(["ctrl", "oe"], dose=[1, 1])) + return { + "X": f"kp*{pl}/dx", + "A": f"(k1 + kx*kp*{pl}/dx)/d1", + "B": f"k2*(k1 + kx*kp*{pl}/dx)/(d1*d2)", + "plasmid": str(pl), + } + + ex = detect( + reactions=rx, observables=g, trafo=[ss(0), ss(1)], events=ev, conditions=grid(["ctrl", "oe"], dose=[1, 1]) + ) assert eq.rank == ex.rank assert eq.identifiable == ex.identifiable assert dirset(eq) == dirset(ex) @@ -443,8 +505,8 @@ def test_kernel_thread_count_invariance(): cg = grid(["c1", "c2", "c3", "c4"], var_u=[0, 1, 0, 1], dose=[1, 1, 2, 2]) def run(cores): - return detect(f, {"y": "s*A"}, events=ev, conditions=cg, inputs=["u"], reconstruct=True, - cores=cores) + return detect(f, {"y": "s*A"}, events=ev, conditions=cg, inputs=["u"], reconstruct=True, cores=cores) + serial, parallel = run(1), run(2) assert serial.rank == parallel.rank assert serial.identifiable == parallel.identifiable @@ -462,10 +524,11 @@ def test_michaelis_menten_enzyme(): pt = {"S": 2, "Etot": 3, "Km": 5, "s": 7, "kcat": 11} for d in res.symmetries: v = tangent(d, pt, list(pt)) - dinv = [pt["s"] * v["S"] + pt["S"] * v["s"], - pt["s"] * v["Km"] + pt["Km"] * v["s"], - pt["kcat"] * pt["Etot"] * v["s"] + pt["s"] * pt["Etot"] * v["kcat"] - + pt["s"] * pt["kcat"] * v["Etot"]] + dinv = [ + pt["s"] * v["S"] + pt["S"] * v["s"], + pt["s"] * v["Km"] + pt["Km"] * v["s"], + pt["kcat"] * pt["Etot"] * v["s"] + pt["s"] * pt["Etot"] * v["kcat"] + pt["s"] * pt["kcat"] * v["Etot"], + ] assert dinv == pytest.approx([0, 0, 0], abs=1e-9) @@ -504,8 +567,7 @@ def test_scalings_peeled_past_interpolation_cap(): def test_two_moieties_scaling_and_general(): - rx = network(("A1", "B1", "k1 * A1"), ("B1", "A1", "k2 * B1"), - ("A2", "B2", "k3 * A2"), ("B2", "A2", "k4 * B2")) + rx = network(("A1", "B1", "k1 * A1"), ("B1", "A1", "k2 * B1"), ("A2", "B2", "k3 * A2"), ("B2", "A2", "k4 * B2")) res = detect(reactions=rx, observables={"y1": "s * A1", "y2": "s * A2"}, reconstruct=True) assert res.rank == 6 assert res.dim == 9 @@ -526,13 +588,27 @@ def test_two_moieties_scaling_and_general(): def test_equilibrate_free_hill_exponent(): ev = [event("u", -1, "1", "replace")] cond = grid(["stim"], kin=["kin"]) - r = detect({"p": "kpr/(1+kinh*p^nhill) - dp*p + kin*u", "u": "0"}, {"y": "s*p"}, - equilibrate=True, inputs=["u"], events=ev, conditions=cond, reconstruct=False) + r = detect( + {"p": "kpr/(1+kinh*p^nhill) - dp*p + kin*u", "u": "0"}, + {"y": "s*p"}, + equilibrate=True, + inputs=["u"], + events=ev, + conditions=cond, + reconstruct=False, + ) assert "nhill" not in supports(r) assert r.dim == 6 # a fractional-root steady state: a scaling with weight 1 - q on dp - r2 = detect({"x": "kpr - dp*x^q + kin*u", "u": "0"}, {"y": "s*x"}, - equilibrate=True, inputs=["u"], events=ev, conditions=cond, reconstruct=True) + r2 = detect( + {"x": "kpr - dp*x^q + kin*u", "u": "0"}, + {"y": "s*x"}, + equilibrate=True, + inputs=["u"], + events=ev, + conditions=cond, + reconstruct=True, + ) assert len(r2.symmetries) == 1 d2 = r2.symmetries[0] assert d2["explicit"] is True @@ -559,12 +635,15 @@ def test_equilibrate_free_hill_exponent(): assert not any("log(" in x for x in gen3) -@pytest.mark.parametrize("rhs, n_dirs", [ - ("k1*x^N/((2*K)^N + x^N) - k2*x", 4), - ("k1*x^N/(2^N*K^N + x^N) - k2*x", 4), - ("k1*x^N/((3/2*K)^N + x^N) - k2*x", 4), - ("k1*(2*x)^N - k2*x + k3", 4), -]) +@pytest.mark.parametrize( + "rhs, n_dirs", + [ + ("k1*x^N/((2*K)^N + x^N) - k2*x", 4), + ("k1*x^N/(2^N*K^N + x^N) - k2*x", 4), + ("k1*x^N/((3/2*K)^N + x^N) - k2*x", 4), + ("k1*(2*x)^N - k2*x + k3", 4), + ], +) @pytest.mark.parametrize("n", ["n", "zz", "a1"]) def test_equilibrate_number_base_power(rhs, n_dirs, n): # a power b^N of a number joins the base of K^N or is held as a constant, and the names stay @@ -578,8 +657,13 @@ def test_equilibrate_number_base_power(rhs, n_dirs, n): def test_equilibrate_hill_closed_form_recast(): # a constant state given per condition rests at that value in each condition - r = detect({"p": "kpr/(1+kinh*p^nhill) - dp*p + kin*u", "u": "0"}, {"y": "s*p"}, - equilibrate=True, conditions=grid(["ctrl", "stim"], u=[0, 1]), reconstruct=True) + r = detect( + {"p": "kpr/(1+kinh*p^nhill) - dp*p + kin*u", "u": "0"}, + {"y": "s*p"}, + equilibrate=True, + conditions=grid(["ctrl", "stim"], u=[0, 1]), + reconstruct=True, + ) assert all(d["explicit"] for d in r.symmetries) exprs = generator_strings(r) assert any("p^nhill" in x for x in exprs) @@ -587,8 +671,10 @@ def test_equilibrate_hill_closed_form_recast(): assert not any("_E_" in x or "_L_" in x for x in exprs) # generators use the ^ power syntax and are plain name-to-string maps assert not any("**" in x for x in exprs) - assert all(isinstance(d["generator"], dict) and all(isinstance(v, str) for v in d["generator"].values()) - for d in r.symmetries) + assert all( + isinstance(d["generator"], dict) and all(isinstance(v, str) for v in d["generator"].values()) + for d in r.symmetries + ) def test_michaelis_hill_exponent_non_identifiable(): @@ -602,8 +688,7 @@ def test_michaelis_hill_exponent_non_identifiable(): def test_michaelis_hill_reconstruct_log_factor(): - r = detect(reactions=hill_michaelis(), observables={"xobs": "scale * x"}, equilibrate=True, - reconstruct=True) + r = detect(reactions=hill_michaelis(), observables={"xobs": "scale * x"}, equilibrate=True, reconstruct=True) assert all(d["explicit"] for d in r.symmetries) assert any("log(" in x for x in generator_strings(r)) @@ -612,8 +697,7 @@ def test_log_observable_of_an_eliminated_species(): # a logarithm positive in the full model is positive on the manifold of the conserved total rx = network(("A", "B", "k1 * A * (1 + kin*u)"), ("B", "A", "k2 * B"), ("0", "u", "0")) ev = [event("u", 0, "dose", "replace")] - args = dict(reactions=rx, equilibrate=True, inputs=["u"], events=ev, - conditions=grid(["d1", "d2"], dose=[1, 2])) + args = dict(reactions=rx, equilibrate=True, inputs=["u"], events=ev, conditions=grid(["d1", "d2"], dose=[1, 2])) pos = ["A", "B", "u", "k1", "k2", "kin", "sA", "sB"] obs = {"yA": "log(sA * A)", "yB": "log(sB * B + oB)"} r_t = detect(**args, observables=obs, reduce_cq=True, positive=pos + ["oB"]) @@ -629,8 +713,15 @@ def test_equilibrate_held_variable_moiety(): rx = network(("A", "B", "k1 * A * (1 + kin*u)"), ("B", "A", "k2 * B"), ("0", "u", "0")) obs = {"y": "scale * A"} ev = [event("u", 0, "dose", "replace")] - args = dict(reactions=rx, observables=obs, equilibrate=True, inputs=["u"], events=ev, - conditions=grid(["d1", "d2"], dose=[1, 2]), reconstruct=True) + args = dict( + reactions=rx, + observables=obs, + equilibrate=True, + inputs=["u"], + events=ev, + conditions=grid(["d1", "d2"], dose=[1, 2]), + reconstruct=True, + ) r_t = detect(**args, reduce_cq=True) r_f = detect(**args, reduce_cq=False) assert r_f.rank == r_t.rank @@ -647,25 +738,38 @@ def test_equilibrate_held_variable_moiety(): assert len(pool) >= 1 assert expr_equal(pool[0]["generator"]["A"], "A") # a single condition with a rank-deficient f = 0 - r1 = detect(reactions=rx, observables=obs, equilibrate=True, inputs=["u"], events=ev, - conditions=grid(["d1"], dose=[1]), reconstruct=True) + r1 = detect( + reactions=rx, + observables=obs, + equilibrate=True, + inputs=["u"], + events=ev, + conditions=grid(["d1"], dose=[1]), + reconstruct=True, + ) assert "A" in supports(r1) def test_sparse_reconstruction_matches_dense(): - res = detect(reactions=canonical(), observables={"Aobs": "alpha * A"}, reconstruct=True, - control=si.reconst_control(relevance_cap=0)) - d = [x for x in res.symmetries - if x["explicit"] and {"B", "k1", "k2"} <= set(x["generator"] or {})] + res = detect( + reactions=canonical(), + observables={"Aobs": "alpha * A"}, + reconstruct=True, + control=si.reconst_control(relevance_cap=0), + ) + d = [x for x in res.symmetries if x["explicit"] and {"B", "k1", "k2"} <= set(x["generator"] or {})] assert len(d) >= 1 assert expr_equal(d[0]["generator"]["B"], "A + B") assert expr_equal(d[0]["generator"]["k1"], "k2") def test_multi_condition_switch_gated_rate(): - multi = detect({"A": "-(k1 + u*k2)*A", "u": "0"}, {"y": "A"}, - events=[event("u", -1, "var_u", "replace")], - conditions=grid(["ctrl", "stim"], var_u=[0, 1])) + multi = detect( + {"A": "-(k1 + u*k2)*A", "u": "0"}, + {"y": "A"}, + events=[event("u", -1, "var_u", "replace")], + conditions=grid(["ctrl", "stim"], var_u=[0, 1]), + ) assert multi.identifiable is True assert multi.info["conditions"] == 2 assert not any("u" in d["support"] for d in multi.symmetries) @@ -678,8 +782,12 @@ def test_multi_condition_union_parameter_space(): def test_multi_condition_common_confounder(): - res = detect({"A": "-k*A", "u": "0"}, {"y": "s*A"}, events=[event("u", -1, "var_u", "replace")], - conditions=grid(["a", "b"], var_u=[0, 1])) + res = detect( + {"A": "-k*A", "u": "0"}, + {"y": "s*A"}, + events=[event("u", -1, "var_u", "replace")], + conditions=grid(["a", "b"], var_u=[0, 1]), + ) assert res.identifiable is False supp = supports(res) assert {"A", "s"} <= supp @@ -690,8 +798,10 @@ def test_gap_dose_resolved_in_own_condition(): # the same model with the grid column named apart from or after the first cell def run(colname): ev = [event("A", 0, "0", "replace"), event("A", 1, colname, "add")] - return detect({"A": "-k*A"}, {"y": "A"}, events=ev, - conditions={"rows": ["c1", "c2"], "cols": {colname: ["d", "d2"]}}) + return detect( + {"A": "-k*A"}, {"y": "A"}, events=ev, conditions={"rows": ["c1", "c2"], "cols": {colname: ["d", "d2"]}} + ) + neutral = run("dose") colliding = run("d") assert colliding.dim == neutral.dim @@ -731,8 +841,7 @@ def test_scaling_lattice_intersection_per_condition(): def test_post_t0_event_second_segment(): ev = [event("A", 0, "d0", "add"), event("A", 1, "d1", "add")] - r = detect({"A": "-k*A"}, {"y": "s*A"}, events=ev, conditions=grid(["c1"], d0=[1], d1=[1]), - reconstruct=True) + r = detect({"A": "-k*A"}, {"y": "s*A"}, events=ev, conditions=grid(["c1"], d0=[1], d1=[1]), reconstruct=True) assert r.info["conditions"] == 1 assert r.info["segments"] == 2 assert r.dim == 3 @@ -742,8 +851,7 @@ def test_post_t0_event_second_segment(): def test_direction_depending_on_gap(): # only z(1) = z*exp(-k2) reaches the output, so z and k2 move in a gap-dependent ratio ev = [event("u", 0, "0", "replace"), event("u", 1, "1", "replace")] - r = detect({"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, {"y": "x"}, events=ev, - reconstruct=True) + r = detect({"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, {"y": "x"}, events=ev, reconstruct=True) assert r.identifiable is False assert r.rank == 3 assert len(r.symmetries) == 1 @@ -757,8 +865,7 @@ def test_direction_depending_on_gap(): def test_event_time_parameter_is_coordinate(): ev = [event("u", 0, "0", "replace"), event("u", "tau", "1", "replace")] - r = detect({"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, {"y": "x"}, events=ev, - reconstruct=True) + r = detect({"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, {"y": "x"}, events=ev, reconstruct=True) assert "tau" in r.info["coordinates"] assert r.rank == 4 gen = r.symmetries[0]["generator"] @@ -768,16 +875,25 @@ def test_event_time_parameter_is_coordinate(): evd = [event("A", "tau", "d", "add")] rj = detect({"A": "-k*A"}, {"y": "A"}, events=evd, trafo={"A": "0"}) assert rj.identifiable is True - rk = detect({"D": "-ka*D", "A": "ka*D - k*A"}, {"y": "A"}, events=[event("D", "tau", "d", "add")], - trafo={"D": "0", "A": "0"}) + rk = detect( + {"D": "-ka*D", "A": "ka*D - k*A"}, + {"y": "A"}, + events=[event("D", "tau", "d", "add")], + trafo={"D": "0", "A": "0"}, + ) assert rk.identifiable is True # a switch the output does not feel leaves the switch time free - ri = detect({"A": "-k*A", "u": "0"}, {"y": "A"}, - events=[event("u", 0, "0"), event("u", "tau", "1")], reconstruct=True) + ri = detect( + {"A": "-k*A", "u": "0"}, {"y": "A"}, events=[event("u", 0, "0"), event("u", "tau", "1")], reconstruct=True + ) assert ri.rank == 2 assert list(ri.symmetries[0]["generator"]) == ["tau"] - bad = [event("A", 0, "d", "add"), event("A", 5, "d", "add"), event("A", "tau", "d", "add"), - event("A", 2, "d", "add")] + bad = [ + event("A", 0, "d", "add"), + event("A", 5, "d", "add"), + event("A", "tau", "d", "add"), + event("A", 2, "d", "add"), + ] with pytest.raises(Exception, match="ascending"): detect({"A": "-k*A"}, {"y": "A"}, events=bad) with pytest.raises(Exception, match="modular"): @@ -810,8 +926,7 @@ def test_log_parameters_and_log_observables(): def test_single_segment_without_later_events(): - r = detect({"A": "-k*A"}, {"y": "s*A"}, events=[event("A", 0, "d0", "add")], - conditions=grid(["c1"], d0=[1])) + r = detect({"A": "-k*A"}, {"y": "s*A"}, events=[event("A", 0, "d0", "add")], conditions=grid(["c1"], d0=[1])) assert r.info["segments"] == 1 assert r.dim == 3 assert r.identifiable is False @@ -821,8 +936,7 @@ def test_transient_channel_parameter_identified(): # kinh acts only on the boundary state at t = 0, reached through the propagated gap f = {"x": "kpr/(1 + kinh*inh) - kdeg*x + kstim*stim", "inh": "0", "stim": "0"} ev = [event("inh", -30, "1", "replace"), event("stim", 0, "1", "replace")] - r30 = detect(f, {"y": "s*x"}, equilibrate=True, events=ev, conditions=grid(["c1"]), - inputs=["inh", "stim"]) + r30 = detect(f, {"y": "s*x"}, equilibrate=True, events=ev, conditions=grid(["c1"]), inputs=["inh", "stim"]) assert r30.info["segments"] == 2 # the exact scaling bounds the rank, which the gap order 0 already reaches assert r30.info["rank_status"]["status"] == "proven" and r30.info["order_bound"] == 0.0 @@ -831,8 +945,7 @@ def test_transient_channel_parameter_identified(): def test_equilibrate_seeds_later_segment(): ev = [event("x", 0, "dose", "replace"), event("x", 1, "d1", "add")] - r = detect({"x": "b - a*x"}, {"y": "s*x"}, equilibrate=True, events=ev, - conditions=grid(["stim"], dose=[2], d1=[1])) + r = detect({"x": "b - a*x"}, {"y": "s*x"}, equilibrate=True, events=ev, conditions=grid(["stim"], dose=[2], d1=[1])) assert r.info["conditions"] == 1 assert r.info["segments"] == 2 assert r.identifiable is True @@ -841,9 +954,15 @@ def test_equilibrate_seeds_later_segment(): def test_free_hill_feedback_weighted_scaling(): # k_fb * k_pf^nh is invariant: a scaling of k_pf compensated by k_fb with weight -nh f = {"R": "k_pr/(1 + k_fb*FB^nh) - k_dg*R + k_stim*u", "FB": "k_pf*R - k_df*FB", "u": "0"} - r = detect(f, {"R_obs": "s*R"}, equilibrate=True, inputs=["u"], - events=[event("u", 0, "dose", "replace")], conditions=grid(["c1"], dose=[1]), - reconstruct=True) + r = detect( + f, + {"R_obs": "s*R"}, + equilibrate=True, + inputs=["u"], + events=[event("u", 0, "dose", "replace")], + conditions=grid(["c1"], dose=[1]), + reconstruct=True, + ) assert all(d["explicit"] for d in r.symmetries) hill = [d for d in r.symmetries if set(d["support"]) == {"k_fb", "k_pf"}] assert len(hill) == 1 @@ -853,8 +972,9 @@ def test_free_hill_feedback_weighted_scaling(): def test_implicit_steady_state_multi_condition(): f = {"x1": "v1 - k*x1/(K + x1)", "x2": "v2 - k*x2/(K + x2)"} - r = detect(f, {"y": "s*(x1 + x2)"}, equilibrate=True, conditions=grid(["c1", "c2"], k=["k1", "k2"]), - reconstruct=False) + r = detect( + f, {"y": "s*(x1 + x2)"}, equilibrate=True, conditions=grid(["c1", "c2"], k=["k1", "k2"]), reconstruct=False + ) assert r.identifiable is False assert r.dim == 6 assert r.rank == 2 @@ -891,23 +1011,27 @@ def test_scalings_with_events_and_conditions(): base = detect(reactions=canonical(), observables=g, scalings_only=True) assert len(base.symmetries) == 1 # a known dose pins the absolute value of A - pinned = detect(reactions=canonical(), observables=g, scalings_only=True, - events=[event("A", 0, "2", "replace")]) + pinned = detect(reactions=canonical(), observables=g, scalings_only=True, events=[event("A", 0, "2", "replace")]) assert len(pinned.symmetries) == 0 # a second condition fixing alpha drops the shared scaling - drop = detect(reactions=canonical(), observables=g, scalings_only=True, - trafo=[{"k1": "k1"}, {"alpha": "1"}]) + drop = detect(reactions=canonical(), observables=g, scalings_only=True, trafo=[{"k1": "k1"}, {"alpha": "1"}]) assert len(drop.symmetries) == 0 - keep = detect(reactions=canonical(), observables=g, scalings_only=True, - conditions=grid(["c1", "c2"], k1=["ka", "kb"])) + keep = detect( + reactions=canonical(), observables=g, scalings_only=True, conditions=grid(["c1", "c2"], k1=["ka", "kb"]) + ) assert len(keep.symmetries) == 1 def test_toric_peel_hill_weight(): # k_inh * p^nhill is invariant under p -> lam*p, k_inh -> lam^(-nhill)*k_inh - r = detect({"p": "kpr/(1 + kinh*p^nhill) - dp*p + kin*u", "u": "0"}, {"y": "s*p"}, - equilibrate=True, events=[event("u", -1, "var_u", "replace")], - conditions=grid(["ctrl", "stim"], var_u=[0, 1]), reconstruct=True) + r = detect( + {"p": "kpr/(1 + kinh*p^nhill) - dp*p + kin*u", "u": "0"}, + {"y": "s*p"}, + equilibrate=True, + events=[event("u", -1, "var_u", "replace")], + conditions=grid(["ctrl", "stim"], var_u=[0, 1]), + reconstruct=True, + ) hill = [d for d in r.symmetries if d["type"] == "scaling" and "kinh" in (d["generator"] or {})] assert len(hill) == 1 assert hill[0]["explicit"] is True @@ -975,12 +1099,15 @@ def test_lie_order_saturates_per_condition(): def test_lie_order_certified_by_rank_bound(): - free = detect({"A": "-k1*A", "B": "k1*A - k2*B"}, [{"y": "s*A"}, {"y": "s*B"}], - conditions=grid(["c1", "c2"])) + free = detect({"A": "-k1*A", "B": "k1*A - k2*B"}, [{"y": "s*A"}, {"y": "s*B"}], conditions=grid(["c1", "c2"])) assert free.info["lie_certified"] is True # a steady state as initial value - ss = detect({"x": "b - a*x", "z": "a*x - c*z"}, {"y": "s*x"}, trafo={"x": "b/a", "z": "b/c"}, - conditions=grid(["c1", "c2"], b=[1, 2])) + ss = detect( + {"x": "b - a*x", "z": "a*x - c*z"}, + {"y": "s*x"}, + trafo={"x": "b/a", "z": "b/c"}, + conditions=grid(["c1", "c2"], b=[1, 2]), + ) assert ss.info["lie_certified"] is True # a fixed initial value at which the lower rows vanish pin = detect({"x": "th"}, {"y": "x^5"}, trafo={"x": "0", "th": "th"}) @@ -988,24 +1115,35 @@ def test_lie_order_certified_by_rank_bound(): assert pin.identifiable is True assert pin.info["lie_order_used"] == 5 # a state that stays at zero - zs = detect({"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, {"y": "x2"}, - trafo={"x1": "1", "x2": "0", "x3": "0", "k1": "k1", "k2": "k2", "k3": "k3", "a": "a"}) + zs = detect( + {"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, + {"y": "x2"}, + trafo={"x1": "1", "x2": "0", "x3": "0", "k1": "k1", "k2": "k2", "k3": "k3", "a": "a"}, + ) assert zs.info["lie_certified"] is True assert zs.rank == 2 # a start state on an invariant affine space - li = detect({"x1": "a - (d + f)*x1", "x2": "b - (d + f)*x2", "f": "-c*f"}, {"y": "x1 + x2"}, - trafo={"x1": "a/d", "x2": "b/d", "f": "1", "a": "a", "b": "b", "c": "c", "d": "d"}) + li = detect( + {"x1": "a - (d + f)*x1", "x2": "b - (d + f)*x2", "f": "-c*f"}, + {"y": "x1 + x2"}, + trafo={"x1": "a/d", "x2": "b/d", "f": "1", "a": "a", "b": "b", "c": "c", "d": "d"}, + ) assert li.info["lie_certified"] is True assert li.rank == 3 # exact scalings prove the rank; a scaling that holds only at rest does not - sw = detect({"A": "-k1*A", "B": "k1*A - k2*B"}, {"y": "s*B"}, - trafo={"A": "A0", "B": "0", "k1": "k1", "k2": "k2", "s": "s"}) + sw = detect( + {"A": "-k1*A", "B": "k1*A - k2*B"}, {"y": "s*B"}, trafo={"A": "A0", "B": "0", "k1": "k1", "k2": "k2", "s": "s"} + ) assert sw.info["rank_proven"] == 1 rs = detect({"x": "k1 - k2*x"}, {"y": "x"}, trafo={"x": "k1/k2", "k1": "k1", "k2": "k2"}) assert rs.info.get("rank_proven") is None # an event time among the coordinates - td = detect({"A": "-k*A"}, {"y": "A"}, events=[event("A", "tau", "d", "add")], - trafo={"A": "0", "k": "k", "d": "d", "tau": "tau"}) + td = detect( + {"A": "-k*A"}, + {"y": "A"}, + events=[event("A", "tau", "d", "add")], + trafo={"A": "0", "k": "k", "d": "d", "tau": "tau"}, + ) assert td.info["lie_certified"] is True assert td.identifiable is True @@ -1043,47 +1181,67 @@ def test_complete_generator_flow(): "m": "ktx*(C + b0)/dm", "P": "ktl*ktx*(C + b0)*(Km + R1 + R2 + R3)/(dm*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", "kint": "ksec*ktl*ktx*r_C_1*r_L_1*(C + b0)*(Km + R1 + R2 + R3)/(C*dm*(r_C_1*r_L_1 + r_C_1 + 1)" - "*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", + "*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", "koff": "ksec*ktl*ktx*r_L_1*(C + b0)*(Km + R1 + R2 + R3)/(C*dm*(r_C_1*r_L_1 + r_C_1 + 1)" - "*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", + "*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", "ksR": "(R*kdR*r_C_1*r_L_1 + R*kdR*r_C_1 + R*kdR*r_L_1 + R*kdR + ksec*ktl*ktx*r_C_1*r_L_1**2*(C + b0)" - "*(Km + R1 + R2 + R3)/(dm*(r_C_1*r_L_1 + r_C_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))" - " + ksec*ktl*ktx*r_C_1*r_L_1*(C + b0)*(Km + R1 + R2 + R3)/(dm*(Km*ksec + R1*ksec + R2*ksec" - " + R3*ksec + kdg)))/(r_C_1*r_L_1 + r_C_1 + r_L_1 + 1)", + "*(Km + R1 + R2 + R3)/(dm*(r_C_1*r_L_1 + r_C_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))" + " + ksec*ktl*ktx*r_C_1*r_L_1*(C + b0)*(Km + R1 + R2 + R3)/(dm*(Km*ksec + R1*ksec + R2*ksec" + " + R3*ksec + kdg)))/(r_C_1*r_L_1 + r_C_1 + r_L_1 + 1)", "kon": "ksec*ktl*ktx*r_L_1*(C + b0)*(r_L_1/(r_C_1*r_L_1 + r_C_1 + 1) + 1)*(Km + R1 + R2 + R3)" - "/(L*R*dm*(r_L_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", + "/(L*R*dm*(r_L_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", "kL": "ksec*ktl*ktx*(C + b0)*(r_L_1/(r_C_1*r_L_1 + r_C_1 + 1) + 1)*(Km + R1 + R2 + R3)" - "/(L*dm*(r_L_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", + "/(L*dm*(r_L_1 + 1)*(Km*ksec + R1*ksec + R2*ksec + R3*ksec + kdg))", } def test_sum_of_leaves_translation_group(): # the curved direction trading kdg against ksec has the entry ksec*(Km + R1 + R2 + R3)^2; # the trafo is the steady state of the network solved for some rates - rx = network(("", "m", "ktx*(b0 + C)"), ("m", "", "dm*m"), ("", "P", "ktl*m"), - ("P", "", "kdg*P/(Km + R1 + R2 + R3)"), ("P", "L", "ksec*P"), ("L", "", "kL*L"), - ("", "R", "ksR"), ("R", "", "kdR*R"), ("L + R", "C", "kon*L*R"), - ("C", "L + R", "koff*C"), ("C", "", "kint*C")) + rx = network( + ("", "m", "ktx*(b0 + C)"), + ("m", "", "dm*m"), + ("", "P", "ktl*m"), + ("P", "", "kdg*P/(Km + R1 + R2 + R3)"), + ("P", "L", "ksec*P"), + ("L", "", "kL*L"), + ("", "R", "ksR"), + ("R", "", "kdR*R"), + ("L + R", "C", "kon*L*R"), + ("C", "L + R", "koff*C"), + ("C", "", "kint*C"), + ) g = {"ym": "sm*m", "yC": "sC*C", "yL": "L", "yR1": "R1", "yR2": "R2", "yR3": "R3"} - args = dict(reactions=rx, observables=g, trafo=_AUTOCRINE_STEADY_STATE, - events=[event("L", 0, "dose", "add")], conditions=grid(["ctrl", "stim"], dose=[0, 1]), - reconstruct=True) + args = dict( + reactions=rx, + observables=g, + trafo=_AUTOCRINE_STEADY_STATE, + events=[event("L", 0, "dose", "add")], + conditions=grid(["ctrl", "stim"], dose=[0, 1]), + reconstruct=True, + ) with state.switches(NOGROUP=False): res = detect(**args) assert all(d["explicit"] for d in res.symmetries) wide = next(d for d in res.symmetries if "ksec" in (d["generator"] or {})) - assert expr_equal(f"({wide['generator']['Km']})/({wide['generator']['ksec']})", - "(Km + R1 + R2 + R3)**2/kdg") + assert expr_equal(f"({wide['generator']['Km']})/({wide['generator']['ksec']})", "(Km + R1 + R2 + R3)**2/kdg") # without the groups the narrow route may close another basis vector of the same span with state.switches(NOGROUP=True): res0 = detect(**args) import sympy as sp + gens = [d["generator"] for d in res.symmetries] names = sorted({v for gen in gens + [d["generator"] for d in res0.symmetries] for v in gen}) - pt = {sp.Symbol(v): sp.Rational(7 + 3 * i, 5 + i) for i, v in enumerate( - sorted({str(x) for gen in gens for e in gen.values() for x in sp.sympify(e).free_symbols} | set(names)))} + pt = { + sp.Symbol(v): sp.Rational(7 + 3 * i, 5 + i) + for i, v in enumerate( + sorted({str(x) for gen in gens for e in gen.values() for x in sp.sympify(e).free_symbols} | set(names)) + ) + } + def mat(gs): return sp.Matrix([[sp.sympify(gen.get(v, "0")).xreplace(pt) for v in names] for gen in gs]) + for d in res0.symmetries: assert mat(gens + [d["generator"]]).rank() == mat(gens).rank() == len(gens) @@ -1092,13 +1250,14 @@ def test_translation_groups_test_only_pairs_alike_under_single_moves(): import numpy as np from symident.detection.groups import translation_groups + P = 1000003 calls = [] def kb(pts, primes, nt): calls.append(len(pts)) - return [{"ok": True, "pivots": [0], "v": np.array([(z[0] + z[1]) % P, z[2] * z[3] % P, z[4] % P])} - for z in pts] + return [{"ok": True, "pivots": [0], "v": np.array([(z[0] + z[1]) % P, z[2] * z[3] % P, z[4] % P])} for z in pts] + base = [2, 3, 5, 7, 11] ref = kb([base], [P], 4)[0] rel = [] @@ -1106,8 +1265,7 @@ def kb(pts, primes, nt): z = list(base) z[li] += 1 rel.append({"rp": kb([z], [P], 4)[0]}) - sc = {"point0": base, "pool": lambda idx: np.atleast_1d(idx).astype(np.int64) * 7 + 3, "pool_next": 0, - "nt_used": 4} + sc = {"point0": base, "pool": lambda idx: np.atleast_1d(idx).astype(np.int64) * 7 + 3, "pool_next": 0, "nt_used": 4} calls.clear() groups = translation_groups(rel, ref, lambda o, p: o["v"], kb, sc, P, 5) assert [(g["type"], g["rep"], g["members"]) for g in groups] == [("add", 0, [1]), ("mul", 2, [3])] @@ -1127,8 +1285,7 @@ def test_per_condition_observables_as_tuple(): def test_symbolic_engine_free_hill_exponent(): ss = {"FB": "k_pr_FB/d_FB", "x": "k_pr_x*K^n/(d_x*(K^n + (k_pr_FB/d_FB)^n))"} - sres = detect(reactions=hill_michaelis(), observables={"xobs": "scale * x"}, engine="symbolic", - trafo=ss) + sres = detect(reactions=hill_michaelis(), observables={"xobs": "scale * x"}, engine="symbolic", trafo=ss) assert any("n" in d["support"] for d in sres.symmetries) @@ -1202,6 +1359,7 @@ def test_stacked_narrowing_reads_off_and_closes_columns_without_rows(monkeypatch assert res.rank == res.dim - 5 # the lifts in forked workers prove the same directions from symident.detection.observability import proof + monkeypatch.setattr(proof, "_PAR_LIFTS", 1) with state.options(stacked_min=0): par = detect(f, g, conditions=cg, reconstruct=True, cores=2) @@ -1210,8 +1368,7 @@ def test_stacked_narrowing_reads_off_and_closes_columns_without_rows(monkeypatch def test_constant_state_events_per_segment(): - rx = network(("", "R", "kR"), ("R", "", "dR*R"), ("", "G", "kG*R*(b + u)"), ("G", "", "dG*G"), - ("", "u", "0")) + rx = network(("", "R", "kR"), ("R", "", "dR*R"), ("", "G", "kG*R*(b + u)"), ("G", "", "dG*G"), ("", "u", "0")) g = {"yG": "sG*G"} ev = [event("u", 0, "dose", "add")] cg = grid(["c0", "stim"], dose=[0, 1]) @@ -1229,13 +1386,29 @@ def test_constant_state_events_per_segment(): def test_static_subsystem_proves_rank(): - rx = network(("", "m", "km*plasmid"), ("m", "", "dm*m"), ("", "E", "kt*m"), ("E", "", "dE*E"), - ("E", "X", "kex*E"), ("", "X", "kx"), ("X", "", "dX*X*(1 + L)"), - ("", "L", "kL"), ("L", "", "dL*L")) + rx = network( + ("", "m", "km*plasmid"), + ("m", "", "dm*m"), + ("", "E", "kt*m"), + ("E", "", "dE*E"), + ("E", "X", "kex*E"), + ("", "X", "kx"), + ("X", "", "dX*X*(1 + L)"), + ("", "L", "kL"), + ("L", "", "dL*L"), + ) g = {"yX": "sX*(X + E)", "ym": "sm*m", "yL": "L"} ev = [event("L", 0, "dose", "add"), event("L", 5, "dose", "add")] - r = detect(reactions=rx, observables=g, conditions=grid(["ctrl", "oe"], plasmid=[0, 1], dose=[1, 1]), - events=ev, equilibrate=True, reduce_cq=True, gauge=None, reconstruct=True) + r = detect( + reactions=rx, + observables=g, + conditions=grid(["ctrl", "oe"], plasmid=[0, 1], dose=[1, 1]), + events=ev, + equilibrate=True, + reduce_cq=True, + gauge=None, + reconstruct=True, + ) assert r.rank == 7 assert r.info["rank_proof"] == "proven symmetries" # a subsystem that no event reaches stays at rest and has exact directions @@ -1247,18 +1420,26 @@ def test_static_subsystem_proves_rank(): def test_log_coordinate_read_off_depends_on_own_coordinate(): - rx = network(("", "x1", "kb"), ("", "x1", "kin*u"), ("x1", "x2", "k1*x1"), ("x1", "", "kl*x1"), - ("x2", "", "k2*x2")) + rx = network(("", "x1", "kb"), ("", "x1", "kin*u"), ("x1", "x2", "k1*x1"), ("x1", "", "kl*x1"), ("x2", "", "k2*x2")) rx["species"].append("u") rx["stoichiometry"] = [row + [0] for row in rx["stoichiometry"]] - r = detect(reactions=rx, observables={"y": "s*x2"}, inputs=["u"], - events=[event("u", 0, "dose", "replace")], conditions=grid(["low", "high"], dose=[1, 10]), - equilibrate=True, reduce_cq=True, reconstruct=True) + r = detect( + reactions=rx, + observables={"y": "s*x2"}, + inputs=["u"], + events=[event("u", 0, "dose", "replace")], + conditions=grid(["low", "high"], dose=[1, 10]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + ) assert r.rank == 4 gen = next(d for d in r.symmetries if d.type == "general").generator assert set(gen) == {"k1", "kb", "kin", "kl"} - ratio = {k: spy.simplify(spy.sympify(v.replace("^", "**")) / spy.sympify(gen["k1"].replace("^", "**"))) - for k, v in gen.items()} + ratio = { + k: spy.simplify(spy.sympify(v.replace("^", "**")) / spy.sympify(gen["k1"].replace("^", "**"))) + for k, v in gen.items() + } assert ratio == {"k1": 1, "kb": spy.sympify("-kb/k1"), "kin": spy.sympify("-kin/k1"), "kl": -1} @@ -1271,10 +1452,24 @@ def test_lie_order_certified_per_condition_from_a_generic_state(): def test_failed_relevance_probe_does_not_freeze_a_rate(): - rx = network(("A", "B", "kf0*u*A"), ("B", "A", "kr0*B"), ("B", "C", "kf1*B"), ("C", "B", "kr1*C"), - ("D", "E", "V*C*D/(K + D)"), ("E", "D", "kr2*E"), ("E", "F", "kf3*E"), ("F", "E", "kr3*F")) - r = detect(reactions=rx, observables={"y0": "s0*C", "y1": "s1*B"}, conditions=grid(["a", "b"], u=[1, 4]), - equilibrate=True, reduce_cq=True, reconstruct=True) + rx = network( + ("A", "B", "kf0*u*A"), + ("B", "A", "kr0*B"), + ("B", "C", "kf1*B"), + ("C", "B", "kr1*C"), + ("D", "E", "V*C*D/(K + D)"), + ("E", "D", "kr2*E"), + ("E", "F", "kf3*E"), + ("F", "E", "kr3*F"), + ) + r = detect( + reactions=rx, + observables={"y0": "s0*C", "y1": "s1*B"}, + conditions=grid(["a", "b"], u=[1, 4]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + ) gens = [d.generator for d in r.symmetries if d.generator] assert {"kf0": "kf0", "kr0": "kr0"} in gens and {"kf1": "kf1", "kr1": "kr1"} in gens for g in gens: @@ -1297,12 +1492,26 @@ def test_directions_span_the_kernel_without_duplicates(): def test_forward_closed_form_has_no_resting_state(): - rx = network(("x1", "x2", "V3*x1/(K4 + x1)"), ("", "x1", "k5"), ("", "x2", "k6"), ("x1", "", "k7*x1"), - ("x2", "", "k8*x2"), ("", "x1", "k10*u")) + rx = network( + ("x1", "x2", "V3*x1/(K4 + x1)"), + ("", "x1", "k5"), + ("", "x2", "k6"), + ("x1", "", "k7*x1"), + ("x2", "", "k8*x2"), + ("", "x1", "k10*u"), + ) rx["species"].append("u") rx["stoichiometry"] = [row + [0] for row in rx["stoichiometry"]] - r = detect(reactions=rx, observables={"y2": "x2"}, inputs=["u"], events=[event("u", 0, "dose", "replace")], - conditions=grid(["c1"], dose=[5]), equilibrate=True, reduce_cq=True, reconstruct=True) + r = detect( + reactions=rx, + observables={"y2": "x2"}, + inputs=["u"], + events=[event("u", 0, "dose", "replace")], + conditions=grid(["c1"], dose=[5]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + ) gen = next(d for d in r.symmetries if d.type == "general").generator assert all("x1" not in str(v) for v in gen.values()) ratio = spy.simplify(spy.sympify(gen["k5"].replace("^", "**")) / spy.sympify(gen["K4"].replace("^", "**"))) @@ -1318,8 +1527,14 @@ def test_unobserved_sink_state_leaves_the_resting_system(): def test_hill_resting_state_does_not_stall_static_fields(): rx = network(("x1", "", "V2*x1^3/(K1^3 + x1^3)"), ("x1", "", "k3*x1"), ("", "x1", "k5")) - r = detect(reactions=rx, observables={"y1": "s1*x1"}, conditions=grid(["c1", "c2"], K1=[7, 1]), - equilibrate=True, reduce_cq=True, reconstruct=True) + r = detect( + reactions=rx, + observables={"y1": "s1*x1"}, + conditions=grid(["c1", "c2"], K1=[7, 1]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + ) assert (r.rank, r.dim) == (2, 4) @@ -1329,13 +1544,16 @@ def test_small_network_at_rest_finishes_quickly(): assert (r.rank, r.dim) == (1, 5) -@pytest.mark.parametrize("odes, obs, rank_dim", [ - ({"x": "-k*x"}, {"y": "exp2(s*x) + acsch(s*x)"}, (2, 3)), - ({"x": "-k*atanh(x)"}, {"y": "x"}, (2, 2)), - ({"x": "-k*acot(x) - c*x"}, {"y": "x"}, (3, 3)), - ({"x": "-k*asech(x)"}, {"y": "s*x"}, (3, 3)), - ({"x": "-k*x"}, {"y": "acoth(1 + s*x)"}, (2, 3)), -]) +@pytest.mark.parametrize( + "odes, obs, rank_dim", + [ + ({"x": "-k*x"}, {"y": "exp2(s*x) + acsch(s*x)"}, (2, 3)), + ({"x": "-k*atanh(x)"}, {"y": "x"}, (2, 2)), + ({"x": "-k*acot(x) - c*x"}, {"y": "x"}, (3, 3)), + ({"x": "-k*asech(x)"}, {"y": "s*x"}, (3, 3)), + ({"x": "-k*x"}, {"y": "acoth(1 + s*x)"}, (2, 3)), + ], +) def test_the_functions_of_the_backend_expressions(odes, obs, rank_dim): r = detect(odes, obs) assert (r.rank, r.dim) == rank_dim @@ -1364,37 +1582,44 @@ def test_fractional_power_of_a_positive_parameter(): assert [d.generator for d in r.symmetries] == [{"a": "a", "b": "-b"}] -@pytest.mark.parametrize("odes, obs, trafo, rank_dim", [ - ({"x": "-k*atan(x)"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*log(1 + x^2) - d*x"}, {"y": "s*x"}, None, (4, 4)), - ({"x": "-a*atan(b*x)"}, {"y": "x"}, None, (3, 3)), - ({"x": "-k*x"}, {"y": "atan(s*x)"}, None, (2, 3)), - ({"x": "-k*sqrt(1 + x^2)"}, {"y": "x"}, {"x": "0"}, (1, 1)), - ({"x": "-k*asinh(x) + c"}, {"y": "x"}, {"x": "0"}, (2, 2)), - ({"x": "-sqrt(a + b)*x"}, {"y": "x"}, None, (2, 3)), - ({"x": "-k*log(x, 3)"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*x + a*atan2(x, 2)"}, {"y": "x"}, None, (3, 3)), - ({"x": "-k*atanh(x/(1 + x))"}, {"y": "x"}, None, (2, 2)), -]) +@pytest.mark.parametrize( + "odes, obs, trafo, rank_dim", + [ + ({"x": "-k*atan(x)"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*log(1 + x^2) - d*x"}, {"y": "s*x"}, None, (4, 4)), + ({"x": "-a*atan(b*x)"}, {"y": "x"}, None, (3, 3)), + ({"x": "-k*x"}, {"y": "atan(s*x)"}, None, (2, 3)), + ({"x": "-k*sqrt(1 + x^2)"}, {"y": "x"}, {"x": "0"}, (1, 1)), + ({"x": "-k*asinh(x) + c"}, {"y": "x"}, {"x": "0"}, (2, 2)), + ({"x": "-sqrt(a + b)*x"}, {"y": "x"}, None, (2, 3)), + ({"x": "-k*log(x, 3)"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*x + a*atan2(x, 2)"}, {"y": "x"}, None, (3, 3)), + ({"x": "-k*atanh(x/(1 + x))"}, {"y": "x"}, None, (2, 2)), + ], +) def test_elementary_functions_agree_with_the_symbolic_engine(odes, obs, trafo, rank_dim): mod = detect(odes, obs, trafo=trafo) sym = detect(odes, obs, trafo=trafo, engine="symbolic") assert (mod.rank, mod.dim) == (sym.rank, sym.dim) == rank_dim -@pytest.mark.parametrize("odes, obs, trafo, rank_dim", [ - ({"x": "-k*sqrt(1 + x^2)"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*x"}, {"y": "s*sqrt(1 + x^2)"}, None, (3, 3)), - ({"x": "-k*sqrt(1 + exp(c*x))"}, {"y": "x"}, None, (3, 3)), - ({"x": "-k*asin(x/(1 + x))"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*sqrt(1 + x^2) + a"}, {"y": "s*x"}, {"x": "2"}, (3, 3)), - ({"x": "-k*(1 + x^2)^(1/3)"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*(1 + x^2)^(2/3) + a"}, {"y": "s*x"}, None, (4, 4)), - ({"x": "-k*(1 + x^2)^(1/6)"}, {"y": "x"}, None, (2, 2)), - ({"x": "-k*(1 + x^2)^(1/5)"}, {"y": "x"}, {"x": "1"}, (1, 1)), -]) +@pytest.mark.parametrize( + "odes, obs, trafo, rank_dim", + [ + ({"x": "-k*sqrt(1 + x^2)"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*x"}, {"y": "s*sqrt(1 + x^2)"}, None, (3, 3)), + ({"x": "-k*sqrt(1 + exp(c*x))"}, {"y": "x"}, None, (3, 3)), + ({"x": "-k*asin(x/(1 + x))"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*sqrt(1 + x^2) + a"}, {"y": "s*x"}, {"x": "2"}, (3, 3)), + ({"x": "-k*(1 + x^2)^(1/3)"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*(1 + x^2)^(2/3) + a"}, {"y": "s*x"}, None, (4, 4)), + ({"x": "-k*(1 + x^2)^(1/6)"}, {"y": "x"}, None, (2, 2)), + ({"x": "-k*(1 + x^2)^(1/5)"}, {"y": "x"}, {"x": "1"}, (1, 1)), + ], +) def test_rational_powers_of_initial_values_are_exact(odes, obs, trafo, rank_dim): from symident import gfp + mod = detect(odes, obs, trafo=trafo) sym = detect(odes, obs, trafo=trafo, engine="symbolic") assert (mod.rank, mod.dim) == (sym.rank, sym.dim) == rank_dim @@ -1403,6 +1628,7 @@ def test_rational_powers_of_initial_values_are_exact(odes, obs, trafo, rank_dim) def test_odd_root_rerun_restores_the_primes(): from symident import gfp + rx = detect({"x": "-k*(1 + x^2)^(1/3)"}, {"y": "x"}) assert rx.rank == 2 assert list(gfp.PRIMES) == [1518500183, 1518500173, 1518500171, 1518500143] @@ -1410,13 +1636,13 @@ def test_odd_root_rerun_restores_the_primes(): def test_a_constant_with_an_engine_prime_as_denominator_reruns_over_other_primes(): - r = detect({"x": "-k*x/1518500183"}, {"y": "s*x"}, - conditions=grid(["a", "b", "c"], k=["k1", "k2", "k3"]), cores=4) + r = detect({"x": "-k*x/1518500183"}, {"y": "s*x"}, conditions=grid(["a", "b", "c"], k=["k1", "k2", "k3"]), cores=4) assert (r.rank, r.dim) == (4, 5) def test_use_primes_switches_every_prime_together(): from symident import gfp + before = gfp.all_primes() with gfp.use_primes([], [3]): run = gfp.prime_run(12) @@ -1444,28 +1670,49 @@ def test_sink_behind_a_state_at_zero_leaves_the_resting_system(): def test_directions_stay_independent_under_several_resting_conditions(): - rx = network(("M0s2", "M0s1", "kr01*M0s2"), ("M1s0", "M1s1", "kf10*u*M1s0"), ("M1s1", "M1s0", "kr10*M1s1"), - ("M1s1", "M1s2", "kf11*u*M1s1"), ("M1s2", "M1s1", "kr11*M1s2"), ("", "P", "kin*M1s2"), - ("P", "", "kdeg*P")) - r = detect(reactions=rx, observables={"y1": "s1*P"}, conditions=grid(["a", "b"], u=[1, 4]), - equilibrate=True, reduce_cq=True, reconstruct=True) + rx = network( + ("M0s2", "M0s1", "kr01*M0s2"), + ("M1s0", "M1s1", "kf10*u*M1s0"), + ("M1s1", "M1s0", "kr10*M1s1"), + ("M1s1", "M1s2", "kf11*u*M1s1"), + ("M1s2", "M1s1", "kr11*M1s2"), + ("", "P", "kin*M1s2"), + ("P", "", "kdeg*P"), + ) + r = detect( + reactions=rx, + observables={"y1": "s1*P"}, + conditions=grid(["a", "b"], u=[1, 4]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + ) assert len(r.symmetries) == r.dim - r.rank -@pytest.mark.parametrize("odes, obs, rank_dim", [ - ({"x": "-(k1 + k2)*x"}, {"y": "x"}, (0, 2)), - ({"x": "-k1*x"}, {"y": "x"}, (0, 1)), - ({"x1": "x2 - x1 + k4", "x2": "-k1*x2 - k2*x2"}, {"y": "x1"}, (1, 3)), -]) +@pytest.mark.parametrize( + "odes, obs, rank_dim", + [ + ({"x": "-(k1 + k2)*x"}, {"y": "x"}, (0, 2)), + ({"x": "-k1*x"}, {"y": "x"}, (0, 1)), + ({"x1": "x2 - x1 + k4", "x2": "-k1*x2 - k2*x2"}, {"y": "x1"}, (1, 3)), + ], +) def test_ode_state_resting_at_zero(odes, obs, rank_dim): r = detect(odes, obs, equilibrate=True, reconstruct=True) assert (r.rank, r.dim) == rank_dim def test_ode_zero_rest_with_an_input_pulse(): - r = detect({"x1": "x2 - x1 + k4", "x2": "-k1*x2 - k2*x2 + u", "u": "-u"}, {"y": "x1"}, inputs=["u"], - events=[event("u", 0, "dose", "replace")], conditions=grid(["c"], dose=[3]), - equilibrate=True, reconstruct=True) + r = detect( + {"x1": "x2 - x1 + k4", "x2": "-k1*x2 - k2*x2 + u", "u": "-u"}, + {"y": "x1"}, + inputs=["u"], + events=[event("u", 0, "dose", "replace")], + conditions=grid(["c"], dose=[3]), + equilibrate=True, + reconstruct=True, + ) assert (r.rank, r.dim) == (2, 3) assert [d.generator for d in r.symmetries] == [{"k1": "1", "k2": "-1"}] @@ -1477,6 +1724,7 @@ def test_small_root_finder_matches_sympy(): from sympy.polys.domains import ZZ from symident.sym.gfpoly import _x_pow_mod + p, rng = 1518500183, random.Random(3) for n in range(1, 9): f = [1] + [rng.randrange(p) for _ in range(n)] @@ -1486,14 +1734,22 @@ def test_small_root_finder_matches_sympy(): def test_unobserved_production_branch_keeps_independent_directions(): rx = network(("A", "B", "kf*u*A"), ("B", "A", "kr*B"), ("", "P", "kin*B"), ("P", "", "kdeg*P")) for gauge in (None, False): - r = detect(reactions=rx, observables={"y": "A + B"}, conditions=grid(["a", "b"], u=[1, 4]), - equilibrate=True, reduce_cq=True, reconstruct=True, gauge=gauge) + r = detect( + reactions=rx, + observables={"y": "A + B"}, + conditions=grid(["a", "b"], u=[1, 4]), + equilibrate=True, + reduce_cq=True, + reconstruct=True, + gauge=gauge, + ) assert (r.rank, r.dim, len(r.symmetries)) == (1, 5, 4) assert r.reduce().remaining == [] def test_modular_values_take_decimals_exactly_and_refuse_irrationals(): from symident.sym.modp import eval_rational_mod + assert eval_rational_mod("0.5*k", ["k"], [3], 7) == 3 * pow(2, 5, 7) % 7 with pytest.raises(TypeError): eval_rational_mod("sqrt(k)", ["k"], [2], 7) @@ -1501,6 +1757,7 @@ def test_modular_values_take_decimals_exactly_and_refuse_irrationals(): def test_direction_check_fails_where_a_leaf_component_does_not_evaluate(): from symident.detection.verify import verify_direction + znames, leaves = ["a", "b", "x_c1"], ["a", "b"] def kcall(pt, q, nt): @@ -1508,6 +1765,7 @@ def kcall(pt, q, nt): def residues(rq, q, z): return np.array([1, 2, 5]) + ok = {"vector": {"a": "1", "b": "2", "x_c1": "x_c1^2"}} assert verify_direction(ok, 0, znames, leaves, [3, 4], 1, kcall, residues) pole = {"vector": {"a": "1", "b": "2 + 1/(a - a)"}} @@ -1518,6 +1776,7 @@ def residues(rq, q, z): def test_rate_zero_test_is_exact_for_rational_rates(): from symident.detection.cq import _expr_is_zero + assert not _expr_is_zero("1e-10*x", set()) assert _expr_is_zero("k*x*y", {"y"}) and _expr_is_zero("k1*x - k1*x", set()) assert not _expr_is_zero("k/(1 + y)", {"y"}) @@ -1525,6 +1784,7 @@ def test_rate_zero_test_is_exact_for_rational_rates(): def test_rate_zero_test_is_exact_for_other_rates(): from symident.detection.cq import _expr_is_zero + assert _expr_is_zero("k*exp(x)*y", {"y"}) and _expr_is_zero("log(1 + y)*k", {"y"}) assert _expr_is_zero("sqrt(k)*x - k^(1/2)*x", set()) assert not _expr_is_zero("1e-12*exp(x)", set()) and not _expr_is_zero("exp(y) - 1 + x", {"y", "z"}) @@ -1532,6 +1792,7 @@ def test_rate_zero_test_is_exact_for_other_rates(): def test_the_sink_weights_solve_the_lp_exactly(): from symident.detection.cq import _exact_lp, _sink_cluster + # rows are reactions, columns species assert _sink_cluster(np.array([[-1.0, 0.0], [0.0, 1.0]]))[0] == [0] assert _sink_cluster(np.array([[-1.0, 1.0], [1.0, -1.0]]))[0] == [] @@ -1539,8 +1800,10 @@ def test_the_sink_weights_solve_the_lp_exactly(): p, q = 1000003, 999983 M = [[-p, q], [p, -q], [-1, 0]] assert _sink_cluster(np.array(M, dtype=float))[0] == [0] - assert _exact_lp([[Fraction(a) for a in row] for row in M], [Fraction(-1), Fraction(0)]) == \ - [Fraction(q, p), Fraction(1)] + assert _exact_lp([[Fraction(a) for a in row] for row in M], [Fraction(-1), Fraction(0)]) == [ + Fraction(q, p), + Fraction(1), + ] def test_scalings_only_reports_terms_left_out(): @@ -1554,22 +1817,27 @@ def test_names_that_sympy_holds_as_functions_or_constants_are_symbols(): r = detect({"S": "b - k*S", "N": "k*S - d*N"}, {"y": "s*N"}, reconstruct=True) assert (r.rank, r.dim) == (5, 6) gens = [g.sympy() for g in r.symmetries] - assert all(isinstance(k, str) and v.free_symbols <= {spy.Symbol(n) for n in ("S", "N", "b", "k", "d", "s")} - for g in gens for k, v in g.items()) + assert all( + isinstance(k, str) and v.free_symbols <= {spy.Symbol(n) for n in ("S", "N", "b", "k", "d", "s")} + for g in gens + for k, v in g.items() + ) def _kernel_ref(vectors, nz, p): """The reduced rows of a matrix whose kernel the integer `vectors` span.""" from symident.gfp import rref_modp + K = spy.Matrix(vectors).T A = [list(v.T) for v in K.T.nullspace()] A = [[int(x * spy.lcm([spy.fraction(y)[1] for y in row])) for x in row] for row in A] rr = rref_modp(np.array(A, dtype=np.int64) % p, p) - return {"R": rr["R"][:rr["rank"]], "pivots": rr["piv"], "rank": rr["rank"], "dim": nz, "ok": True} + return {"R": rr["R"][: rr["rank"]], "pivots": rr["piv"], "rank": rr["rank"], "dim": nz, "ok": True} def test_minimal_support_beyond_six_coordinates(): from symident.gfp import PRIMES, minsupport_gauge + p, nz = PRIMES[0], 14 wide = [1, 2, 3, 4, 5, 6, 7, 8, 9] + [0] * 5 narrow = [0] * 9 + [1, 1, 0, 0, 0] @@ -1585,6 +1853,7 @@ def test_minimal_support_beyond_six_coordinates(): def test_entry_degrees_along_lines(): from symident.detection.interp import entry_degrees from symident.gfp import PRIMES + p = PRIMES[0] def kbatch(pts, primes, nt): @@ -1594,6 +1863,7 @@ def nv(rp, q, z): x1, x2, x3 = (int(rp["pt"][i]) for i in (1, 2, 3)) inv = lambda a: pow(a % p, p - 2, p) # noqa: E731 return [1, (x1 * x1 + x2) * inv(x1 + 3) % p, x1 * x2 * x3 % p, inv(pow(x1, 5, p))] + rel = {"relevant": [1, 2, 3], "support_cols": [1, 2, 3], "rel_by_entry": [[1, 2], [1, 2, 3], [1]]} ctrl = si.reconst_control() # an entry past degree_cap is found when the bound doubles, and stays over below it @@ -1604,8 +1874,7 @@ def nv(rp, q, z): def test_several_resting_branches_are_recorded(): f = {"x": "c + a*x - b*x^3 + kin*u - d*x*z", "z": "e*x - g*z", "u": "0"} - m = si.Model(f, {"y": "s*x"}, inputs=["u"], - events=[{"var": "u", "time": 0, "value": "1", "method": "replace"}]) + m = si.Model(f, {"y": "s*x"}, inputs=["u"], events=[{"var": "u", "time": 0, "value": "1", "method": "replace"}]) # the forward seed names the component it samples and picks no root br = si.detect(m, equilibrate=True).info["branches"] assert len(br) == 1 and br[0].startswith("forward seed") @@ -1617,21 +1886,37 @@ def test_several_resting_branches_are_recorded(): def test_a_start_on_a_curved_invariant_set_leaves_the_lie_order_unproven(): - m = si.Model({"x1": "-w*x2 - k*x1*(x1^2 + x2^2 - 1)", "x2": "w*x1 - k*x2*(x1^2 + x2^2 - 1)"}, {"y": "s*x1"}, - trafo={"x1": "1", "x2": "0"}) + m = si.Model( + {"x1": "-w*x2 - k*x1*(x1^2 + x2^2 - 1)", "x2": "w*x1 - k*x2*(x1^2 + x2^2 - 1)"}, + {"y": "s*x1"}, + trafo={"x1": "1", "x2": "0"}, + ) r = si.detect(m, reconstruct=True) assert (r.rank, r.dim) == (2, 3) and [s.support for s in r.symmetries] == [["k"]] assert r.info["lie_certified"] is False - assert r.info["rank_status"] == {"status": "lower bound", "why": "the Lie order is not proven sufficient", - "probability": None} + assert r.info["rank_status"] == { + "status": "lower bound", + "why": "the Lie order is not proven sufficient", + "probability": None, + } def _autocrine(times, **kw): - f = {"L": "ksec*m/(V*vf) - kon*L*R + koff*C - kdL*L", "R": "kR - kon*L*R + koff*C - kdR*R", - "C": "kon*L*R - koff*C - kc*C", "m": "kb + ka*C - dm*m"} - return detect(f, {"y": "s*m", "yC": "C"}, conditions=grid(["a", "b"], vf=[1, 1.5], dose=[1, 1]), - events=[event("L", t, "dose", "add") for t in times], equilibrate=True, reconstruct=True, - **kw) + f = { + "L": "ksec*m/(V*vf) - kon*L*R + koff*C - kdL*L", + "R": "kR - kon*L*R + koff*C - kdR*R", + "C": "kon*L*R - koff*C - kc*C", + "m": "kb + ka*C - dm*m", + } + return detect( + f, + {"y": "s*m", "yC": "C"}, + conditions=grid(["a", "b"], vf=[1, 1.5], dose=[1, 1]), + events=[event("L", t, "dose", "add") for t in times], + equilibrate=True, + reconstruct=True, + **kw, + ) @pytest.mark.parametrize("times", [[0], [0, 10]]) @@ -1643,21 +1928,28 @@ def test_the_diagonal_start_lifts_coupled_conditions_without_a_resting_solve(mon def no_solve(*a, **k): raise AssertionError("resting state solved at a point") + monkeypatch.setattr(rest, "solve_steady_state_modular", no_solve) r = _autocrine(times) assert (r.rank, r.dim) == (ref.rank, ref.dim) - assert sorted(map(tuple, (s.support for s in r.symmetries))) == \ - sorted(map(tuple, (s.support for s in ref.symmetries))) + assert sorted(map(tuple, (s.support for s in r.symmetries))) == sorted( + map(tuple, (s.support for s in ref.symmetries)) + ) def test_the_diagonal_start_zeroes_the_secretion_that_couples_the_conditions(): from symident.detection.observability.start import DiagonalStart - m = ["L = ksec*m/(V*vf) - kon*L*R + koff*C - kdL*L", "R = kR - kon*L*R + koff*C - kdR*R", - "C = kon*L*R - koff*C - kc*C", "m = kb + ka*C - dm*m"] + m = [ + "L = ksec*m/(V*vf) - kon*L*R + koff*C - kdL*L", + "R = kR - kon*L*R + koff*C - kdR*R", + "C = kon*L*R - koff*C - kc*C", + "m = kb + ka*C - dm*m", + ] models = [[s.replace("vf", "1") for s in m], [s.replace("vf", "1.5") for s in m]] - ds = DiagonalStart(models, [0, 1], 0, lambda ci: [], ["ksec", "kon", "koff", "kdL", "kR", "kdR", "kc", "kb", - "ka", "dm", "V"]) + ds = DiagonalStart( + models, [0, 1], 0, lambda ci: [], ["ksec", "kon", "koff", "kdL", "kR", "kdR", "kc", "kb", "ka", "dm", "V"] + ) assert ds.ok and ds.Z == ["ksec"] and ds.S == ["C", "L"] bad = DiagonalStart(models, [0, 1], 0, lambda ci: [], ["V"]) assert not bad.ok @@ -1672,29 +1964,42 @@ def test_an_event_after_the_start_leaves_the_start_at_zero(): def test_names_sympy_reserves_stay_coordinates_in_closed_forms(): from symident.detection.closedform import simplify + assert spy.simplify(model_sympify(simplify("I**2*k")) - model_sympify("I^2*k")) == 0 assert "log(E)" in simplify("log(E)*k") - r = detect({"C": "Ef+Eb+Ep-k*C", "C13": "Ef*rf+Eb*rb+Ep*rp-a*k*C13"}, {"CH4": "C", "ratio": "C13/C"}, - fixed=["rf", "rb", "rp", "a"], reconstruct=True) + r = detect( + {"C": "Ef+Eb+Ep-k*C", "C13": "Ef*rf+Eb*rb+Ep*rp-a*k*C13"}, + {"CH4": "C", "ratio": "C13/C"}, + fixed=["rf", "rb", "rp", "a"], + reconstruct=True, + ) assert not r.info["errors"] def test_a_state_named_e_keeps_its_closed_form(): - r = detect({"E": "b*(al*P+I+al*A)-E/De", "P": "E/De-P/Dp", "I": "r*P/Dp-I/Di", "A": "(1-r)*P/Dp-A/Di"}, - {"y": "r*P/Dp"}, fixed=["De", "Dp", "Di"], reconstruct=True) + r = detect( + {"E": "b*(al*P+I+al*A)-E/De", "P": "E/De-P/Dp", "I": "r*P/Dp-I/Di", "A": "(1-r)*P/Dp-A/Di"}, + {"y": "r*P/Dp"}, + fixed=["De", "Dp", "Di"], + reconstruct=True, + ) assert not r.info["errors"] and all("exp" not in str(s.generator) for s in r.symmetries) curved = [s.generator for s in r.symmetries if "E" in s.generator] - assert curved and all(spy.simplify(model_sympify(g["E"]) / model_sympify(g["P"]) - spy.Symbol("E") / - spy.Symbol("P")) == 0 for g in curved) + assert curved and all( + spy.simplify(model_sympify(g["E"]) / model_sympify(g["P"]) - spy.Symbol("E") / spy.Symbol("P")) == 0 + for g in curved + ) def test_a_premature_lie_order_is_extended(): from symident.detection.core import _past_premature_order + calls = [] def oam(): calls.append(state.get("nt_floor")) return {"verification": {"ok": True}} + out = _past_premature_order(oam, {"verification": {"ok": False, "grow_at": 14}}) assert out["verification"]["ok"] and calls == [14 + int(state.env_value("LIEPLATEAU", "3"))] @@ -1715,10 +2020,15 @@ def test_free_exponents_of_states_with_given_initial_values(): def test_a_kernel_in_log_coordinates_is_renamed_back(): - ev = [{"var": "P", "time": i, "value": str(v), "method": "replace"} for i, v in enumerate([3, 0, 8])] + \ - [{"var": "PET", "time": i, "value": str(v), "method": "replace"} for i, v in enumerate([1, 2, 1])] - odes = {"SM": "P - P*SM^BETA/FC^BETA - PET*min(SM/(LP*FC),1)", "SUZ": "P*SM^BETA/FC^BETA - K1*SUZ", - "P": "0", "PET": "0"} + ev = [{"var": "P", "time": i, "value": str(v), "method": "replace"} for i, v in enumerate([3, 0, 8])] + [ + {"var": "PET", "time": i, "value": str(v), "method": "replace"} for i, v in enumerate([1, 2, 1]) + ] + odes = { + "SM": "P - P*SM^BETA/FC^BETA - PET*min(SM/(LP*FC),1)", + "SUZ": "P*SM^BETA/FC^BETA - K1*SUZ", + "P": "0", + "PET": "0", + } assert detect(odes, {"Q": "K1*SUZ"}, inputs=["P", "PET"], events=ev).identifiable @@ -1727,27 +2037,34 @@ def test_a_size_cap_in_the_gap_bound_leaves_no_bound(monkeypatch): def boom(*a): raise OverflowError("a Lie derivative grows past the size cap") + monkeypatch.setattr(gapcert, "_gap_bound", boom) assert gapcert.gap_bound([], [], [], 1, 7, None)["bound"] is None def test_the_combined_lift_solves_the_square_subsystem(): from symident.detection.fields import _square_solve + a, b = spy.symbols("a b") A = spy.Matrix([[a, 1], [2 * a, 2], [1, b]]) c = _square_solve(A, A * spy.Matrix([b, a])) assert [spy.cancel(x) for x in c] == [b, a] from symident.sym.direction import _canon_int_vector + assert _canon_int_vector([spy.E * a], [a]) is None def test_a_signed_net_uptake_rests_at_zero(): rx = network(("", "X", "ki*(lev*u - X)"), ("X", "Y", "kf*X"), ("", "Y", "kb"), ("Y", "", "kd*Y")) rx = dict(rx, species=rx["species"] + ["u"], stoichiometry=[r + [0] for r in rx["stoichiometry"]]) - res = detect(reactions=rx, observables={"y": "s*Y"}, inputs=["u"], events=[event("u", 0, "1")], - equilibrate=True) - ex = detect({"X": "ki*(lev*u - X)", "Y": "kf*X + kb - kd*Y", "u": "0"}, {"y": "s*Y"}, inputs=["u"], - events=[event("u", 0, "1")], trafo={"X": "0", "Y": "kb/kd"}) + res = detect(reactions=rx, observables={"y": "s*Y"}, inputs=["u"], events=[event("u", 0, "1")], equilibrate=True) + ex = detect( + {"X": "ki*(lev*u - X)", "Y": "kf*X + kb - kd*Y", "u": "0"}, + {"y": "s*Y"}, + inputs=["u"], + events=[event("u", 0, "1")], + trafo={"X": "0", "Y": "kb/kd"}, + ) assert res.rank == ex.rank @@ -1767,16 +2084,23 @@ def test_a_repeated_reduction_is_a_copy_of_the_first(monkeypatch): def test_exponentials_of_parameters_outside_the_resting_model_under_equilibrate(): ev = [event("u", 1, "exp(5*(1-c)/c)")] - eq = detect({"x": "b - k*x + u", "u": "0"}, {"y": "s*x"}, inputs=["u"], events=ev, equilibrate=True, - reconstruct=True) - ex = detect({"x": "b - k*x + u", "u": "0"}, {"y": "s*x"}, inputs=["u"], events=ev, trafo={"x": "b/k"}, - reconstruct=True) + eq = detect( + {"x": "b - k*x + u", "u": "0"}, {"y": "s*x"}, inputs=["u"], events=ev, equilibrate=True, reconstruct=True + ) + ex = detect( + {"x": "b - k*x + u", "u": "0"}, {"y": "s*x"}, inputs=["u"], events=ev, trafo={"x": "b/k"}, reconstruct=True + ) assert (eq.rank, eq.dim) == (ex.rank, ex.dim) and "_ew" not in str(eq.info["coordinates"]) def test_a_state_idle_at_rest_keeps_a_resting_value(): - r = detect({"x": "b - k*x + u", "z": "kz*u", "u": "0"}, {"y": "s*x + z"}, inputs=["u"], - events=[event("u", 0, "1")], equilibrate=True) + r = detect( + {"x": "b - k*x + u", "z": "kz*u", "u": "0"}, + {"y": "s*x + z"}, + inputs=["u"], + events=[event("u", 0, "1")], + equilibrate=True, + ) assert "z" in r.info["coordinates"] @@ -1810,10 +2134,13 @@ def test_a_missing_msolve_names_its_installation(monkeypatch): def test_a_spike_train_with_state_dependent_events(): ev = [] for t in [f"{k}/10" for k in range(5, 20)]: - ev += [event("u", t, "u+U*(1-u)"), event("Is", f"{t}+1/1000", "Is+A*u*x"), - event("x", f"{t}+2/1000", "x-u*x")] - r = detect({"x": "(1-x)/tD", "u": "(U-u)/tF", "Is": "-Is/ts"}, {"y": "Is"}, events=ev, - trafo={"x": "1", "u": "0", "Is": "0"}) + ev += [event("u", t, "u+U*(1-u)"), event("Is", f"{t}+1/1000", "Is+A*u*x"), event("x", f"{t}+2/1000", "x-u*x")] + r = detect( + {"x": "(1-x)/tD", "u": "(U-u)/tF", "Is": "-Is/ts"}, + {"y": "Is"}, + events=ev, + trafo={"x": "1", "u": "0", "Is": "0"}, + ) assert r.identifiable @@ -1823,40 +2150,60 @@ def brief(r): def test_a_compound_replacement_binds_as_one_operand(): from symident.rexpr import replace_symbols + assert replace_symbols(["k"], ["a+b"], "-k*x") == "-(a+b)*x" assert replace_symbols(["k"], ["-1"], "k") == "-1" assert replace_symbols(["k"], ["exp(l)"], "-k*x") == "-exp(l)*x" -@pytest.mark.parametrize("kw", [ - dict(odes={"x": "-k*x"}), - dict(odes={"x": "-c*x"}, trafo={"x": "1"}, conditions=grid(["p", "q"], c=["1", "c*k"])), - dict(odes={"x": "-c*x"}, trafo={"x": "1"}, events=[event("x", "1", "c*k", "add")]), - dict(odes={"x": "-c*x"}, trafo=[{"x": "1"}, {"x": "2"}], events=[event("x", "1", "c*k", "add")]), - dict(odes={"x": "u - k*x", "u": "0"}, trafo=[{}, {}], inputs=["u"], events=[event("u", "0", "1")], - equilibrate=True), -]) +@pytest.mark.parametrize( + "kw", + [ + dict(odes={"x": "-k*x"}), + dict(odes={"x": "-c*x"}, trafo={"x": "1"}, conditions=grid(["p", "q"], c=["1", "c*k"])), + dict(odes={"x": "-c*x"}, trafo={"x": "1"}, events=[event("x", "1", "c*k", "add")]), + dict(odes={"x": "-c*x"}, trafo=[{"x": "1"}, {"x": "2"}], events=[event("x", "1", "c*k", "add")]), + dict( + odes={"x": "u - k*x", "u": "0"}, + trafo=[{}, {}], + inputs=["u"], + events=[event("u", "0", "1")], + equilibrate=True, + ), + ], +) def test_a_compound_trafo_value_equals_its_parenthesized_form(kw): def run(v): tr = kw.get("trafo") tr = [dict(t, k=v) for t in tr] if isinstance(tr, list) else dict(tr or {}, k=v) return detect(observables={"y": "x"}, **dict(kw, trafo=tr)) + assert brief(run("a+b")) == brief(run("(a+b)")) -@pytest.mark.parametrize("clock, plain", [ - (dict(trafo={"x": "a + time"}), dict(trafo={"x": "a"})), - (dict(trafo={"x": "a + time"}, events=[event("x", "-1", "c", "add")]), - dict(trafo={"x": "a - 1"}, events=[event("x", "-1", "c", "add")])), - (dict(trafo={"x": "1"}, events=[event("x", "2", "c*time", "add")]), - dict(trafo={"x": "1"}, events=[event("x", "2", "2*c", "add")])), - (dict(trafo={"k": "a*time"}), dict(odes={"x": "-a*time*x"})), - (dict(trafo=[{"x": "1", "k": "a*time"}, {"x": "2", "k": "a*time"}]), - dict(odes={"x": "-a*time*x"}, trafo=[{"x": "1"}, {"x": "2"}])), -]) +@pytest.mark.parametrize( + "clock, plain", + [ + (dict(trafo={"x": "a + time"}), dict(trafo={"x": "a"})), + ( + dict(trafo={"x": "a + time"}, events=[event("x", "-1", "c", "add")]), + dict(trafo={"x": "a - 1"}, events=[event("x", "-1", "c", "add")]), + ), + ( + dict(trafo={"x": "1"}, events=[event("x", "2", "c*time", "add")]), + dict(trafo={"x": "1"}, events=[event("x", "2", "2*c", "add")]), + ), + (dict(trafo={"k": "a*time"}), dict(odes={"x": "-a*time*x"})), + ( + dict(trafo=[{"x": "1", "k": "a*time"}, {"x": "2", "k": "a*time"}]), + dict(odes={"x": "-a*time*x"}, trafo=[{"x": "1"}, {"x": "2"}]), + ), + ], +) def test_time_outside_the_right_hand_sides_is_the_clock(clock, plain): def run(kw): return detect(**{"odes": {"x": "-k*x"}, "observables": {"y": "x"}, **kw}, reconstruct=True) + r = run(clock) assert brief(r) == brief(run(plain)) and "time" not in r.info["coordinates"] @@ -1883,22 +2230,29 @@ def test_the_clock_under_equilibrate_is_an_input_from_the_start(): def _scaling_rows(r): """The weights of the scalings of `r` over the coordinates of `r`, a zero row without one.""" c = r.info["coordinates"] - return spy.Matrix([[int(s.weights.get(z, 0)) for z in c] for s in r.symmetries if s.type == "scaling"] or - [[0] * len(c)]) - - -@pytest.mark.parametrize("odes, obs, kw", [ - ({"x": "-d*x"}, {"y": "s*x"}, dict(trafo={"x": "1"})), - ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "0", "1")])), - ({"x": "-d*x"}, {"y": "s*x"}, dict(conditions=grid(["c1"], s=[2]))), - ({"x": "-d*x"}, {"y": "s*x"}, dict(conditions=grid(["c1", "c2"], s=[2, 3]))), - ({"x": "-k*x + b*u"}, {"y": "x"}, dict(known_inputs=["u"])), - ({"x": "-d*x"}, {"y": "s*x"}, dict(trafo=[{"x": "1"}, {"x": "2"}])), - ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "1", "c", "add")])), - ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "tau", "c", "add")])), - ({"x": "kb + kin*u - k*x", "u": "0"}, {"y": "s*x"}, dict(inputs=["u"], events=[event("u", "0", "dose")], - equilibrate=True)), -]) + return spy.Matrix( + [[int(s.weights.get(z, 0)) for z in c] for s in r.symmetries if s.type == "scaling"] or [[0] * len(c)] + ) + + +@pytest.mark.parametrize( + "odes, obs, kw", + [ + ({"x": "-d*x"}, {"y": "s*x"}, dict(trafo={"x": "1"})), + ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "0", "1")])), + ({"x": "-d*x"}, {"y": "s*x"}, dict(conditions=grid(["c1"], s=[2]))), + ({"x": "-d*x"}, {"y": "s*x"}, dict(conditions=grid(["c1", "c2"], s=[2, 3]))), + ({"x": "-k*x + b*u"}, {"y": "x"}, dict(known_inputs=["u"])), + ({"x": "-d*x"}, {"y": "s*x"}, dict(trafo=[{"x": "1"}, {"x": "2"}])), + ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "1", "c", "add")])), + ({"x": "-d*x"}, {"y": "s*x"}, dict(events=[event("x", "tau", "c", "add")])), + ( + {"x": "kb + kin*u - k*x", "u": "0"}, + {"y": "s*x"}, + dict(inputs=["u"], events=[event("u", "0", "dose")], equilibrate=True), + ), + ], +) def test_scalings_only_holds_the_values_the_detection_holds(odes, obs, kw): full = detect(odes, obs, reconstruct=True, **kw) sc = detect(odes, obs, scalings_only=True, **kw) @@ -1907,16 +2261,23 @@ def test_scalings_only_holds_the_values_the_detection_holds(odes, obs, kw): assert a.rank() == b.rank() == spy.Matrix.vstack(a, b).rank() -@pytest.mark.parametrize("kw", [ - dict(conditions=grid(["a", "b"], tau=[0, 1])), - dict(trafo=[{"x": "1", "tau": "0"}, {"x": "1", "tau": "1"}]), -]) +@pytest.mark.parametrize( + "kw", + [ + dict(conditions=grid(["a", "b"], tau=[0, 1])), + dict(trafo=[{"x": "1", "tau": "0"}, {"x": "1", "tau": "1"}]), + ], +) def test_an_event_time_resolved_per_condition(kw): ev = [event("x", "tau", "c", "add")] kw = dict({"trafo": {"x": "1"}}, **kw) r = detect({"x": "-k*x"}, {"y": "x"}, events=ev, **kw) - ref = detect({"x": "-k*x"}, {"y": "x"}, trafo=[{"x": "1"}, {"x": "1"}], - events=[dict(ev[0], time="0", cond=[0]), dict(ev[0], time="1", cond=[1])]) + ref = detect( + {"x": "-k*x"}, + {"y": "x"}, + trafo=[{"x": "1"}, {"x": "1"}], + events=[dict(ev[0], time="0", cond=[0]), dict(ev[0], time="1", cond=[1])], + ) assert brief(r) == brief(ref) one = detect({"x": "-k*x"}, {"y": "x"}, events=ev, trafo={"x": "1"}, conditions=grid(["a"], tau=[0])) assert brief(one) == brief(detect({"x": "-k*x"}, {"y": "x"}, events=ev, trafo={"x": "1", "tau": "0"})) @@ -1924,20 +2285,38 @@ def test_an_event_time_resolved_per_condition(kw): def test_the_segments_of_a_condition_follow_its_resolved_event_times(): from symident.detection.conditions import Grid, as_events, resolve_conditions - res = resolve_conditions(Grid(["a", "b"], {"tau": [0, 1]}), as_events([event("x", "tau", "c", "add")]), - {"x": "1"}, ["x", "k", "c", "tau"], ["x"]) + + res = resolve_conditions( + Grid(["a", "b"], {"tau": [0, 1]}), + as_events([event("x", "tau", "c", "add")]), + {"x": "1"}, + ["x", "k", "c", "tau"], + ["x"], + ) assert res["chain_of"] == [1, 2, 2] and res["times"] == ["0", "0", "1"] - assert res["ic0"][0] == {"x": "(1) + (c)"} and res["seg_events"][2] == [ - {"var": "x", "method": "add", "value": "c"}] + assert res["ic0"][0] == {"x": "(1) + (c)"} and res["seg_events"][2] == [{"var": "x", "method": "add", "value": "c"}] def test_reduce_cq_reads_the_totals_of_an_ode_model(): ev = [event("u", "0", "1")] - ode = si.Model({"A": "-k1*A*(1+u) + k2*B", "B": "k1*A*(1+u) - k2*B", "u": "0"}, {"y": "s*B"}, inputs=["u"], - events=ev, totals={"T": "A + B"}) - rx = si.Model(reactions={"species": ["A", "B", "u"], "stoichiometry": [[-1, 1, 0], [1, -1, 0]], - "rates": ["k1*A*(1+u)", "k2*B"]}, observables={"y": "s*B"}, inputs=["u"], events=ev, - totals={"T": "A + B"}) + ode = si.Model( + {"A": "-k1*A*(1+u) + k2*B", "B": "k1*A*(1+u) - k2*B", "u": "0"}, + {"y": "s*B"}, + inputs=["u"], + events=ev, + totals={"T": "A + B"}, + ) + rx = si.Model( + reactions={ + "species": ["A", "B", "u"], + "stoichiometry": [[-1, 1, 0], [1, -1, 0]], + "rates": ["k1*A*(1+u)", "k2*B"], + }, + observables={"y": "s*B"}, + inputs=["u"], + events=ev, + totals={"T": "A + B"}, + ) for eq in (False, True): a, b = si.detect(ode, equilibrate=eq, reduce_cq=True), si.detect(rx, equilibrate=eq, reduce_cq=True) assert brief(a) == brief(b) and "T" in a.info["coordinates"] @@ -1947,33 +2326,46 @@ def test_reduce_cq_reads_the_totals_of_an_ode_model(): def test_the_totals_of_a_reaction_network_are_integer_combinations(): - rx = si.Model(reactions={"species": ["A", "B", "C"], "stoichiometry": [[-1.0, 1.0, 0.0], [0.0, -2.0, 1.0]], - "rates": ["k1*A", "k2*B^2"]}, observables={"y": "s*C"}) + rx = si.Model( + reactions={ + "species": ["A", "B", "C"], + "stoichiometry": [[-1.0, 1.0, 0.0], [0.0, -2.0, 1.0]], + "rates": ["k1*A", "k2*B^2"], + }, + observables={"y": "s*C"}, + ) assert rx.totals == {"total1": "A + B + 2*C"} - still = si.Model(reactions={"species": ["A"], "stoichiometry": [[0.0]], "rates": ["k*A"]}, - observables={"y": "s*A"}) + still = si.Model(reactions={"species": ["A"], "stoichiometry": [[0.0]], "rates": ["k*A"]}, observables={"y": "s*A"}) assert still.totals == {"total1": "A"} def test_a_total_whose_coefficients_hold_a_volume(): # a declared total with a parameter in the coefficients replaces a state as a coordinate - m = si.Model({"A": "-k1*A*(1+u) + V*k2*B", "B": "k1*A*(1+u)/V - k2*B", "u": "0"}, {"y": "s*B"}, - inputs=["u"], events=[event("u", "0", "1")], totals={"T": "A + V*B"}) + m = si.Model( + {"A": "-k1*A*(1+u) + V*k2*B", "B": "k1*A*(1+u)/V - k2*B", "u": "0"}, + {"y": "s*B"}, + inputs=["u"], + events=[event("u", "0", "1")], + totals={"T": "A + V*B"}, + ) r = si.detect(m, equilibrate=True, reduce_cq=True) assert (r.rank, r.dim) == (3, 5) and "T" in r.info["coordinates"] assert sorted(sorted(x.support) for x in r.symmetries) == [["T", "V"], ["V", "s"]] assert all(x.level == "exact" for x in r.symmetries) -@pytest.mark.parametrize("kw, name", [ - (dict(known_inputs=["U"]), "U"), - (dict(known_inputs=["x"]), "x"), - (dict(inputs=["U"]), "U"), - (dict(events=[event("X", "1", "c", "add")]), "X"), - (dict(conditions=grid(["lo", "hi"], Dose=[1, 10])), "Dose"), - (dict(fixed=["S"]), "S"), - (dict(parameters=["p"]), "p"), -]) +@pytest.mark.parametrize( + "kw, name", + [ + (dict(known_inputs=["U"]), "U"), + (dict(known_inputs=["x"]), "x"), + (dict(inputs=["U"]), "U"), + (dict(events=[event("X", "1", "c", "add")]), "X"), + (dict(conditions=grid(["lo", "hi"], Dose=[1, 10])), "Dose"), + (dict(fixed=["S"]), "S"), + (dict(parameters=["p"]), "p"), + ], +) def test_a_declared_name_outside_the_model_is_refused(kw, name): with pytest.raises(ValueError, match=f"\\b{name}\\b"): detect({"x": "-k*x + b*u"}, {"y": "s*x"}, **kw) @@ -1990,11 +2382,14 @@ def test_names_in_the_trafo_events_cells_and_totals_are_declared(): detect({"x": "-k*x"}, {"y": "x"}, positive=["k", "K", "1 - x"]) -@pytest.mark.parametrize("kw", [ - dict(trafo={"x": "0", "u": "w"}), - dict(trafo=[{"x": "0", "u": "1"}, {"x": "0", "u": "2"}]), - dict(trafo={"x": "0"}, conditions=grid(["a", "b"], u=[1, 2])), -]) +@pytest.mark.parametrize( + "kw", + [ + dict(trafo={"x": "0", "u": "w"}), + dict(trafo=[{"x": "0", "u": "1"}, {"x": "0", "u": "2"}]), + dict(trafo={"x": "0"}, conditions=grid(["a", "b"], u=[1, 2])), + ], +) def test_an_input_takes_no_initial_value(kw): with pytest.raises(ValueError, match="input u starts at zero"): detect({"x": "-k*x + b*u", "u": "-d*u"}, {"y": "x"}, inputs=["u"], **kw) @@ -2009,19 +2404,32 @@ def test_an_event_at_the_start_sets_an_input(start): def test_a_rate_set_to_zero_by_the_trafo_rests_like_a_constant_state(): ev = [event("u", "0", "1")] - zero = detect({"z": "-k*u*z", "w": "-j*u*w", "u": "0"}, {"y": "z*w"}, inputs=["u"], events=ev, - trafo={"k": "0"}, equilibrate=True) + zero = detect( + {"z": "-k*u*z", "w": "-j*u*w", "u": "0"}, + {"y": "z*w"}, + inputs=["u"], + events=ev, + trafo={"k": "0"}, + equilibrate=True, + ) idle = detect({"z": "0", "w": "-j*u*w", "u": "0"}, {"y": "z*w"}, inputs=["u"], events=ev, equilibrate=True) assert brief(zero) == brief(idle) - r = detect({"z": "-k*u*z", "w": "-j*u*w", "u": "0"}, {"y": "z*w"}, inputs=["u"], events=ev, equilibrate=True, - reconstruct=True) + r = detect( + {"z": "-k*u*z", "w": "-j*u*w", "u": "0"}, + {"y": "z*w"}, + inputs=["u"], + events=ev, + equilibrate=True, + reconstruct=True, + ) assert si.reduce(r, allow_checked=True).checks["loop"]["ok"] is not None def _ligand(method="replace", **kw): rx = network(("L", "L + R", "u*L"), ("R", "", "d*R"), ("A", "B", "k1*R*A + kb*A"), ("B", "A", "k2*B")) - return detect(reactions=rx, observables={"y": "s*B"}, events=[event("L", 0, "dose", method)], - equilibrate=True, **kw) + return detect( + reactions=rx, observables={"y": "s*B"}, events=[event("L", 0, "dose", method)], equilibrate=True, **kw + ) def supports_of(r, kind=None): @@ -2040,10 +2448,13 @@ def test_an_event_at_the_start_sets_a_constant_state_on_top_of_its_resting_value assert supports_of(r) == [["B", "s"], ["dose", "u"], ["k1", "u"]] -@pytest.mark.parametrize("method, scalings", [ - ("replace", [["B", "s"], ["L", "dose", "u"], ["k1", "u"]]), - ("multiply", [["B", "s"], ["L", "u"], ["k1", "u"]]), -]) +@pytest.mark.parametrize( + "method, scalings", + [ + ("replace", [["B", "s"], ["L", "dose", "u"], ["k1", "u"]]), + ("multiply", [["B", "s"], ["L", "u"], ["k1", "u"]]), + ], +) def test_an_exact_scaling_leaves_the_resting_model_invariant(method, scalings): assert supports_of(_ligand(method), "scaling") == scalings assert supports_of(_ligand(method, scalings_only=True)) == scalings @@ -2060,12 +2471,15 @@ def test_the_count_substitutes_the_trafo_into_the_initial_values(): def test_the_count_of_a_model_that_is_not_rational_is_none(): - for f, tr in [({"x1": "x2", "x2": "-(p+q)*x2 - p*q*abs(x1)"}, {"x1": "1", "x2": "0"}), - ({"x": "-k*x^n"}, {"x": "2"})]: + for f, tr in [ + ({"x1": "x2", "x2": "-(p+q)*x2 - p*q*abs(x1)"}, {"x1": "1", "x2": "0"}), + ({"x": "-k*x^n"}, {"x": "2"}), + ]: r = detect(f, {"y": "x1" if "x1" in f else "x"}, trafo=tr) assert r.identifiable and r.solution_count() is None - r = detect({"x1": "x2", "x2": "-(p+q)*x2 - p*q*x1 + piecewise(p, time > 1, 0)"}, {"y": "x1"}, - trafo={"x1": "1", "x2": "0"}) + r = detect( + {"x1": "x2", "x2": "-(p+q)*x2 - p*q*x1 + piecewise(p, time > 1, 0)"}, {"y": "x1"}, trafo={"x1": "1", "x2": "0"} + ) with pytest.raises(ValueError, match="switches"): r.solution_count() @@ -2120,14 +2534,17 @@ def test_a_free_moiety_is_held_by_the_state_that_closes_the_directions(): assert {s.level for s in detect(three, {"y": "s*B"}, equilibrate=True, reconstruct=True).symmetries} == {"exact"} -@pytest.mark.parametrize("names", [("a1", "a2", "b11", "b12", "b21", "b22"), - ("p35", "p30", "p17", "p58", "p21", "p81")]) +@pytest.mark.parametrize( + "names", [("a1", "a2", "b11", "b12", "b21", "b22"), ("p35", "p30", "p17", "p58", "p21", "p81")] +) def test_the_levels_do_not_depend_on_the_names(names): # the narrow route closes the third direction on another minimal support than the column order picks a1, a2, b11, b12, b21, b22 = names - r = detect(odes={"x1": f"x1*({a1} - {b11}*log(x1) - {b12}*log(x2))", - "x2": f"x2*({a2} - {b21}*log(x1) - {b22}*log(x2))"}, - observables={"y1": "x1"}, reconstruct=True) + r = detect( + odes={"x1": f"x1*({a1} - {b11}*log(x1) - {b12}*log(x2))", "x2": f"x2*({a2} - {b21}*log(x1) - {b22}*log(x2))"}, + observables={"y1": "x1"}, + reconstruct=True, + ) assert r.rank == 5 and r.info["rank_status"]["status"] == "proven" assert [s.level for s in r.symmetries] == ["exact"] * 3 @@ -2136,6 +2553,7 @@ def test_each_direction_has_the_kind_of_its_orbits(): import json from symident import rjson + m = si.Model({"x": "-(k1 + k2)*x*s", "z": "x"}, {"y": "z"}) r = si.detect(m, reconstruct=True) kinds = {s.kind: s for s in r.symmetries} @@ -2143,8 +2561,7 @@ def test_each_direction_has_the_kind_of_its_orbits(): assert kinds["translation"].type == "general" and kinds["translation"].level == "exact" assert "Translations:" in repr(r) and all("kind" in d for d in r.to_dict()["symmetries"]) # a curved direction: the outflow k1 + kl is kept while k1 moves in proportion to itself - curved = si.detect(si.Model({"x1": "kb - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "x2"}), - reconstruct=True) + curved = si.detect(si.Model({"x1": "kb - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "x2"}), reconstruct=True) assert [s.kind for s in curved.symmetries] == ["curved"] and "Curved:" in repr(curved) # the labels of the reduction follow the same order: scalings, then translations red = r.reduce().to_dict() @@ -2157,9 +2574,16 @@ def test_a_scaling_that_moves_the_states_of_some_resting_conditions_only_is_exac # a parameter scales the total in some conditions only, with the resting states and the scale factors there ev = [{"var": "u", "time": "0", "value": "1"}] tr = [{"H": h, "u": "0"} for h in ("0", "1", "1", "0")] - r = detect({"P": "r*(1+u)*(exp(H*d) - P) - ki*P", "u": "0"}, [{f"y{i}": f"s{i}*P"} for i in range(4)], - trafo=tr, conditions={"rows": [f"c{i}" for i in range(4)], "cols": {}}, events=ev, inputs=["u"], - equilibrate=True, reconstruct=True) + r = detect( + {"P": "r*(1+u)*(exp(H*d) - P) - ki*P", "u": "0"}, + [{f"y{i}": f"s{i}*P"} for i in range(4)], + trafo=tr, + conditions={"rows": [f"c{i}" for i in range(4)], "cols": {}}, + events=ev, + inputs=["u"], + equilibrate=True, + reconstruct=True, + ) assert (r.rank, r.dim) == (6, 7) and r.info["rank_status"]["status"] == "proven" (d,) = r.symmetries assert d.level == "exact" and d.generator == {"d": "1", "s1": "-s1", "s2": "-s2"} diff --git a/tests/test_determinism.py b/tests/test_determinism.py index 0beadf0..af05bf9 100644 --- a/tests/test_determinism.py +++ b/tests/test_determinism.py @@ -44,8 +44,15 @@ def _runs(settings): procs = [] for hashseed, cores in settings: env = dict(os.environ, PYTHONHASHSEED=str(hashseed)) - procs.append(subprocess.Popen([sys.executable, "-c", RUN, str(cores)], env=env, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)) + procs.append( + subprocess.Popen( + [sys.executable, "-c", RUN, str(cores)], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + ) outs = [] for p in procs: out, err = p.communicate(timeout=600) @@ -66,22 +73,27 @@ def test_same_result_in_every_process(settings): def test_session_seeds_depend_on_seed_model_and_stage_only(): from symident.session import Session + s = Session(0, "m") assert s.seed("point", 1) == 7274323681973122755 assert s.rng("x", "a", 2).random() == s.rng("x", "a", 2).random() - assert len({Session(0, "m").seed("p"), Session(1, "m").seed("p"), Session(0, "n").seed("p"), - s.seed("q")}) == 4 + assert len({Session(0, "m").seed("p"), Session(1, "m").seed("p"), Session(0, "n").seed("p"), s.seed("q")}) == 4 -INH = dict(odes={"R": "-kR*R", "S": "kact*R/(1 + kinh*I) - kd*S", "I": "b + ks*S - dI*I"}, - observables={"z": "s2*S"}, - events=[{"var": "R", "time": 0, "value": "d0", "method": "add"}, - {"var": "R", "time": 1, "value": "d1", "method": "add"}], - conditions={"rows": ["a", "b"], "cols": {"d0": [1, 2], "d1": [1, 1]}}) +INH = dict( + odes={"R": "-kR*R", "S": "kact*R/(1 + kinh*I) - kd*S", "I": "b + ks*S - dI*I"}, + observables={"z": "s2*S"}, + events=[ + {"var": "R", "time": 0, "value": "d0", "method": "add"}, + {"var": "R", "time": 1, "value": "d1", "method": "add"}, + ], + conditions={"rows": ["a", "b"], "cols": {"d0": [1, 2], "d1": [1, 1]}}, +) def _detect(**kw): import symident as si + d = si.detect(si.Model(**INH), reconstruct=True, equilibrate=True, **kw).to_dict() d["info"].pop("elapsed", None) d["info"].pop("timing", None) @@ -90,6 +102,7 @@ def _detect(**kw): def test_the_reconstruction_takes_no_time_limit(): import symident as si + with pytest.raises(TypeError): si.reconst_control(timeout=10) assert "timeout" not in si.reconst_control() @@ -97,6 +110,7 @@ def test_the_reconstruction_takes_no_time_limit(): def test_the_jet_route_stops_at_its_work_limit(): from symident.sym.jets import jet_generator + cond = {"f": ["x = -k*x + a*y", "y = -m*y"], "g": ["x"], "ic": ["x = x0", "y = y0"]} assert jet_generator([cond], ["a", "y0"], "a")["ok"] assert jet_generator([cond], ["a", "y0"], "a", work_limit=1)["reason"] == "work limit" diff --git a/tests/test_discrete.py b/tests/test_discrete.py index bc81f52..f1a54c0 100644 --- a/tests/test_discrete.py +++ b/tests/test_discrete.py @@ -26,14 +26,14 @@ def same(a, b): def two_compartment(): - return si.Model({"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, {"y": "x2"}, - known_inputs=["u"]) + return si.Model({"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, {"y": "x2"}, known_inputs=["u"]) def test_two_compartment_exchanges_the_elimination_rates(): r = si.detect(two_compartment(), cores=1) - out = r.discrete(points=[{"x1": 1, "x2": 2, "k01": 3, "k12": 5, "k21": 7}, - {"x1": 1, "x2": 2, "k01": 4, "k12": 4, "k21": 7}]) + out = r.discrete( + points=[{"x1": 1, "x2": 2, "k01": 3, "k12": 5, "k21": 7}, {"x1": 1, "x2": 2, "k01": 4, "k12": 4, "k21": 7}] + ) (s,) = out["symmetries"] # the coordinates SIAN.jl reports locally but not globally identifiable assert s["level"] == "exact" and set(s["changes"]) == {"x1", "k01", "k12"} @@ -55,6 +55,7 @@ def run(trafo): m = two_compartment() m.trafo = trafo return si.detect(m, cores=1).discrete()["symmetries"] + (s,) = run({"x1": "1/k21", "x2": "0"}) assert set(s["changes"]) == {"k01", "k12"} assert run({"x1": "1/(k01 + 1)", "x2": "0"}) == [] @@ -70,8 +71,7 @@ def test_a_given_start_takes_the_state_map_solved_from_the_outputs(): def test_a_symmetry_outside_the_domain_is_not_relevant(): - r = si.detect(si.Model({"x": "-theta^2*x"}, {"y": "x"}), cores=1, mode="global", - global_options={"points": 2}) + r = si.detect(si.Model({"x": "-theta^2*x"}, {"y": "x"}), cores=1, mode="global", global_options={"points": 2}) (s,) = r.discrete_symmetries assert same(s["map"]["theta"], "-theta") and s["preserves_domain"] is False and s["level"] == "exact" info = r.info["discrete"] @@ -84,15 +84,23 @@ def test_the_count_in_the_domain_differs_between_regions(): out = si.detect(m, cores=1).discrete(points=[{"a": 2, "b": 1}, {"a": 1, "b": 3}]) (s,) = out["symmetries"] assert same(s["map"]["b"], "2*a - b") and s["level"] == "exact" - assert s["preserves_domain"] is None and [spy.sympify(c.split(">")[0]) for c in s["domain_conditions"]] == \ - [spy.sympify("2*a - b")] + assert s["preserves_domain"] is None and [spy.sympify(c.split(">")[0]) for c in s["domain_conditions"]] == [ + spy.sympify("2*a - b") + ] assert [c["in_domain"] for c in out["info"]["counts"]] == [2, 1] def test_rates_identified_only_as_a_set(): # HIV model of Rey Barreiro and Villaverde (2023): c, k1 + w1 and w2 enter only through symmetric functions - m = si.Model({"x1": "-b*x1*x4 - d*x1 + s", "x2": "b*q1*x1*x4 - w1*x2 - k1*x2", - "x3": "b*x1*q2*x4 - x3*w2 + k1*x2", "x4": "-c*x4 + k2*x3"}, {"y1": "x1", "y2": "x4"}) + m = si.Model( + { + "x1": "-b*x1*x4 - d*x1 + s", + "x2": "b*q1*x1*x4 - w1*x2 - k1*x2", + "x3": "b*x1*q2*x4 - x3*w2 + k1*x2", + "x4": "-c*x4 + k2*x3", + }, + {"y1": "x1", "y2": "x4"}, + ) r = si.detect(m, cores=1, reconstruct=True) assert not r.identifiable out = r.discrete(points=1) @@ -112,12 +120,18 @@ def test_rates_identified_only_as_a_set(): def test_a_square_outside_the_domain_leaves_the_model_globally_identifiable(): # beta-cell model of Finegood et al. (1995), as in SIAN.jl: SIAN reports alpha locally but not globally # identifiable over the complex numbers, from alpha -> -alpha - m = si.Model({"G": "u1 - (c + si*II)*G", - "beta": "beta*((1/(48*24*60))/(1 + (8/G)^2) - (1/(40*24*60))/(1 + (G/5)^8))", - "II": "p1*beta*(G^2/(alpha^2 + G^2)) - gm*II"}, {"y1": "G"}, known_inputs=["u1"]) + m = si.Model( + { + "G": "u1 - (c + si*II)*G", + "beta": "beta*((1/(48*24*60))/(1 + (8/G)^2) - (1/(40*24*60))/(1 + (G/5)^8))", + "II": "p1*beta*(G^2/(alpha^2 + G^2)) - gm*II", + }, + {"y1": "G"}, + known_inputs=["u1"], + ) r = si.detect(m, cores=1, reconstruct=True) # the exact count finds no relation of this rational model: a small search keeps the test fast - out = r.discrete(points=2, search_entries=10 ** 7) + out = r.discrete(points=2, search_entries=10**7) (s,) = out["symmetries"] assert s["changes"] == ["alpha"] and same(s["map"]["alpha"], "-alpha") assert s["level"] == "exact" and s["preserves_domain"] is False @@ -132,6 +146,7 @@ def _stage_toy(monkeypatch, d): import types from symident.detection import discrete + fib = types.SimpleNamespace(names=["x0", "x1", "x2"], allnames=["x0", "x1", "x2"], sep_mode={}) fib._ms_block = lambda idx, polys, sat, p: discrete.Fiber._ms_block(fib, idx, polys, sat, p) polys = [{((0, 1),): 1, ((1, 1),): 1}, {((0, 1), (1, 1)): 4, (): d}, {((2, 1),): 1, ((0, 1),): -1}] @@ -141,6 +156,7 @@ def record(*a): got = orig(*a) calls.append((a[4], got is not None)) return got + monkeypatch.setattr(discrete, "_stage_points", record) return discrete, fib, polys, calls @@ -153,6 +169,7 @@ def test_a_block_that_msolve_counts_at_once_is_not_split_into_stages(monkeypatch def test_a_block_past_an_eighth_of_the_cap_of_msolve_goes_by_stages(monkeypatch): from symident.detection import work + discrete, fib, polys, calls = _stage_toy(monkeypatch, 4) caps = [] orig = discrete._block_count @@ -160,6 +177,7 @@ def test_a_block_past_an_eighth_of_the_cap_of_msolve_goes_by_stages(monkeypatch) def record(*a): caps.append(work.cap("msolve_entries")) return None if len(caps) == 1 else orig(*a) + monkeypatch.setattr(discrete, "_block_count", record) with work.caps(msolve_entries=800): assert discrete._staged_count(fib, [0, 1, 2], polys, [], discrete.PRIMES[0]) == 2 @@ -180,6 +198,7 @@ def first_fails(fib_, idx, polys_, sat, p_): seen.add(tuple(idx)) return None return orig(fib_, idx, polys_, sat, p_) + monkeypatch.setattr(discrete, "_block_count", first_fails) assert discrete._staged_count(fib, [0, 1, 2], polys, [], 0) == 2 assert calls == [(p, False)] @@ -188,13 +207,16 @@ def first_fails(fib_, idx, polys_, sat, p_): def test_a_vanishing_denominator_is_no_point_of_the_fiber(): # the x4 equation of the p53 model of Rey Barreiro and Villaverde (2023), the other states as known inputs: # where p22^4 = -1 a denominator and a numerator vanish together, which the saturation must exclude - f = {"x4": "p20 - p21*(1-p24)*(1-p25)/((p22^4)+1) - (p20*x4) + (p21*(x3^4))" - " + (1+p23*u1)*(1-p24*x1)*(1-p25*x2)/(p22^4+x3^4)"} + f = { + "x4": "p20 - p21*(1-p24)*(1-p25)/((p22^4)+1) - (p20*x4) + (p21*(x3^4))" + " + (1+p23*u1)*(1-p24*x1)*(1-p25*x2)/(p22^4+x3^4)" + } m = si.Model(f, {"y4": "x4"}, known_inputs=["u1", "x1", "x2", "x3"]) from symident.detection import work + # a short search and few steps of the monodromy keep the test fast - with work.caps(monodromy_products=10 ** 7): - out = si.detect(m, cores=1).discrete(points=1, search_entries=10 ** 7) + with work.caps(monodromy_products=10**7): + out = si.detect(m, cores=1).discrete(points=1, search_entries=10**7) (s,) = out["symmetries"] assert same(s["map"]["p22"], "-p22") and s["preserves_domain"] is False info = out["info"] @@ -223,14 +245,19 @@ def test_conditions_share_the_coordinates_of_the_fiber(): def dosed(var, time="1", value="D", method="add", start=None): - return si.Model(FREE, {"y": "x2"}, trafo=start or {"x1": "0", "x2": "0"}, fixed=["D"] if "D" in value else (), - events=[{"var": var, "time": time, "value": value, "method": method}]) + return si.Model( + FREE, + {"y": "x2"}, + trafo=start or {"x1": "0", "x2": "0"}, + fixed=["D"] if "D" in value else (), + events=[{"var": var, "time": time, "value": value, "method": method}], + ) def test_a_dose_after_rest_keeps_or_breaks_the_swap(): # the impulse response from the first compartment is symmetric in k01 and k12, the one from the second is not maps, info = maps_of(dosed("x1")) - (sig, level), = maps + ((sig, level),) = maps assert level == "exact" and same(sig["k01"], "k12") and info["count"] == 2 and info["count_final"] maps, info = maps_of(dosed("x2")) assert maps == [] and info["count"] == 1 @@ -239,7 +266,7 @@ def test_a_dose_after_rest_keeps_or_breaks_the_swap(): def test_an_estimated_event_time_is_a_coordinate_of_the_fiber(): # the segment after the dose is expanded at the start of the condition, so its series holds tau maps, info = maps_of(dosed("x1", time="tau")) - (sig, level), = maps + ((sig, level),) = maps assert level == "exact" and "tau" not in sig and info["count"] == 2 assert "the bound covers models without events" in info["certificate"]["count_bound_why"] @@ -261,8 +288,9 @@ def test_detect_in_global_mode_counts_after_the_local_analysis(): # a setting the global analysis does not handle warns and keeps the local result dose = [{"var": "x", "time": 1, "value": 1, "method": "add"}] with pytest.warns(UserWarning, match="global analysis not done"): - r = si.detect(si.Model({"x": "-k*x + w"}, {"y": "x", "yw": "w"}, unknown_inputs=["w"], events=dose), - mode="global") + r = si.detect( + si.Model({"x": "-k*x + w"}, {"y": "x", "yw": "w"}, unknown_inputs=["w"], events=dose), mode="global" + ) assert r.rank is not None and "unknown inputs" in r.info["discrete"]["unsupported"] with pytest.raises(ValueError, match="mode"): si.detect(two_compartment(), mode="globally") @@ -272,8 +300,14 @@ def test_the_json_interface_runs_the_global_mode(): import json from symident import rjson - spec = {"f": {"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, "g": {"y": "x2"}, - "known_inputs": ["u"], "mode": "global", "global_options": {"points": 1}} + + spec = { + "f": {"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, + "g": {"y": "x2"}, + "known_inputs": ["u"], + "mode": "global", + "global_options": {"points": 1}, + } out = json.loads(rjson.detect_json(json.dumps(spec))) assert out["info"]["discrete"]["count"] == 2 and len(out["discrete_symmetries"]) == 1 @@ -286,8 +320,12 @@ def test_a_start_at_rest_takes_the_resting_state_in_closed_form(): (s,) = r.discrete_symmetries assert s["level"] == "exact" and same(s["map"]["k01"], "k12") and r.info["discrete"]["count_final"] # a state the observables do not read, which never rests, is left out - m = si.Model({"x": "p - d*x", "z": "k*x"}, {"y": "x"}, fixed=["D"], - events=[{"var": "x", "time": 0, "value": "D", "method": "add"}]) + m = si.Model( + {"x": "p - d*x", "z": "k*x"}, + {"y": "x"}, + fixed=["D"], + events=[{"var": "x", "time": 0, "value": "D", "method": "add"}], + ) r = si.detect(m, equilibrate=True, mode="global") assert r.discrete_symmetries == [] and r.info["discrete"]["count"] == 1 @@ -303,8 +341,9 @@ def test_a_switch_enters_with_copies_that_start_on_the_surface(): (s,) = r.discrete_symmetries assert s["level"] == "exact" and same(s["map"]["k"], "-k") and s["preserves_domain"] is False with pytest.warns(UserWarning, match="parameters alone"): - si.detect(si.Model({"x": "piecewise(-k1*x, k1 > k2, -k2*x)"}, {"y": "x"}, regimes=["k1 - k2 > 0"]), - mode="global") + si.detect( + si.Model({"x": "piecewise(-k1*x, k1 > k2, -k2*x)"}, {"y": "x"}, regimes=["k1 - k2 > 0"]), mode="global" + ) def _swap_model(k01="k01", k12="k12", k21="k21"): @@ -317,6 +356,7 @@ def test_each_side_of_a_discrete_symmetry_is_a_branch_chart(): import json from symident import rjson + r = si.detect(_swap_model(), mode="global", global_options={"points": 1}) red = r.reduce() bs = {b["branch"]: b for b in red.discrete["branches"]} @@ -366,7 +406,7 @@ def test_a_chain_swaps_the_decay_rates_of_its_last_two_members(): def test_log_coordinates_and_a_bleaching_log_output_are_rewritten(): tr = {**REST, **{k: f"exp({k})" for k in ("b", "c", "sh", "kR", "kA", "s", "off", "tau")}} m = si.Model(CHAIN, {"y": "log(s*A + off) - tau*time"}, known_inputs=["u"], trafo=tr) - r = si.detect(m, mode="global", global_options={"search_entries": 10 ** 7}) + r = si.detect(m, mode="global", global_options={"search_entries": 10**7}) (s,) = r.discrete_symmetries assert s["level"] == "exact" and s["map"] == {"kA": "kR", "kR": "kA"} and s["fixed_set"] == ["kA - kR"] info = r.info["discrete"] @@ -385,18 +425,21 @@ def test_a_term_that_stays_transcendental_is_named(): def test_maps_of_log_coordinates_go_back_as_translations(): from symident.detection.rationalize import map_to_given, relation_to_given + a, b, c = spy.symbols("a b c") logs = {"a": (spy.E, 1), "b": (spy.E, 1)} out = map_to_given({a: 2 * b, b: a / 2, c: c * a}, logs) assert same(out[a], "b + log(2)") and same(out[b], "a - log(2)") and same(out[c], "c*exp(a)") - assert relation_to_given("a - 2*b", logs) in ("a - b - log(2)", "-b + a - log(2)") or \ - same(relation_to_given("a - 2*b", logs), "a - b - log(2)") + assert relation_to_given("a - 2*b", logs) in ("a - b - log(2)", "-b + a - log(2)") or same( + relation_to_given("a - 2*b", logs), "a - b - log(2)" + ) def test_the_reduction_of_the_fiber_is_the_same_in_cpp_and_python(): import random from symident.detection import discrete + p = 1000003 rng = random.Random(7) for _ in range(30): @@ -408,9 +451,11 @@ def poly(): mm = tuple(sorted({v: rng.randint(1, 2) for v in rng.sample(range(nv), rng.randint(0, 2))}.items())) P[mm] = rng.randint(1, p - 1) return P + # equations a*v + b that fix variables, and jets that one equation holds alone - polys = [poly() for _ in range(8)] + [{((v, 1),): rng.randint(1, p - 1), (): rng.randint(0, p - 1)} - for v in rng.sample(range(nv), 3)] + polys = [poly() for _ in range(8)] + [ + {((v, 1),): rng.randint(1, p - 1), (): rng.randint(0, p - 1)} for v in rng.sample(range(nv), 3) + ] polys += [{((v, 1),): 1, **poly()} for v in rng.sample(range(m0, nv), 2)] sat = [{((v, 1),): 1} for v in rng.sample(range(nv), 2)] a = discrete._reduce_mod(polys, sat, nv, m0, p) @@ -421,7 +466,6 @@ def poly(): assert a[1:] == b[1:] - def test_a_fiber_whose_invariants_are_output_functions_is_exact(): r = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1) info = r.info["discrete"] @@ -441,8 +485,10 @@ def test_a_known_constant_is_a_symbol_of_the_base_field_of_the_exact_count(): def test_a_point_where_the_fiber_leaves_the_domain_counts_none_and_is_not_verified(monkeypatch): from symident.detection import discrete, fieldproof - monkeypatch.setattr(fieldproof, "exact_fiber", - lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0}) + + monkeypatch.setattr( + fieldproof, "exact_fiber", lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0} + ) m = si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}) cert = si.detect(m, mode="global", cores=1).info["discrete"]["certificate"] assert cert["complete"] == "verified" and cert["count_bound"] * 2 ** cert["count_bits"] >= 1 @@ -451,6 +497,7 @@ def test_a_point_where_the_fiber_leaves_the_domain_counts_none_and_is_not_verifi def at_zero(fib, point): # at k = 0 both points k and -k meet the zero of the coordinate, which the saturation removes return orig(fib, {**point, spy.Symbol("k"): spy.Integer(0)}) + monkeypatch.setattr(discrete, "q_count", at_zero) cert = si.detect(m, mode="global", cores=1).info["discrete"]["certificate"] assert cert["complete"] == "axiom" and cert["count_bound"] is None @@ -459,6 +506,7 @@ def at_zero(fib, point): def test_the_series_on_degree_bounds_shares_denominators(): from symident.sym.degrees import Atoms, Deg, common + A = Atoms() a, b = Deg(A, 1), Deg(A, 1) d = a - b @@ -473,6 +521,7 @@ def test_the_series_on_degree_bounds_shares_denominators(): def test_the_fixed_field_of_a_swap_is_generated_by_the_symmetric_functions(): from symident.detection.fieldproof import generators + a, b, c = spy.symbols("a b c") grp = [{}, {a: b, b: a}] alpha, F, traces, others = generators(grp, [a, b, c]) @@ -483,12 +532,15 @@ def test_the_fixed_field_of_a_swap_is_generated_by_the_symmetric_functions(): def test_a_bezout_number_past_the_bits_of_the_point_leaves_the_axiom(monkeypatch): from symident.detection import discrete, fieldproof - monkeypatch.setattr(fieldproof, "exact_fiber", - lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0}) - monkeypatch.setattr(discrete, "_fiber_degrees", lambda fib: [10 ** 2000, 10 ** 2000]) + + monkeypatch.setattr( + fieldproof, "exact_fiber", lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0} + ) + monkeypatch.setattr(discrete, "_fiber_degrees", lambda fib: [10**2000, 10**2000]) monkeypatch.setattr(discrete, "_x_bezout", lambda fib: None) - cert = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", - cores=1).info["discrete"]["certificate"] + cert = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1).info["discrete"][ + "certificate" + ] assert cert["complete"] == "axiom" and "bits" in cert["count_bound_why"] @@ -496,26 +548,29 @@ def test_msolve_output_over_q_is_read_exactly(): from fractions import Fraction from symident.detection.discrete import parse_rational + digits = "1" + "0" * 5000 # quotients past the range of a float and integers past the default digit limit stay exact got = parse_rational("[0, [1, " + digits + "/3, -7 / 2^3, " + digits + "]]") - assert got == [0, [1, Fraction(10 ** 5000, 3), Fraction(-7, 8), 10 ** 5000]] + assert got == [0, [1, Fraction(10**5000, 3), Fraction(-7, 8), 10**5000]] def test_msolve_output_with_long_integers_is_read_in_linear_time(): import time from symident.detection.discrete import parse_rational + n = 200000 t = time.monotonic() got = parse_rational("[" + "7" * n + ", -" + "7" * n + " / 2^3]") - value = 7 * (10 ** n - 1) // 9 + value = 7 * (10**n - 1) // 9 assert got[0] == value and got[1] * 8 == -value assert time.monotonic() - t < 10 def test_a_polynomial_in_more_symbols_than_the_recursion_limit_is_read(): from symident.detection.discrete import _dict + # the jets of known inputs give a part a thousand symbols and more xs = spy.symbols("x0:1100") P = _dict(xs[0] * xs[1099] / 2 + 3, xs) @@ -524,12 +579,15 @@ def test_a_polynomial_in_more_symbols_than_the_recursion_limit_is_read(): def test_a_verified_count_at_a_point_of_thousands_of_digits(monkeypatch): from symident.detection import discrete, fieldproof - monkeypatch.setattr(fieldproof, "exact_fiber", - lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0}) + + monkeypatch.setattr( + fieldproof, "exact_fiber", lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0} + ) # the Taylor coefficients at the point pass the default limit of digits of int() monkeypatch.setattr(discrete, "_MIN_BITS", 4000) - cert = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", - cores=1).info["discrete"]["certificate"] + cert = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1).info["discrete"][ + "certificate" + ] assert cert["complete"] == "verified" and cert["count_bits"] == 4000 @@ -540,8 +598,9 @@ def test_a_parameter_read_only_as_a_fourth_power_has_maps_over_q_of_i_from_monod assert info["count"] == 4 and info["certificate"]["orbit"] == 4 and info["certificate"]["complete"] == "exact" assert not any(lim.startswith("k enters only as k^4") for lim in info["limits"]) over_i = [s for s in r.discrete_symmetries if "monodromy" in s["found_by"]] - assert sorted((spy.sympify(s["map"]["k"]) / spy.Symbol("k") for s in over_i), key=str) == \ - sorted([spy.I, -spy.I], key=str) + assert sorted((spy.sympify(s["map"]["k"]) / spy.Symbol("k") for s in over_i), key=str) == sorted( + [spy.I, -spy.I], key=str + ) assert all(s["level"] == "exact" and s["preserves_domain"] is False for s in over_i) assert info["monodromy"]["certified"] == 4 @@ -615,6 +674,7 @@ def test_a_leading_coefficient_without_a_scaling_is_a_leaf(): def _start_power_series(g, positive=True): from symident.detection.discrete import Series + seg = {"f": {"x": "p - m*x", "si_N1": "0"}, "g": g, "ic": {"x": "0", "si_N1": "0"}, "t": "0"} part = {"segments": [seg], "spow": {"N": "si_N1", "state": "x", "alpha": "a", "k": 1}} return Series([part], ["a", "m", "p", "q", "r"], positive) @@ -641,6 +701,7 @@ def test_the_series_of_a_start_power_has_the_layers_of_the_exponent(): def test_the_leading_order_of_a_state_at_zero(): from symident.detection.startpow import leading + k, c = leading({"x": "z", "z": "p - m*z + x^a"}, {"x": "0", "z": "0"}, spy.Symbol("x"), spy.Symbol("a")) assert k == 2 and same(c, "p/2") @@ -656,10 +717,15 @@ def test_a_coordinate_proven_in_the_field_of_the_outputs_pins_the_count(monkeypa from symident.detection import fieldproof def run(proven): - monkeypatch.setattr(fieldproof, "exact_fiber", lambda *a, **k: { - "exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": proven}) - return si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", - cores=1).info["discrete"] + monkeypatch.setattr( + fieldproof, + "exact_fiber", + lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": proven}, + ) + return si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1).info[ + "discrete" + ] + free, pinned = run([]), run(["x0", "c"]) assert free["count"] == pinned["count"] == 2 # the pins are equations of degree one in place of output coefficients of higher degree @@ -669,8 +735,16 @@ def run(proven): def test_a_state_that_starts_at_one_maps_to_a_power_of_itself(): # z = exp(n k t): n -> -n takes z to 1/z - r = si.detect(si.Model({"x": "-k*x", "z": "n*k*z"}, {"y1": "x", "y2": "c*(1 + a*z)/(1 + z)"}, - trafo={"z": "1"}, positive=["x", "k", "c", "a"]), mode="global", cores=1) + r = si.detect( + si.Model( + {"x": "-k*x", "z": "n*k*z"}, + {"y1": "x", "y2": "c*(1 + a*z)/(1 + z)"}, + trafo={"z": "1"}, + positive=["x", "k", "c", "a"], + ), + mode="global", + cores=1, + ) (s,) = r.discrete_symmetries assert s["level"] == "exact" and same(s["map"]["n"], "-n") and same(s["map"]["a"], "1/a") assert s["state_maps"][0]["z"] == "1/z" @@ -678,10 +752,14 @@ def test_a_state_that_starts_at_one_maps_to_a_power_of_itself(): def test_an_equation_that_sets_a_variable_to_a_monomial_eliminates_it(): from symident.detection import discrete + p = 1000003 # 2*x0 - 3*x1*x2 = 0 sets the coordinate x0; x3 is a jet, set to a monomial in a coordinate - polys = [{((0, 1),): 2, ((1, 1), (2, 1)): p - 3}, {((0, 2),): 1, ((1, 1),): p - 1, ((3, 1),): 1}, - {((3, 1),): 1, ((2, 2),): 7}] + polys = [ + {((0, 1),): 2, ((1, 1), (2, 1)): p - 3}, + {((0, 2),): 1, ((1, 1),): p - 1, ((3, 1),): 1}, + {((3, 1),): 1, ((2, 2),): 7}, + ] sat = [{((0, 1), (1, 1)): 1}] out, sat2, gone = discrete._monomial_eliminate(polys, sat, 3, p) assert gone == {0, 3} @@ -695,10 +773,17 @@ def test_the_count_after_the_elimination_of_monomial_pins_is_the_same(monkeypatc from symident.detection import fieldproof def run(proven): - monkeypatch.setattr(fieldproof, "exact_fiber", lambda *a, **k: { - "exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": proven}) - return si.detect(si.Model({"x1": "-a*b*x1", "x2": "-(a + c)*x2"}, {"y1": "x1 + x2"}, - trafo={"x1": "1", "x2": "1"}), mode="global", cores=1).info["discrete"] + monkeypatch.setattr( + fieldproof, + "exact_fiber", + lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": proven}, + ) + return si.detect( + si.Model({"x1": "-a*b*x1", "x2": "-(a + c)*x2"}, {"y1": "x1 + x2"}, trafo={"x1": "1", "x2": "1"}), + mode="global", + cores=1, + ).info["discrete"] + pinned = run(["a*b", "a + c", "b/c"]) assert pinned["count"] == 2 and pinned["certificate"]["complete"] == "verified" @@ -707,6 +792,7 @@ def test_a_process_past_its_address_space_fails_and_not_the_one_that_waits(): import sys from symident.detection import work + if sys.platform.startswith("linux"): r = work.run([sys.executable, "-c", "x = bytearray(1 << 31)"], memory=1 << 30) assert r.returncode != 0 @@ -717,6 +803,7 @@ def test_run_msolve_closes_the_pipes_of_the_process(monkeypatch): import sys from symident.detection import work + procs = [] class Recorded(subprocess.Popen): @@ -736,34 +823,44 @@ def test_the_symbols_of_the_package_hold_no_clock(): import re import symident + # every search and count stops on work caps: no deadline, timeout or CPU clock decides a result src = pathlib.Path(symident.__file__).parent pat = re.compile(r"\b(deadline|timeout|cpuclock|process_time|RLIMIT_CPU)\b") - hits = [f"{p.name}:{n}" for p in src.rglob("*.py") for n, line in enumerate(p.read_text().splitlines(), 1) - if pat.search(line)] + hits = [ + f"{p.name}:{n}" + for p in src.rglob("*.py") + for n, line in enumerate(p.read_text().splitlines(), 1) + if pat.search(line) + ] assert hits == [] def test_a_fiber_past_the_term_limit_is_not_counted(monkeypatch): from symident.detection import discrete + monkeypatch.setattr(discrete, "_FIBER_TERMS", 3) - info = si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", - cores=1).info["discrete"] + info = si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1).info[ + "discrete" + ] assert info["count"] is None assert any("have more than 3 terms, the most a count takes" in w for w in info["limits"]) def test_a_fiber_past_the_limit_of_unknowns_is_not_counted(monkeypatch): from symident.detection import discrete + monkeypatch.setattr(discrete, "_FIBER_UNKNOWNS", 3, raising=False) - info = si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", - cores=1).info["discrete"] + info = si.detect(si.Model({"x": "-k^2*x - c*x^3"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1).info[ + "discrete" + ] assert info["count"] is None assert any("unknowns, more than the 3 a count takes" in w for w in info["limits"]) def test_a_power_of_a_series_past_the_term_limit_stops_the_prolongation(): from symident.detection import discrete + R, a, b = spy.ring("a,b", spy.QQ) xs = [[a + b, a * b + 1, a + 1]] assert len(discrete._ser_poly({(3,): 1}, xs, [], 2, R(1), R(0))[2]) > 4 @@ -773,6 +870,7 @@ def test_a_power_of_a_series_past_the_term_limit_stops_the_prolongation(): def test_a_product_of_the_series_of_two_states_past_the_term_limit_stops_the_prolongation(): from symident.detection import discrete + R, a, b, c, d = spy.ring("a,b,c,d", spy.QQ) xs = [[a + b, a * b + 1, a + 1], [c + d, c * d + 1, c + 1]] assert all(sum(len(t) for t in x) <= 6 for x in xs) @@ -782,6 +880,7 @@ def test_a_product_of_the_series_of_two_states_past_the_term_limit_stops_the_pro def test_a_sum_of_series_past_the_term_limit_stops_the_prolongation(): from symident.detection import discrete + R, a, b, c, d = spy.ring("a,b,c,d", spy.QQ) xs = [[a + b, a * b + 1, a + 1], [c + d, c * d + 1, c + 1]] with pytest.raises(discrete.FiberTooLargeError): @@ -790,6 +889,7 @@ def test_a_sum_of_series_past_the_term_limit_stops_the_prolongation(): def test_the_term_limit_holds_for_the_coefficients_in_the_gap_variable(): from symident.detection import discrete + R, a, b, c, d = spy.ring("a,b,c,d", spy.QQ) E = discrete._Eps xs = [[E([a + b, a]), E([a * b + 1, b])], [E([c + d, c]), E([c * d + 1, d])]] @@ -800,17 +900,28 @@ def test_the_term_limit_holds_for_the_coefficients_in_the_gap_variable(): def test_a_product_within_the_term_limit_is_the_product_without_it(): from symident.detection import discrete + R, a, b = spy.ring("a,b", spy.QQ) xs = [[(a + b) ** 4, a]] # the bound of the terms of the product exceeds the limit, the product itself does not - assert discrete._ser_poly({(2,): 1}, xs, [], 1, R(1), R(0), limit=20) == \ - discrete._ser_poly({(2,): 1}, xs, [], 1, R(1), R(0)) + assert discrete._ser_poly({(2,): 1}, xs, [], 1, R(1), R(0), limit=20) == discrete._ser_poly( + {(2,): 1}, xs, [], 1, R(1), R(0) + ) def test_resting_balances_past_the_bezout_cap_end_with_a_reason(): - m = si.Model({"x": "k1*(1 + u) - k2*x*y + k8*z - k3*x", "y": "k2*x*y - k4*y*z - k5*y + k9*x*z", - "z": "k4*y*z - k6*z - k9*x*z - k8*z", "u": "0"}, {"y1": "x", "y2": "y", "y3": "z"}, inputs=["u"], - equilibrate=True, events=[{"var": "u", "time": 0, "value": 1, "method": "replace"}]) + m = si.Model( + { + "x": "k1*(1 + u) - k2*x*y + k8*z - k3*x", + "y": "k2*x*y - k4*y*z - k5*y + k9*x*z", + "z": "k4*y*z - k6*z - k9*x*z - k8*z", + "u": "0", + }, + {"y1": "x", "y2": "y", "y3": "z"}, + inputs=["u"], + equilibrate=True, + events=[{"var": "u", "time": 0, "value": 1, "method": "replace"}], + ) with pytest.warns(UserWarning, match="global analysis not done"): r = si.detect(m, mode="global", cores=1) assert "Bezout number 8 in the states is past the cap rest_bezout of 4" in r.info["discrete"]["unsupported"] @@ -818,6 +929,7 @@ def test_resting_balances_past_the_bezout_cap_end_with_a_reason(): def test_resting_balances_past_the_block_cap_end_with_a_reason(): from symident.detection import work + tc = {"x1": "p - (k21 + k01)*x1 + k12*x2", "x2": "k21*x1 - k12*x2"} m = si.Model(tc, {"y": "x2"}, events=[{"var": "x1", "time": 1, "value": "D", "method": "add"}], fixed=["D"]) with work.caps(rest_block=1), pytest.warns(UserWarning, match="global analysis not done"): @@ -827,6 +939,7 @@ def test_resting_balances_past_the_block_cap_end_with_a_reason(): def test_a_transcendental_balance_at_rest_is_named_without_a_search(): from symident.detection import discrete + with pytest.raises(ValueError, match="balances of x are not rational in the states"): discrete.resting_start({"x": "k - x*exp(x)", "u": "0"}, {}, ["u"], {"k"}) @@ -834,12 +947,16 @@ def test_a_transcendental_balance_at_rest_is_named_without_a_search(): def test_a_closed_stage_of_the_fiber_is_solved_first_and_its_points_substituted(): from symident.detection import discrete from symident.gfp import PRIMES + p = PRIMES[0] fib = object.__new__(discrete.Fiber) fib.names, fib.allnames = ["x0", "x1", "x2"], ["x0", "x1", "x2"] # x0*x1 = 2, x0 + x1 = 3 close on (x0, x1) with two points in GF(p); x2^2 = x0 reads them - polys = [{((0, 1), (1, 1)): 1, (): p - 2}, {((0, 1),): 1, ((1, 1),): 1, (): p - 3}, - {((2, 2),): 1, ((0, 1),): p - 1}] + polys = [ + {((0, 1), (1, 1)): 1, (): p - 2}, + {((0, 1),): 1, ((1, 1),): 1, (): p - 3}, + {((2, 2),): 1, ((0, 1),): p - 1}, + ] sat = [{((0, 1), (1, 1), (2, 1)): 1}] assert discrete._first_stage(polys, [0, 1, 2]) == {0, 1} staged = discrete._staged_count(fib, [0, 1, 2], polys, sat, p) @@ -851,11 +968,15 @@ def test_a_closed_stage_of_the_fiber_is_solved_first_and_its_points_substituted( def test_a_closed_stage_over_q_with_rational_points_gives_the_degree_of_the_whole_block(): from symident.detection import discrete + fib = object.__new__(discrete.Fiber) fib.names, fib.allnames, fib.sep_mode = ["x0", "x1", "x2"], ["x0", "x1", "x2"], {} F = Fraction - polys = [{((0, 1), (1, 1)): F(1), (): F(-2)}, {((0, 1),): F(1), ((1, 1),): F(1), (): F(-3)}, - {((2, 2),): F(1), ((0, 1),): F(-1)}] + polys = [ + {((0, 1), (1, 1)): F(1), (): F(-2)}, + {((0, 1),): F(1), ((1, 1),): F(1), (): F(-3)}, + {((2, 2),): F(1), ((0, 1),): F(-1)}, + ] sat = [{((0, 1), (1, 1), (2, 1)): F(1)}] pts = discrete._stage_points(fib, {0, 1}, polys[:2], [], 0) assert sorted((pt[0], pt[1]) for pt in pts) == [(1, 2), (2, 1)] @@ -866,6 +987,7 @@ def test_a_closed_stage_over_q_with_rational_points_gives_the_degree_of_the_whol def test_a_system_past_the_caps_of_msolve_is_not_solved_and_the_cap_is_named(): from symident.detection import discrete, work from symident.gfp import PRIMES + p = PRIMES[0] fib = object.__new__(discrete.Fiber) fib.names, fib.allnames, fib.sep_mode = ["x0", "x1"], ["x0", "x1"], {} @@ -884,6 +1006,7 @@ def test_a_system_past_the_caps_of_msolve_is_not_solved_and_the_cap_is_named(): def test_msolve_ends_at_the_cap_on_the_entries_of_its_matrices(): from symident.detection import discrete, work from symident.gfp import PRIMES + p = PRIMES[0] fib = object.__new__(discrete.Fiber) fib.names, fib.allnames, fib.sep_mode = ["x0", "x1"], ["x0", "x1"], {} @@ -902,16 +1025,22 @@ def test_msolve_ends_at_the_cap_on_the_entries_of_its_matrices(): def test_the_memory_of_msolve_is_a_setting_of_the_global_analysis(monkeypatch): from symident.detection import work + seen, orig = [], work._limiter def record(memory): if memory is not None: seen.append(memory) return orig(memory) + monkeypatch.setattr(work, "_limiter", record) default = work.MSOLVE_MEMORY - r = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1, - global_options={"memory": 3, "points": 1}) + r = si.detect( + si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), + mode="global", + cores=1, + global_options={"memory": 3, "points": 1}, + ) assert r.info["discrete"]["count"] == 2 assert seen and set(seen) == {3 << 30} and work.MSOLVE_MEMORY == default @@ -920,9 +1049,11 @@ def test_the_orders_of_the_count_rise_a_fixed_number_of_times(monkeypatch): import types from symident.detection import discrete + given = [] - monkeypatch.setattr(discrete, "Fiber", lambda series, orders, positive, gap=0: types.SimpleNamespace( - orders=orders, too_large=None)) + monkeypatch.setattr( + discrete, "Fiber", lambda series, orders, positive, gap=0: types.SimpleNamespace(orders=orders, too_large=None) + ) monkeypatch.setattr(discrete, "complex_count", lambda fib, point, p: given.append(fib.orders)) series = types.SimpleNamespace(output_orders=lambda cap, p: [1, 3], coords=["a"], labels=["y", "z"]) discrete.choose_order(series, True, 1, 20) @@ -934,13 +1065,16 @@ def test_a_count_past_the_caps_of_msolve_ends_the_rise_of_the_orders(monkeypatch import types from symident.detection import discrete + given = [] def count(fib, point, p): given.append(fib.orders) discrete._failed(kind="size") - monkeypatch.setattr(discrete, "Fiber", lambda series, orders, positive, gap=0: types.SimpleNamespace( - orders=orders, too_large=None)) + + monkeypatch.setattr( + discrete, "Fiber", lambda series, orders, positive, gap=0: types.SimpleNamespace(orders=orders, too_large=None) + ) monkeypatch.setattr(discrete, "complex_count", count) series = types.SimpleNamespace(output_orders=lambda cap, p: [1, 3], coords=["a"], labels=["y", "z"]) assert discrete.choose_order(series, True, 1, 20)[2] is None and given == [[4, 4]] @@ -948,9 +1082,14 @@ def count(fib, point, p): def test_a_count_that_msolve_ends_out_of_memory_is_named_so(monkeypatch): from symident.detection import fieldproof + monkeypatch.setattr(fieldproof, "exact_fiber", lambda *a, **k: {"exact": False, "why": "off", "proven": []}) - info = si.detect(si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1, - global_options={"memory": 0.05, "points": 1}).info["discrete"] + info = si.detect( + si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}), + mode="global", + cores=1, + global_options={"memory": 0.05, "points": 1}, + ).info["discrete"] assert info["count"] is None (lim,) = [w for w in info["limits"] if w.startswith("msolve found no finite count")] assert "memory" in lim and "positive dimension" not in lim @@ -958,6 +1097,7 @@ def test_a_count_that_msolve_ends_out_of_memory_is_named_so(monkeypatch): def _pinned_series(f, g, ic, coords, pins): from symident.detection import discrete + series = discrete.Series([{"segments": [{"f": f, "g": g, "ic": ic, "t": "0", "label": ""}]}], coords) series.pins = discrete._pins(pins, series) return series @@ -965,24 +1105,41 @@ def _pinned_series(f, g, ic, coords, pins): def _chain_series(): from symident.detection import discrete - return discrete.Series([{"segments": [{"f": {"x": "-k1*x", "y": "k1*x - k2*y"}, "g": {"o": "y"}, - "ic": {"x": "x0", "y": "0"}, "t": "0", "label": ""}]}], ["k1", "k2", "x0"]) + + return discrete.Series( + [ + { + "segments": [ + { + "f": {"x": "-k1*x", "y": "k1*x - k2*y"}, + "g": {"o": "y"}, + "ic": {"x": "x0", "y": "0"}, + "t": "0", + "label": "", + } + ] + } + ], + ["k1", "k2", "x0"], + ) def test_the_taylor_series_of_the_outputs_stops_at_the_cap_of_its_meter(): from symident.detection import work from symident.gfp import PRIMES + series = _chain_series() series.meter = work.Meter("the Taylor series of the outputs", 10, "term products") assert series.output_orders(40, PRIMES[0]) is None assert series.capped is not None and series.meter.over series = _chain_series() - series.meter = work.Meter("the Taylor series of the outputs", 10 ** 9, "term products") - assert series.output_orders(40, PRIMES[0]) is not None and 0 < series.meter.spent < 10 ** 9 + series.meter = work.Meter("the Taylor series of the outputs", 10**9, "term products") + assert series.output_orders(40, PRIMES[0]) is not None and 0 < series.meter.spent < 10**9 def test_a_taylor_series_past_the_cap_is_named_in_the_limits(): from symident.detection import work + m = si.Model({"x": "-k1*x - k2*x^2"}, {"y": "x"}, trafo={"x": "x0"}) with work.caps(series_products=10): info = si.detect(m, mode="global", cores=1).info["discrete"] @@ -992,18 +1149,22 @@ def test_a_taylor_series_past_the_cap_is_named_in_the_limits(): def test_the_candidates_stop_at_their_cap_with_the_cap_named(): from symident.detection import work + m = si.Model({"x1": "-k1*x1", "x2": "-k2*x2"}, {"y": "x1 + x2"}, trafo={"x1": "a1", "x2": "a2"}) info = si.detect(m, mode="global", cores=1).info["discrete"] assert info["candidates"]["complete_search"] and info["candidates"]["found"] >= 1 with work.caps(candidates=0): info = si.detect(m, mode="global", cores=1).info["discrete"] assert info["candidates"]["complete_search"] is False and info["candidates"]["found"] == 0 - assert "the candidates were not all tested: the search of candidates reached the cap of 0 permutations" in \ - info["limits"] + assert ( + "the candidates were not all tested: the search of candidates reached the cap of 0 permutations" + in info["limits"] + ) def test_the_reconstruction_of_the_maps_stops_at_its_cap_of_points(): from symident.detection import discrete, work + m = si.Model({"x": "-k^2*x"}, {"y": "x"}, trafo={"x": "x0"}) r = si.detect(m, cores=1, reconstruct=True) parts, _ = r._fiber_parts(6, "discrete()") @@ -1017,6 +1178,7 @@ def test_the_reconstruction_of_the_maps_stops_at_its_cap_of_points(): def test_a_share_of_a_meter_ends_with_either_cap(): from symident.detection import work + m = work.Meter("the search", 10, "entries") s = m.share("the dense relations", 3) assert not s.spend(3) and s.spend(1) and not m.over and m.spent == 4 @@ -1027,6 +1189,7 @@ def test_a_share_of_a_meter_ends_with_either_cap(): def test_the_rows_of_the_rank_take_the_orders_by_doubling(): from symident.gfp import PRIMES + series = _chain_series() rows = series.rank_rows(40, PRIMES[0]) # the series stops at the first doubled order where the rows reach the rank, far below the cap @@ -1036,6 +1199,7 @@ def test_the_rows_of_the_rank_take_the_orders_by_doubling(): def test_proven_functions_lower_the_orders_of_the_rank_criterion(): from symident.detection import discrete + series = _pinned_series({"x": "-k1*x - k2*x^2"}, {"y": "x"}, {"x": "x0"}, ["k1", "k2", "x0"], ["k1", "k2"]) p = discrete.PRIMES[0] assert series.output_orders(6, p) == [2] @@ -1050,8 +1214,12 @@ def test_proven_functions_lower_the_orders_of_the_rank_criterion(): def test_the_count_of_the_proven_functions_verifies_where_the_search_stops(monkeypatch): from symident.detection import fieldproof - monkeypatch.setattr(fieldproof, "exact_fiber", lambda *a, **k: { - "exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": ["k1", "k2"]}) + + monkeypatch.setattr( + fieldproof, + "exact_fiber", + lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": ["k1", "k2"]}, + ) r = si.detect(si.Model({"x": "-k1*x - k2*x^2"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1) info = r.info["discrete"] cert = info["certificate"] @@ -1065,9 +1233,15 @@ def test_the_count_of_the_proven_functions_verifies_where_the_search_stops(monke def test_a_count_of_the_proven_functions_past_twice_the_orbit_certifies_nothing(): from symident.detection import discrete + # the swap of k1 and k2 with x0 -> k1 x0 / k2 keeps the pins: two points where the orbit of the proven maps is one - series = _pinned_series({"x": "-k1*x", "z": "k1*x - k2*z"}, {"y": "z"}, {"x": "x0", "z": "0"}, - ["k1", "k2", "x0"], ["k1 + k2", "k1*k2", "k1*x0"]) + series = _pinned_series( + {"x": "-k1*x", "z": "k1*x - k2*z"}, + {"y": "z"}, + {"x": "x0", "z": "0"}, + ["k1", "k2", "x0"], + ["k1 + k2", "k1*k2", "k1*x0"], + ) out = discrete.pinned_count(series, True, 1) assert out["count"] == 2 and out["cert"] is None and "not below 2" in out["why"] @@ -1078,6 +1252,7 @@ def _toy_projection(series, syms): from symident.detection import fieldproof, ioproj from symident.gfp import all_primes + rel = fieldproof._relations(series, syms) rng = random.Random(3) p = all_primes()[0] @@ -1092,6 +1267,7 @@ def test_random_primes_for_the_trials_of_a_verified_relation(): import random from symident.detection import fewcoef + rng = random.Random(1) assert all(fewcoef._is_prime(n) == spy.isprime(n) for n in range(2, 3000)) q = fewcoef.random_prime(rng, 1 << 30) @@ -1104,6 +1280,7 @@ def test_coefficients_of_a_projection_over_a_monomial_one_are_verified(): import random from symident.detection import fewcoef + series = _pinned_series({"x": "-k1*x - k2*x^2"}, {"y": "x"}, {"x": "x0"}, ["k1", "k2", "x0"], []) syms = list(series.cs) log = [] @@ -1117,8 +1294,15 @@ def test_a_verified_relation_enters_the_count_and_its_bound(monkeypatch): from symident.detection import fieldproof def search(series, orders, grp, syms, *a, **k): - return {"exact": False, "why": "off", "generators": [], "seconds": 0.0, "proven": [], - "large": _toy_projection(series, syms)} + return { + "exact": False, + "why": "off", + "generators": [], + "seconds": 0.0, + "proven": [], + "large": _toy_projection(series, syms), + } + monkeypatch.setattr(fieldproof, "exact_fiber", search) r = si.detect(si.Model({"x": "-k1*x - k2*x^2"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1) cert = r.info["discrete"]["certificate"] @@ -1130,16 +1314,23 @@ def search(series, orders, grp, syms, *a, **k): def test_a_state_read_only_through_its_logarithm_is_a_log_coordinate(): - info, _ = _relaxed({"x1": "x1*(a1 - b1*log(x1) - c*log(x2))", "x2": "x2*(a2 - b2*log(x2))"}, - {"y1": "x1", "y2": "x2^2"}) + info, _ = _relaxed( + {"x1": "x1*(a1 - b1*log(x1) - c*log(x2))", "x2": "x2*(a2 - b2*log(x2))"}, {"y1": "x1", "y2": "x2^2"} + ) assert info["relaxed"]["dropped"] == {"x1": "si_P1", "x2": "si_P2"} assert info["relaxed"]["model"]["observables"] == {"y1": "si_L1", "y2": "2*si_L2"} assert info["count"] == 1 and info["certificate"]["complete"] == "exact" def test_a_state_set_to_numbers_by_events_is_a_number_per_segment(): - m = si.Model({"x": "a*exp(v/k)*(1 - x) - b*x", "v": "0"}, {"y": "x"}, inputs=["v"], equilibrate=True, - events=[{"var": "v", "time": 0, "value": 10, "method": "replace"}], positive=["a", "b", "k", "x"]) + m = si.Model( + {"x": "a*exp(v/k)*(1 - x) - b*x", "v": "0"}, + {"y": "x"}, + inputs=["v"], + equilibrate=True, + events=[{"var": "v", "time": 0, "value": 10, "method": "replace"}], + positive=["a", "b", "k", "x"], + ) info = si.detect(m, mode="global", cores=1).info["discrete"] kinds = {rw["rewrite"]: rw for rw in info["rewrites"]} assert kinds["constant"]["state"] == "v" and kinds["coordinate"]["from"] == "exp(10/k)" @@ -1148,11 +1339,18 @@ def test_a_state_set_to_numbers_by_events_is_a_number_per_segment(): def test_the_resting_chart_starts_at_rest(): from symident.detection.restchart import rest_chart - c = rest_chart({"V": "I - g*(V - E) - c*w*(V - F)", "w": "a*exp(V/k)*(1 - w) - b*w", "I": "0"}, {"y": "V"}, - ["I"], ["g", "E", "c", "F", "a", "k", "b"], ["a", "b", "k", "w", "g", "c"]) + + c = rest_chart( + {"V": "I - g*(V - E) - c*w*(V - F)", "w": "a*exp(V/k)*(1 - w) - b*w", "I": "0"}, + {"y": "V"}, + ["I"], + ["g", "E", "c", "F", "a", "k", "b"], + ["a", "b", "k", "w", "g", "c"], + ) # E, signed, is exchanged for the resting value of V; the start solves every balance assert c["exchanged"].keys() == {"E"} and c["rest"] == {"V": "si_V_rest1"} from symident.sym.parse import model_sympify + at = {spy.Symbol(x): model_sympify(v) for x, v in c["trafo"].items()} for e in c["odes"].values(): assert spy.simplify(model_sympify(e).xreplace(at).xreplace({spy.Symbol("I"): 0})) == 0 @@ -1160,9 +1358,14 @@ def test_the_resting_chart_starts_at_rest(): def test_a_resting_state_inside_an_exponential_is_counted_in_the_resting_chart(): - m = si.Model({"V": "I - g*(V - E) - c*w*V", "w": "a*exp(V/k)*(1 - w) - b*w", "I": "0"}, {"y": "V"}, - inputs=["I"], equilibrate=True, events=[{"var": "I", "time": 0, "value": 1, "method": "replace"}], - positive=["a", "b", "k", "w", "g", "c"]) + m = si.Model( + {"V": "I - g*(V - E) - c*w*V", "w": "a*exp(V/k)*(1 - w) - b*w", "I": "0"}, + {"y": "V"}, + inputs=["I"], + equilibrate=True, + events=[{"var": "I", "time": 0, "value": 1, "method": "replace"}], + positive=["a", "b", "k", "w", "g", "c"], + ) info = si.detect(m, mode="global", cores=1).info["discrete"] assert info["relaxed"]["rest_chart"]["rest"] == {"V": "si_V_rest1"} assert info["count"] == 1 and info["certificate"]["complete"] in ("exact", "verified") @@ -1170,6 +1373,7 @@ def test_a_resting_state_inside_an_exponential_is_counted_in_the_resting_chart() def test_the_term_bound_holds_the_terms_of_the_expansion(): from symident.detection.discrete import _term_bound + a, b, c = spy.symbols("a b c") for e in [(a + b) * (a + c), (a + b + c) ** 3, (a + b) / (a + c) ** 2 + c]: assert _term_bound(e) >= len(spy.Add.make_args(spy.expand(spy.fraction(spy.together(e))[0]))) @@ -1177,6 +1381,7 @@ def test_the_term_bound_holds_the_terms_of_the_expansion(): def test_a_map_of_the_states_past_the_cap_on_terms_is_not_solved_and_the_cap_is_named(monkeypatch): from symident.detection import discrete, work + monkeypatch.setattr(discrete, "_block_map", lambda *a: None) f, g = {"x": "-a*x", "y": "-b*y"}, {"o": "x + y"} a, b = spy.symbols("a b") @@ -1198,8 +1403,15 @@ def test_a_result_of_reduce_cq_is_counted_on_the_level_sets_of_the_totals(): assert out["info"]["certificate"]["complete"] == "exact" and out["info"]["count_domain"] == 1 # at rest, with the total set by the trafo f = {"A": "-k1^2*u*A + k2*B", "B": "k1^2*u*A - k2*B", "u": "0"} - m = si.Model(f, {"y1": "A", "y2": "B"}, inputs=["u"], equilibrate=True, reduce_cq=True, trafo={"total1": "A0"}, - events=[{"var": "u", "time": 0, "value": 1, "method": "replace"}]) + m = si.Model( + f, + {"y1": "A", "y2": "B"}, + inputs=["u"], + equilibrate=True, + reduce_cq=True, + trafo={"total1": "A0"}, + events=[{"var": "u", "time": 0, "value": 1, "method": "replace"}], + ) r = si.detect(m, mode="global") i = r.info["discrete"] assert r.info["coordinates"] == ["A0", "k1", "k2"] and [s["map"] for s in r.discrete_symmetries] == [{"k1": "-k1"}] diff --git a/tests/test_errors.py b/tests/test_errors.py index 3d0f31f..2853804 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -35,6 +35,13 @@ def test_debug_raises_a_type_error_that_sympy_did_not_raise(): def test_the_summary_counts_the_errors(): from symident import report - res = {"method": "observability", "identifiable": False, "rank": 1, "dim": 2, "symmetries": [], - "info": {"engine": "modular", "errors": ["a: TypeError: x", "b: ValueError: y"]}} + + res = { + "method": "observability", + "identifiable": False, + "rank": 1, + "dim": 2, + "symmetries": [], + "info": {"engine": "modular", "errors": ["a: TypeError: x", "b: ValueError: y"]}, + } assert " errors: 2 exceptions turned into failed routes (info['errors'])" in report.summary_lines(res, width=80) diff --git a/tests/test_exact.py b/tests/test_exact.py index 9f2af9f..3c56d87 100644 --- a/tests/test_exact.py +++ b/tests/test_exact.py @@ -22,6 +22,7 @@ def without_support_lift(monkeypatch): """The proofs without the lift solved on the support, which proves the directions of the models below.""" from symident.detection import fields + monkeypatch.setattr(fields, "support_lift", lambda *a: None) @@ -48,8 +49,12 @@ def test_a_wrong_field_fails_with_the_identity_named(): def test_closed_forms_reach_the_exact_level(): # the general direction needs a different lift in each condition - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "s*x2"}, - trafo={"x1": "D", "x2": "0"}, conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + {"y": "s*x2"}, + trafo={"x1": "D", "x2": "0"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) r = si.detect(m, reconstruct=True) assert [s.level for s in r.symmetries] == ["exact", "exact"] assert r.info["rank_proof"] == "proven symmetries" @@ -93,8 +98,11 @@ def test_output_identities_refute_a_wrong_direction(): def test_directions_of_a_resting_start_are_exact_at_a_rational_rest(): # a direction of the resting start only is decided exactly by the resting output - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "s*x2"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + {"y": "s*x2"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) r = si.detect(m, reconstruct=True, equilibrate=True) assert {s.level for s in r.symmetries} == {"exact"} and r.info["proof"] == [] r = si.detect(si.Model({"x": "b - a*x"}, {"y": "s*x"}), reconstruct=True, equilibrate=True) @@ -111,30 +119,46 @@ def test_a_held_moiety_pivot_rests_at_its_parameter(): pair = {"species": ["A", "B"], "smatrix": [[-1, 1], [1, -1]], "rates": ["k1*A", "k2*B"]} r = si.detect(si.Model(reactions=pair, observables={"Aobs": "alpha*A"}), reconstruct=True, equilibrate=True) assert {s.level for s in r.symmetries} == {"exact"} and r.info["rank_proof"] == "proven symmetries" - net = {"species": ["A", "B", "C"], "smatrix": [[-1, 1, 0], [1, -1, 0], [0, 0, -1]], - "rates": ["k1*A", "k2*B", "kc*C"]} - m = si.Model(reactions=net, observables={"Aobs": "alpha*A", "Cobs": "s*C"}, - events=[{"var": "C", "time": 5, "value": "1", "method": "add"}]) + net = { + "species": ["A", "B", "C"], + "smatrix": [[-1, 1, 0], [1, -1, 0], [0, 0, -1]], + "rates": ["k1*A", "k2*B", "kc*C"], + } + m = si.Model( + reactions=net, + observables={"Aobs": "alpha*A", "Cobs": "s*C"}, + events=[{"var": "C", "time": 5, "value": "1", "method": "add"}], + ) r = si.detect(m, reconstruct=True, equilibrate=True) assert {s.level for s in r.symmetries} == {"exact"} and r.info["proof"] == [] def test_parameters_of_unobserved_or_vanishing_states_are_exact(): # a parameter of a state that no observable of the same condition sees - m = si.Model({"A": "-k*A", "B": "-q*B"}, [{"yA": "A"}, {"yB": "B"}], - conditions={"rows": ["elisa", "wb"], "cols": {"q": ["q1", "q2"]}}) + m = si.Model( + {"A": "-k*A", "B": "-q*B"}, + [{"yA": "A"}, {"yB": "B"}], + conditions={"rows": ["elisa", "wb"], "cols": {"q": ["q1", "q2"]}}, + ) assert [s.level for s in si.detect(m, reconstruct=True).symmetries] == ["exact"] # parameters that act only through a state that starts and stays at zero - m = si.Model({"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, {"y": "x2"}, - trafo={"x1": "1", "x2": "0", "x3": "0"}) + m = si.Model( + {"x1": "-k1*x1", "x2": "k1*x1 - k2*x2 + a*x3", "x3": "-k3*x3"}, + {"y": "x2"}, + trafo={"x1": "1", "x2": "0", "x3": "0"}, + ) r = si.detect(m, reconstruct=True) assert {s.level for s in r.symmetries} == {"exact"} and r.info["rank_proof"] == "proven symmetries" def test_a_start_event_is_part_of_the_initial_value(): # a start event is composed into the initial value the lift has to match - m = si.Model({"A": "-k*A"}, {"y": "s*A"}, conditions={"rows": ["c1"], "cols": {"d0": [1]}}, - events=[{"var": "A", "time": 0, "value": "d0", "method": "add"}]) + m = si.Model( + {"A": "-k*A"}, + {"y": "s*A"}, + conditions={"rows": ["c1"], "cols": {"d0": [1]}}, + events=[{"var": "A", "time": 0, "value": "d0", "method": "add"}], + ) (s,) = si.detect(m, reconstruct=True).symmetries assert s.level == "exact" and s.state_components == {"A": "A"} @@ -151,8 +175,11 @@ def test_symbolic_exponents_are_proven_in_recast_coordinates(): def test_closed_forms_of_the_symbolic_engine_are_proven(): r = si.detect(si.Model({"m": "ktx - dm*m", "p": "ktl*m - dp*p"}, {"y": "p"}), engine="symbolic") assert [s.level for s in r.symmetries] == ["exact"] and r.info["lie_certified"] - assert r.info["rank_status"] == {"status": "proven", "why": "Lie order proven sufficient, exact kernel", - "probability": None} + assert r.info["rank_status"] == { + "status": "proven", + "why": "Lie order proven sufficient, exact kernel", + "probability": None, + } # exponentials of single coordinates and a logarithm of a number enter as symbols m = si.Model({"x": "-exp(lk)*x + exp(lb)"}, {"y": "log10(s*x)"}, trafo={"x": "10^lx", "s": "10^ls"}) r = si.detect(m, engine="symbolic") @@ -164,8 +191,9 @@ def test_closed_forms_of_the_symbolic_engine_are_proven(): def test_without_a_certified_lie_order_the_symbolic_engine_proves_by_lifts(): # a start on an invariant line hides a direction from the rows at the initial values - m = si.Model({"x1": "-k*x1 + a*(x2 - x1)", "x2": "-k*x2 + a*(x1 - x2)"}, {"y": "s*x1/q"}, - trafo={"x1": "1", "x2": "1"}) + m = si.Model( + {"x1": "-k*x1 + a*(x2 - x1)", "x2": "-k*x2 + a*(x1 - x2)"}, {"y": "s*x1/q"}, trafo={"x1": "1", "x2": "1"} + ) r = si.detect(m, engine="symbolic") assert {tuple(s.support): s.level for s in r.symmetries} == {("a",): "checked", ("q", "s"): "exact"} assert not r.info["lie_certified"] @@ -184,11 +212,12 @@ def test_rest_parametrization_solves_states_or_linear_rates(): import sympy as spy from symident.sym.exact import rest_parametrization + x, y, a, b, c = spy.symbols("x y a b c") - par = rest_parametrization([b - a*x, a*x - c*y], [x, y], [a, b, c]) - assert par["params"] == [] and spy.simplify(par["sub"][y] - b/c) == 0 + par = rest_parametrization([b - a * x, a * x - c * y], [x, y], [a, b, c]) + assert par["params"] == [] and spy.simplify(par["sub"][y] - b / c) == 0 # nonlinear in a state: the linear one is eliminated, a rate solves the rest - eqs = [b - a*x**2, a*x - c*y] + eqs = [b - a * x**2, a * x - c * y] par = rest_parametrization(eqs, [x, y], [a, b, c]) assert len(par["params"]) == 1 and set(par["sub"]) == {y} | set(par["params"]) assert all(spy.cancel(e.xreplace(par["sub"])) == 0 for e in eqs) @@ -196,17 +225,22 @@ def test_rest_parametrization_solves_states_or_linear_rates(): def test_kernel_check_bound_from_the_degrees(): from symident.detection.bound import identity_degree, kernel_bound + f = {"x1": "kb - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"} # polynomial rates: each Lie derivative raises the degree by one assert identity_degree(f, {"y": "s*x2"}, {"x1": "D", "x2": "0"}, 3, {"k1": "k1", "s": "-s"}) == 6 assert identity_degree({"x": "-k*exp(x)"}, {"y": "x"}, {"x": "x0"}, 3, {"k": "k"}) is None - b = kernel_bound(f, {"y": "s*x2"}, {"x1": "D", "x2": "0"}, 3, [{"k1": "k1"}] * 2, 10 ** 9 + 7, 2) - assert b["degree"] == 6 and b["probability"] == 2 * (6 / (10 ** 9 + 7)) ** 2 + b = kernel_bound(f, {"y": "s*x2"}, {"x1": "D", "x2": "0"}, 3, [{"k1": "k1"}] * 2, 10**9 + 7, 2) + assert b["degree"] == 6 and b["probability"] == 2 * (6 / (10**9 + 7)) ** 2 def test_directions_below_exact_get_the_bound(): - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "s*x2"}, - trafo={"x1": "D", "x2": "0"}, conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + {"y": "s*x2"}, + trafo={"x1": "D", "x2": "0"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) with si.switches(NOFIELDS=True): r = si.detect(m, reconstruct=True) # the scaling of the whole model is exact without a field proof @@ -216,8 +250,12 @@ def test_directions_below_exact_get_the_bound(): def test_the_regime_detections_of_the_combined_lift_keep_to_their_budget(without_support_lift): - m = si.Model({"A": "-(ka + kb)*A", "B1": "ka*A - k1*B1", "B2": "kb*A - k2*B2", "C": "k3*B1 + k4*B2 - kc*C^2"}, - {"y": "C"}, trafo={"A": "A0", "B1": "0", "B2": "0", "C": "0"}, fixed=["A0"]) + m = si.Model( + {"A": "-(ka + kb)*A", "B1": "ka*A - k1*B1", "B2": "kb*A - k2*B2", "C": "k3*B1 + k4*B2 - kc*C^2"}, + {"y": "C"}, + trafo={"A": "A0", "B1": "0", "B2": "0", "C": "0"}, + fixed=["A0"], + ) r = si.detect(m, reconstruct=True, control=si.reconst_control(exact_work_cap=1)) assert any(lim.startswith("exact proof: work") for lim in r.info["limits"]) assert all("above exact_work_cap=1" in p["reason"] for p in r.info["proof"]) @@ -235,8 +273,10 @@ def test_unproven_directions_are_listed_and_printed_with_their_level(without_sup def test_the_bound_covers_events_after_the_start(): # a direction that is no scaling - ev = [{"var": "A", "time": 0, "value": "d", "method": "add"}, - {"var": "A", "time": 5, "value": "d", "method": "add"}] + ev = [ + {"var": "A", "time": 0, "value": "d", "method": "add"}, + {"var": "A", "time": 5, "value": "d", "method": "add"}, + ] m = si.Model({"A": "-k*A"}, {"y": "(a + b)*A"}, trafo={"A": "0"}, events=ev) with si.switches(NOFIELDS=True): r = si.detect(m, reconstruct=True) @@ -244,8 +284,7 @@ def test_the_bound_covers_events_after_the_start(): assert 0 < r.info["bound"]["probability"] < 1e-6 # an event time in the parameters enters the degree as a rational function of them, but the # gap order has no rank bound with a moving boundary - m = si.Model({"A": "-k*A"}, {"y": "(a + b)*A"}, trafo={"A": "0"}, - events=[dict(ev[0]), dict(ev[1], time="tau")]) + m = si.Model({"A": "-k*A"}, {"y": "(a + b)*A"}, trafo={"A": "0"}, events=[dict(ev[0]), dict(ev[1], time="tau")]) with si.switches(NOFIELDS=True): r = si.detect(m, reconstruct=True) assert r.info["bound"]["degree"] > 0 and r.info["bound"]["probability"] is None @@ -262,8 +301,12 @@ def test_the_bound_holds_in_the_recast_coordinates_of_a_symbolic_exponent(): def test_a_gauged_detection_keeps_the_proofs_and_bound_of_its_second_pass(): - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, {"y": "s*x2"}, - trafo={"x1": "D", "x2": "0"}, conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + {"y": "s*x2"}, + trafo={"x1": "D", "x2": "0"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) with si.switches(NOFIELDS=True): r = si.detect(m, reconstruct=True, gauge=None) ver = {tuple(s.support) for s in r.symmetries if s.type == "general" and s.level == "verified"} @@ -274,17 +317,25 @@ def test_a_gauged_detection_keeps_the_proofs_and_bound_of_its_second_pass(): def test_the_rank_status_says_how_far_the_number_of_directions_holds(): # every direction closed at a Lie order proven sufficient: the rank rests on the verified closed forms f = {"A": "k1 - d1*A + kx*X", "B": "k2*A - d2*B", "X": "kp*plasmid - dx*X"} - rest = [{"X": f"kp*{u}/dx", "A": f"(k1 + kx*kp*{u}/dx)/d1", "B": f"k2*(k1 + kx*kp*{u}/dx)/(d1*d2)", - "plasmid": str(u)} for u in (0, 1)] - m = si.Model(f, {"yA": "s*(A + X)", "yB": "B"}, trafo=rest, - conditions={"rows": ["ctrl", "oe"], "cols": {"dose": [1, 1]}}, - events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}]) + rest = [ + {"X": f"kp*{u}/dx", "A": f"(k1 + kx*kp*{u}/dx)/d1", "B": f"k2*(k1 + kx*kp*{u}/dx)/(d1*d2)", "plasmid": str(u)} + for u in (0, 1) + ] + m = si.Model( + f, + {"yA": "s*(A + X)", "yB": "B"}, + trafo=rest, + conditions={"rows": ["ctrl", "oe"], "cols": {"dose": [1, 1]}}, + events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}], + ) r = si.detect(m, reconstruct=True) st = r.info["rank_status"] assert st["status"] == "verified" and 0 < st["probability"] < 1e-5 assert "The rank is verified, not proven" in repr(r) - r = si.detect(si.Model({"x1": "-k*x1 + a*(x2 - x1)", "x2": "-k*x2 + a*(x1 - x2)"}, {"y": "x1"}, - trafo={"x1": "1", "x2": "1"}), engine="symbolic") + r = si.detect( + si.Model({"x1": "-k*x1 + a*(x2 - x1)", "x2": "-k*x2 + a*(x1 - x2)"}, {"y": "x1"}, trafo={"x1": "1", "x2": "1"}), + engine="symbolic", + ) assert r.info["rank_status"]["status"] == "lower bound" and "lower bound" in repr(r) exact = si.detect(si.Model({"x": "k1 - k2*x"}, {"y": "s*x"}), reconstruct=True) assert exact.info["rank_status"]["status"] == "proven" @@ -294,9 +345,15 @@ def _late_switch(x0=None): tr = {"w": "0", "v": "0", "u": "0"} if x0 is not None: tr["x"] = x0 - return si.Model({"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, {"y": "x"}, trafo=tr, - events=[{"var": "u", "time": 0, "value": "0", "method": "replace"}, - {"var": "u", "time": 1, "value": "1", "method": "replace"}]) + return si.Model( + {"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, + {"y": "x"}, + trafo=tr, + events=[ + {"var": "u", "time": 0, "value": "0", "method": "replace"}, + {"var": "u", "time": 1, "value": "1", "method": "replace"}, + ], + ) CAP1 = si.reconst_control(gap_order_cap=1) @@ -308,25 +365,36 @@ def test_a_gap_order_is_raised_to_its_rank_bound(): assert r.identifiable and r.info["gap_certified"] is True and r.info["gap_order_used"] >= 2 assert r.info["limits"] == [] ev = [{"var": "u", "time": t, "value": v, "method": "replace"} for t, v in ((0, "0"), (1, "1"), (2, "0"))] - m = si.Model({"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, {"y": "x"}, - trafo={"w": "0", "v": "0", "u": "0"}, events=ev) + m = si.Model( + {"x": "u*w - k*x", "w": "c*(1 - u)*v", "v": "1 - u", "u": "0"}, + {"y": "x"}, + trafo={"w": "0", "v": "0", "u": "0"}, + events=ev, + ) assert si.detect(m, reconstruct=True).identifiable def test_a_gap_order_below_its_bound_leaves_the_rank_a_lower_bound(): r = si.detect(_late_switch(), reconstruct=True, verify=False, control=CAP1) assert r.info["gap_certified"] is False - assert r.info["gap_certificate"] == "the rank did not grow from gap order 0 to 1 (the rank stays below " \ - "the bound 3 up to the cap)" - assert r.info["rank_status"] == {"status": "lower bound", "probability": None, - "why": "the gap order is not proven sufficient"} + assert ( + r.info["gap_certificate"] == "the rank did not grow from gap order 0 to 1 (the rank stays below " + "the bound 3 up to the cap)" + ) + assert r.info["rank_status"] == { + "status": "lower bound", + "probability": None, + "why": "the gap order is not proven sufficient", + } assert any(lim.startswith("gap order: ") for lim in r.info["limits"]) assert "the gap order is not proven sufficient" in " ".join(repr(r).split()) r = si.detect(_late_switch(), reconstruct=True, verify=False, control=si.reconst_control(gap_order_cap=0)) assert r.info["gap_certified"] is False and "gap_order_cap=0" in r.info["gap_certificate"] # a proven rank proves the gap order sufficient - ev = [{"var": "A", "time": 0, "value": "d", "method": "add"}, - {"var": "A", "time": 5, "value": "d", "method": "add"}] + ev = [ + {"var": "A", "time": 0, "value": "d", "method": "add"}, + {"var": "A", "time": 5, "value": "d", "method": "add"}, + ] r = si.detect(si.Model({"A": "-k*A"}, {"y": "s*A"}, trafo={"A": "0"}, events=ev), reconstruct=True) assert r.info["rank_status"]["status"] == "proven" and r.info["gap_certified"] is True assert r.info["limits"] == [] @@ -346,8 +414,12 @@ def _fields_model(): # a nonlinear balance and a start event: only the lift on the support proves the direction, with state # components affine in the states and rational in the parameters f = {"A": "-k1*A*B + k2*C", "B": "-k1*A*B + k2*C", "C": "k1*A*B - k2*C"} - return si.Model(f, {"Aobs": "alpha*A"}, trafo={"k1": "k2*C/(A*B)"}, - events=[{"var": "A", "time": 0, "value": "1", "method": "add"}]) + return si.Model( + f, + {"Aobs": "alpha*A"}, + trafo={"k1": "k2*C/(A*B)"}, + events=[{"var": "A", "time": 0, "value": "1", "method": "add"}], + ) def test_a_direction_through_a_start_event_is_proven_by_the_lift_on_the_support(): @@ -366,17 +438,21 @@ def test_a_rank_through_invariant_fields_is_verified(without_support_lift): assert "rank: verified (1 directions, invariant fields at random points, probability" in str(r.summary()) -def test_a_field_wrong_over_q_but_right_modulo_the_engine_prime_does_not_verify_the_rank(monkeypatch, - without_support_lift): +def test_a_field_wrong_over_q_but_right_modulo_the_engine_prime_does_not_verify_the_rank( + monkeypatch, without_support_lift +): from symident.detection import fields from symident.detection.observability import analysis, proof, reconstruct + setup = fields.field_setup def shifted(*a, **k): out = setup(*a, **k) - out["gens"] = [[dict(x, alpha=f"({x.get('alpha', '0')}) + {PRIMES[0]}*alpha") for x in gl] - for gl in out["gens"]] + out["gens"] = [ + [dict(x, alpha=f"({x.get('alpha', '0')}) + {PRIMES[0]}*alpha") for x in gl] for gl in out["gens"] + ] return out + # every module that binds field_setup, so none loaded during the run keeps the patch for mod in (fields, analysis, proof, reconstruct): monkeypatch.setattr(mod, "field_setup", shifted) @@ -400,11 +476,13 @@ def test_identifiable_false_follows_the_rank_status(): def test_the_field_check_bounds_its_random_points(): from symident.sym.fields import verify_distribution + p, q = PRIMES[0], 1000000007 def check(g, field, vec): lift = {"regime": 0, "point": {"x": 3, "k": 5, "s": 7}, "vectors": [vec], "times": []} return verify_distribution([{"f": ["x = -k*x"], "g": [g]}], [[field]], [], [lift], p, q=q) + out = check("y = s*x", {"x": "x", "s": "-s"}, {"x": 3, "s": p - 7}) assert out["ok"] is True and out["bound"]["prime"] == q and 0 < out["bound"]["probability"] < 1e-12 assert check("y = s*x", {"x": "x", "s": f"-s + {p}*s"}, {"x": 3, "s": p - 7})["ok"] is False @@ -412,6 +490,7 @@ def check(g, field, vec): def test_the_field_check_takes_brackets_in_the_span_over_the_rational_functions(): from symident.sym.fields import verify_distribution + p, q = PRIMES[0], 1000000007 f = ["x = k", "y = 0"] field = {"y": "x^2"} @@ -421,13 +500,15 @@ def test_the_field_check_takes_brackets_in_the_span_over_the_rational_functions( assert out["ok"] is True and 0 < out["bound"]["probability"] < 1e-12 # past an event an output that reads the direction refuses the fields join = {"from": 0, "to": 1, "ev": [{"var": "x", "value": "1", "method": "add"}], "lift": 0} - out = verify_distribution([{"f": f, "g": ["o = x"]}, {"f": f, "g": ["o = y"]}], [[field], [field]], [join], - [lift], p, q=q) + out = verify_distribution( + [{"f": f, "g": ["o = x"]}, {"f": f, "g": ["o = y"]}], [[field], [field]], [join], [lift], p, q=q + ) assert out == {"ok": False, "why": "regime 2: a field changes the output"} def test_a_kernel_check_on_part_of_the_entries_is_checked_not_verified(monkeypatch): from symident.detection import finalize, verify + entry = {"vector": {"a": "1"}} monkeypatch.setattr(verify, "_in_nullspace_at", lambda *a: "partial") assert verify.verify_in_nullspace(entry, 0, ["a"], [], [1], 1, None, 0, 1) @@ -444,15 +525,18 @@ def test_a_direction_that_leaves_out_resting_state_columns_is_verified_on_the_on import numpy as np from symident.detection import finalize, verify + # a check on the given columns ignores the entries of the others, a full check does not def kcall(pt, p, nt): R = np.array([[1, 0, -1, 0], [0, 1, 1, 0], [0, 0, -1, 1]]) % p return {"ok": True, "R": R.ravel(), "pivots": [0, 1, 3], "rank": 3, "dim": 4} + names = ["a", "b", "s1", "s2"] def check(vec, cols): e = {"vector": vec} return verify.verify_in_nullspace(e, 2, names, names, [1] * 4, 1, kcall, 0, 4, cols=cols), e + held, e = check({"a": "1", "b": "-1", "s1": "1"}, [0, 1]) assert held and finalize.level_of(e, e["vector"]) == "verified" assert not check({"a": "2", "b": "-1", "s1": "1"}, [0, 1])[0] @@ -461,21 +545,33 @@ def check(vec, cols): def test_a_lift_whose_parameter_components_move_along_the_flow_is_refused(): from symident.detection.fields import exact_direction + rg = {"f": ["x = -k*x"], "g": ["y = c*x"]} # a parameter component that moves along the flow is no symmetry, whatever the state identities say field = {"k": "k*x", "c": "-c*x", "x": "x^2"} assert certify(regime_identities(rg, field))["ok"] is False - light = {"regimes": [rg], "gens": [[{}]], "regime_of": [1], "joins": [], "states": ["x"], - "tapes": [{"ver_ic": ["x = x"], "ver_t0": [], "ver_ev": []}]} + light = { + "regimes": [rg], + "gens": [[{}]], + "regime_of": [1], + "joins": [], + "states": ["x"], + "tapes": [{"ver_ic": ["x = x"], "ver_t0": [], "ver_ev": []}], + } assert exact_direction(light, field, [[0]], False)["ok"] is not True assert exact_direction(light, {"c": "-c", "x": "x"}, [[0]], False)["ok"] is True def _light(f, g, ic): """The setup of exact_direction for one regime without regime fields.""" - return {"regimes": [{"f": f, "g": g}], "gens": [[{}]], "regime_of": [1], "joins": [], - "states": [line.split("=", 1)[0].strip() for line in f], - "tapes": [{"ver_ic": ic, "ver_t0": [], "ver_ev": []}]} + return { + "regimes": [{"f": f, "g": g}], + "gens": [[{}]], + "regime_of": [1], + "joins": [], + "states": [line.split("=", 1)[0].strip() for line in f], + "tapes": [{"ver_ic": ic, "ver_t0": [], "ver_ev": []}], + } def test_a_scaling_that_rate_sums_absorb_is_lifted_on_the_states_it_reaches(): @@ -492,10 +588,15 @@ def test_a_scaling_that_rate_sums_absorb_is_lifted_on_the_states_it_reaches(): def test_a_lift_rational_in_the_parameters_is_solved_on_the_support(): from symident.detection.fields import exact_direction + # a change of basis of the linear block x5, x3 that keeps the input on x5 and the readout c*x3 f = ["x5 = u - (a + k)*x5 + kd*x3", "x3 = k*x5 - (b + kd)*x3", "w = c*x3 - m*w^2"] - field = {"a": "1", "b": "-kd/(a + k - b)", "k": "(b + kd - a - k)/(a + k - b)", - "c": "c*(a + k - b - kd)/(k*(a + k - b))"} + field = { + "a": "1", + "b": "-kd/(a + k - b)", + "k": "(b + kd - a - k)/(a + k - b)", + "c": "c*(a + k - b - kd)/(k*(a + k - b))", + } ex = exact_direction(_light(f, ["y = w"], ["x5 = 0", "x3 = 0", "w = 0"]), field, [[0]], False) assert ex["ok"] is True and set(ex["states"]) == {"x5", "x3"} assert "kd" in ex["states"]["x5"] @@ -503,6 +604,7 @@ def test_a_lift_rational_in_the_parameters_is_solved_on_the_support(): def test_a_lift_quadratic_in_the_states_is_solved_on_the_support(): from symident.detection.fields import exact_direction + # z + q*x^2 is observed: z moves by x^2, the start of z by x0^2 f = ["x = -k*x", "z = p*x^2 - m*z"] field = {"q": "-1", "p": "m - 2*k", "z0": "x0^2"} @@ -532,9 +634,14 @@ def _rest_with_events(names, events): return si.detect(si.Model(odes, {"y": f"{g}*z"}, events=events), equilibrate=True, reconstruct=True) -@pytest.mark.parametrize("names", [("k1", "k2", "k3", "k4", "k5", "s", "d"), - ("q9", "a", "b", "c", "e", "r", "w"), - ("zz", "k", "kk", "k4", "k1", "s", "d")]) +@pytest.mark.parametrize( + "names", + [ + ("k1", "k2", "k3", "k4", "k5", "s", "d"), + ("q9", "a", "b", "c", "e", "r", "w"), + ("zz", "k", "kk", "k4", "k1", "s", "d"), + ], +) @pytest.mark.parametrize("method, time", [("add", 3), ("replace", 3), ("add", 0)]) def test_resting_variety_directions_are_exact_with_events_on_a_driven_state(names, method, time): ev = [{"var": "z", "time": time, "value": "w" if method == "add" else "1", "method": method}] @@ -548,31 +655,50 @@ def test_a_field_whose_lines_the_flow_keeps_and_one_whose_bracket_holds_it_are_e # p1 + p12 is closed, so moving p1(0) against p12(0) keeps the output: [Y, F] = -(d + m) Y; the # bracket of m*d/dm with F is m*p1 times that direction import symident as si - r = si.detect(si.Model({"z": "-k*z", "p1": "k*z - (d + m)*p1", "p12": "m*p1 - d*p12"}, - {"y": "p1 + p12", "w": "z"}), reconstruct=True) + + r = si.detect( + si.Model({"z": "-k*z", "p1": "k*z - (d + m)*p1", "p12": "m*p1 - d*p12"}, {"y": "p1 + p12", "w": "z"}), + reconstruct=True, + ) assert r.rank == 4 and sorted(s.level for s in r.symmetries) == ["exact", "exact"] -@pytest.mark.parametrize("ev, proven", [({"var": "z", "time": 1, "value": "D", "method": "add"}, True), - ({"var": "p1", "time": 1, "value": "D", "method": "add"}, True), - ({"var": "p1", "time": 1, "value": "0", "method": "replace"}, False)]) +@pytest.mark.parametrize( + "ev, proven", + [ + ({"var": "z", "time": 1, "value": "D", "method": "add"}, True), + ({"var": "p1", "time": 1, "value": "D", "method": "add"}, True), + ({"var": "p1", "time": 1, "value": "0", "method": "replace"}, False), + ], +) def test_an_event_keeps_a_field_whose_lines_the_flow_keeps_where_it_maps_the_field_into_their_span(ev, proven): # a reset of p1 ends the split of p1(0) against p12(0), so nothing is proven there - r = si.detect(si.Model({"z": "-k*z", "p1": "k*z - (d + m)*p1", "p12": "m*p1 - d*p12"}, - {"y": "p1 + p12", "w": "z"}, events=[ev]), reconstruct=True) + r = si.detect( + si.Model( + {"z": "-k*z", "p1": "k*z - (d + m)*p1", "p12": "m*p1 - d*p12"}, {"y": "p1 + p12", "w": "z"}, events=[ev] + ), + reconstruct=True, + ) assert ("exact" in [s.level for s in r.symmetries]) is proven def test_directions_with_an_unknown_input_are_exact_through_their_lines(): # the input absorbs every change but x1(0): the input component is prolonged along the jets - r = si.detect(si.Model({"x1": "-(k12 + k1e)*x1 + k21*x2 + b*u", "x2": "k12*x1 - k21*x2"}, {"y1": "x1"}, - unknown_inputs=["u"]), reconstruct=True) + r = si.detect( + si.Model({"x1": "-(k12 + k1e)*x1 + k21*x2 + b*u", "x2": "k12*x1 - k21*x2"}, {"y1": "x1"}, unknown_inputs=["u"]), + reconstruct=True, + ) assert (r.rank, r.dim) == (1, 6) and r.info["rank_status"]["status"] == "proven" assert [s.level for s in r.symmetries] == ["exact"] * 5 def test_an_unknown_input_under_a_log_chart_and_free_powers_is_exact(): - r = si.detect(si.Model({"x1": "k01 + k1/(1 + (x2/(1 + w1))^ntetr) - x1", - "x2": "k02 + k2/(1 + (x1/(1 + w2))^nlaci) - x2"}, {"y1": "x1", "y2": "x2"}, - unknown_inputs=["w1", "w2"]), reconstruct=True) + r = si.detect( + si.Model( + {"x1": "k01 + k1/(1 + (x2/(1 + w1))^ntetr) - x1", "x2": "k02 + k2/(1 + (x1/(1 + w2))^nlaci) - x2"}, + {"y1": "x1", "y2": "x2"}, + unknown_inputs=["w1", "w2"], + ), + reconstruct=True, + ) assert r.info["rank_status"]["status"] == "proven" and [s.level for s in r.symmetries] == ["exact"] * 6 diff --git a/tests/test_experiments.py b/tests/test_experiments.py index 2fdf02b..8dd3cc9 100644 --- a/tests/test_experiments.py +++ b/tests/test_experiments.py @@ -23,6 +23,7 @@ def _has_msolve(): def _series(f, g, params): from symident.detection.discrete import Series + ic = {x: x for x in f} f = dict(f, time="1") ic["time"] = "0" @@ -58,8 +59,12 @@ def test_the_cycle_types_of_a_polynomial_modulo_primes(): @needs_msolve def test_a_cycle_of_three_states_has_no_rational_first_integral(): from symident.detection import firstint - *_, s = _series({"x1": "-k1*x1 + k3*x3 + u0", "x2": "k1*x1 - k2*x2", "x3": "k2*x2 - (k3 + k4)*x3"}, - {"y": "x1"}, ["k1", "k2", "k3", "k4", "u0"]) + + *_, s = _series( + {"x1": "-k1*x1 + k3*x3 + u0", "x2": "k1*x1 - k2*x2", "x3": "k2*x2 - (k3 + k4)*x3"}, + {"y": "x1"}, + ["k1", "k2", "k3", "k4", "u0"], + ) c = firstint.certificate(s) assert c["proven"] and c["field"] == "Q" (b,) = c["blocks"] @@ -69,6 +74,7 @@ def test_a_cycle_of_three_states_has_no_rational_first_integral(): @needs_msolve def test_a_cascade_takes_the_parameters_into_a_number_field(): from symident.detection import firstint + # two blocks of one state: their rational traces are dependent over Q, those over Q(alpha) are not *_, s = _series({"x1": "c - a*x1", "x2": "x1 - b*x2"}, {"y": "x2"}, ["a", "b", "c"]) c = firstint.certificate(s) @@ -77,14 +83,18 @@ def test_a_cascade_takes_the_parameters_into_a_number_field(): @needs_msolve -@pytest.mark.parametrize("f, g, params, why", [ - ({"x1": "-k1*x1 + k2*x2", "x2": "k1*x1 - k2*x2"}, {"y": "x1"}, ["k1", "k2"], "eigenvalue 0"), - ({"x1": "w*x2", "x2": "-w*x1"}, {"y": "x1"}, ["w"], "trace of the Jacobian at the equilibrium is 0"), - ({"x1": "(w + x3)*x2", "x2": "-w*x1", "x3": "0"}, {"y1": "x2", "y2": "x3"}, ["w"], "no isolated equilibrium"), - ({"x": "-k*x + time"}, {"y": "x"}, ["k"], "clock"), -]) +@pytest.mark.parametrize( + "f, g, params, why", + [ + ({"x1": "-k1*x1 + k2*x2", "x2": "k1*x1 - k2*x2"}, {"y": "x1"}, ["k1", "k2"], "eigenvalue 0"), + ({"x1": "w*x2", "x2": "-w*x1"}, {"y": "x1"}, ["w"], "trace of the Jacobian at the equilibrium is 0"), + ({"x1": "(w + x3)*x2", "x2": "-w*x1", "x3": "0"}, {"y1": "x2", "y2": "x3"}, ["w"], "no isolated equilibrium"), + ({"x": "-k*x + time"}, {"y": "x"}, ["k"], "clock"), + ], +) def test_a_first_integral_or_the_clock_leaves_the_premise_unproven(f, g, params, why): from symident.detection import firstint + *_, s = _series(f, g, params) c = firstint.certificate(s) assert not c["proven"] and why in c["why"] @@ -96,6 +106,7 @@ def test_the_count_of_two_experiments_is_that_of_the_parameters_and_the_first_st from symident.detection import discrete, multiexp from symident.gfp import PRIMES + parts, coords, s = _series({"x": "-k*x"}, {"y": "x^2"}, ["k"]) starts, why = multiexp.eligible(s) assert why is None and [str(v) for v in starts.values()] == ["x"] @@ -116,11 +127,17 @@ def test_the_count_of_two_experiments_is_that_of_the_parameters_and_the_first_st def test_a_fixed_start_or_an_event_leaves_the_route_out(): from symident.detection import multiexp from symident.detection.discrete import Series + seg = {"f": {"x": "-k*x"}, "g": {"y": "x"}, "ic": {"x": "1"}, "t": "0", "label": ""} assert "fixed" in multiexp.eligible(Series([{"segments": [seg]}], ["k"]))[1] seg = dict(seg, ic={"x": "x"}) - ev = {"f": seg["f"], "g": seg["g"], "events": [{"var": "x", "method": "add", "value": "1"}], "t": "1", - "label": "@1"} + ev = { + "f": seg["f"], + "g": seg["g"], + "events": [{"var": "x", "method": "add", "value": "1"}], + "t": "1", + "label": "@1", + } assert "events" in multiexp.eligible(Series([{"segments": [seg, ev]}], ["x", "k"]))[1] assert "one condition" in multiexp.eligible(Series([{"segments": [seg]}, {"segments": [seg]}], ["x", "k"]))[1] # a start coordinate that is a parameter as well @@ -156,6 +173,7 @@ def test_the_twisted_oscillator_leaves_the_route_to_one_experiment(): def test_a_conservation_law_is_found_over_the_field_of_the_parameters(): from symident.detection import multiexp + seg = {"f": {"x1": "-k1*x1*x3 + k2*x2", "x2": "(k1*x1*x3 - k2*x2)/v", "x3": "c - d*x3 + u", "u": "0"}} (law,) = multiexp.conservation_laws(seg, ["x1", "x2", "x3"]) assert law == {"x1": 1, "x2": spy.Symbol("v")} @@ -165,6 +183,7 @@ def test_a_conservation_law_is_found_over_the_field_of_the_parameters(): @needs_msolve def test_the_premise_holds_on_the_level_set_of_a_conservation_law(): from symident.detection import firstint, multiexp + f = {"x1": "-k1*x1*x3 + k2*x2", "x2": "k1*x1*x3 - k2*x2", "x3": "c - d*x3"} parts, coords, s = _series(f, {"y1": "x1", "y2": "x3"}, ["c", "d", "k1", "k2"]) laws = multiexp.conservation_laws(parts[0]["segments"][0], ["x1", "x2", "x3"]) diff --git a/tests/test_exponential.py b/tests/test_exponential.py index 6984fa8..11f6545 100644 --- a/tests/test_exponential.py +++ b/tests/test_exponential.py @@ -70,12 +70,10 @@ def test_modular_state_in_exp(): def test_bases_offsets_hyperbolic(): - g10 = general(det({"A": "kA - kd*A", "B": "kB - kE*exp10(A)*B"}, G_AB, - reconstruct=True))[0]["generator"] + g10 = general(det({"A": "kA - kd*A", "B": "kB - kE*exp10(A)*B"}, G_AB, reconstruct=True))[0]["generator"] assert expr_equal(g10["kE"], f"-log(10)*kE*({g10['A']})") - mixed = det({"A": "kA - kd*A", "B": "kB - kE*exp((10 - A)/10)*B + 2^(A/3)*c"}, G_AB, - reconstruct=True) + mixed = det({"A": "kA - kd*A", "B": "kB - kE*exp((10 - A)/10)*B + 2^(A/3)*c"}, G_AB, reconstruct=True) assert (mixed.rank, mixed.dim) == (6, 8) gm = general(mixed)[0]["generator"] assert expr_equal(gm["c"], f"-log(2)/3*c*({gm['A']})") @@ -139,8 +137,14 @@ def test_exp_stage_wide_block(): rne = "Ane*exp(-tsei/tref)*exp(-Ene/T)*cneg" rpe = "Ape*exp(-Epe/T)*alpha*(1 - alpha)" re_ = "Ae*exp(-Ee/T)*ce" - f = {"csei": f"-{rsei}", "cneg": f"-{rne}", "tsei": rne, "alpha": rpe, "ce": f"-{re_}", - "T": f"(Hsei*Wc*{rsei} + Hne*Wc*{rne} + Hpe*Wp*{rpe} + He*We*{re_} - hA*(T - Ta))/rhocp"} + f = { + "csei": f"-{rsei}", + "cneg": f"-{rne}", + "tsei": rne, + "alpha": rpe, + "ce": f"-{re_}", + "T": f"(Hsei*Wc*{rsei} + Hne*Wc*{rne} + Hpe*Wp*{rpe} + He*We*{re_} - hA*(T - Ta))/rhocp", + } obs = det(f, {"y": "T"}, reconstruct=True) assert len(obs.symmetries) == 8 red = si.reduce(obs) @@ -284,8 +288,9 @@ def test_a_numeric_base_with_a_free_exponent_adds_no_coordinate(): def test_numeric_bases_with_shared_primes(): - m = si.Model({"x": "-k*D^n/(D^n+h)*x"}, {"y": "x"}, - conditions={"rows": list("abcd"), "cols": {"D": [1, 3, 10, 30]}}) + m = si.Model( + {"x": "-k*D^n/(D^n+h)*x"}, {"y": "x"}, conditions={"rows": list("abcd"), "cols": {"D": [1, 3, 10, 30]}} + ) assert si.detect(m, cores=1).identifiable @@ -303,8 +308,10 @@ def test_a_free_exponent_of_a_sum_and_of_its_summand(): def test_a_free_exponent_of_a_condition_value_and_of_zero(): - odes = {"S": "kg*S - (kd + Emax*C^gam/(EC50^gam + C^gam))*S - (kg-kd)*(S+R)/Bmax*S", - "R": "(kg-kd)*(S+R)/Bmax*S - kd*R"} + odes = { + "S": "kg*S - (kd + Emax*C^gam/(EC50^gam + C^gam))*S - (kg-kd)*(S+R)/Bmax*S", + "R": "(kg-kd)*(S+R)/Bmax*S - kd*R", + } grid = {"rows": ["c0", "c1", "c4", "c16"], "cols": {"C": [0, 1, 4, 16]}} m = si.Model(odes, {"cfu": "S + R"}, trafo={"S": "S0", "R": "0"}, conditions=grid, fixed=["C"]) assert si.detect(m, cores=1).identifiable @@ -334,8 +341,13 @@ def test_a_declared_positive_expression_charts_the_logarithm(): def test_powers_of_a_sum_with_symbolic_and_high_exponents(): - odes = {"Ac": "-ke*Ac", "x1": "l0*x1/(1 + (l0/l1*(x1+x2+x3+x4))^psi)^(1/psi) - k2*Ac*x1", - "x2": "k2*Ac*x1 - k1*x2", "x3": "k1*(x2 - x3)", "x4": "k1*(x3 - x4)"} + odes = { + "Ac": "-ke*Ac", + "x1": "l0*x1/(1 + (l0/l1*(x1+x2+x3+x4))^psi)^(1/psi) - k2*Ac*x1", + "x2": "k2*Ac*x1 - k1*x2", + "x3": "k1*(x2 - x3)", + "x4": "k1*(x3 - x4)", + } ev = [{"var": "Ac", "time": 1, "value": 1, "method": "add"}] tr = {"Ac": "0", "x2": "0", "x3": "0", "x4": "0"} assert si.detect(si.Model(odes, {"y": "x1+x2+x3+x4"}, events=ev, trafo=tr, fixed=["ke"]), cores=1).identifiable @@ -345,8 +357,11 @@ def test_powers_of_a_sum_with_symbolic_and_high_exponents(): def test_a_high_power_of_a_state_beside_a_free_scale(): base = {"h": "(-p0*(h^8 - p1) + p2*(h - p1) - (T - p3))/C", "T": "kT", "I": "T"} - r = si.detect(si.Model(base, {"y": "a + b*h + g*I"}, trafo={"T": "1/3", "kT": "2/7", "I": "0"}, fixed=["kT"]), - reconstruct=True, cores=1) + r = si.detect( + si.Model(base, {"y": "a + b*h + g*I"}, trafo={"T": "1/3", "kT": "2/7", "I": "0"}, fixed=["kT"]), + reconstruct=True, + cores=1, + ) assert (r.rank, r.dim) == (7, 9) and {s.level for s in r.symmetries} == {"exact"} @@ -363,33 +378,42 @@ def test_a_free_exponent_of_a_parameter_keeps_the_exponent_as_a_coordinate(): def test_a_large_integer_power_costs_a_logarithmic_tape(): from symident.sym.tape import _emit_tape_shared + x = spy.Symbol("x") - n = 10 ** 13 - op = _emit_tape_shared([x ** n], [x ** (-n)], {"x": 0}, 1)[0] + n = 10**13 + op = _emit_tape_shared([x**n], [x ** (-n)], {"x": 0}, 1)[0] # square and multiply: below 2 log2(n) products per power, the inverse shared assert len(op) <= 2 * n.bit_length() + 2 def test_degrees_past_the_dense_limit_come_from_the_expression_tree(): from symident.detection.bound import _total_degree, _vector_degree + x, y = spy.symbols("x y") - n = 10 ** 13 - assert _total_degree(x ** n * (1 - y) - x ** (n // 3) * y, [x, y]) == n + 1 - assert _vector_degree([(x ** n * (1 - y) - x ** (n // 3) * y) / (1 + x ** (n // 2))]) == n + 1 + n = 10**13 + assert _total_degree(x**n * (1 - y) - x ** (n // 3) * y, [x, y]) == n + 1 + assert _vector_degree([(x**n * (1 - y) - x ** (n // 3) * y) / (1 + x ** (n // 2))]) == n + 1 # the sodium current of Luo-Rudy 1991 with the gates h and j in the branch V >= -40, and the inward rectifier LR91_RATES = { - "am": "0.32*(V+47.13)/(1-exp(-0.1*(V+47.13)))", "bm": "0.08*exp(-V/11)", - "bh": "1/(0.13*(1+exp((V+10.66)/(-11.1))))", "bj": "0.3*exp(-2.535e-7*V)/(1+exp(-0.1*(V+32)))", + "am": "0.32*(V+47.13)/(1-exp(-0.1*(V+47.13)))", + "bm": "0.08*exp(-V/11)", + "bh": "1/(0.13*(1+exp((V+10.66)/(-11.1))))", + "bj": "0.3*exp(-2.535e-7*V)/(1+exp(-0.1*(V+32)))", "aK": "1.02/(1+exp(0.2385*(V-EK1-59.215)))", - "bK": "(0.49124*exp(0.08032*(V-EK1+5.476)) + exp(0.06175*(V-EK1-594.31)))/(1+exp(-0.5143*(V-EK1+4.753)))"} + "bK": "(0.49124*exp(0.08032*(V-EK1+5.476)) + exp(0.06175*(V-EK1-594.31)))/(1+exp(-0.5143*(V-EK1+4.753)))", +} def test_a_heart_model_with_unround_rates_keeps_to_small_degrees(): r = LR91_RATES - f = {"V": f"-(gNa*m^3*h*j*(V - ENa) + gK1*({r['aK']})/(({r['aK']}) + ({r['bK']}))*(V - EK1))/Cm", - "m": f"{r['am']}*(1-m) - {r['bm']}*m", "h": f"-{r['bh']}*h", "j": f"-{r['bj']}*j"} + f = { + "V": f"-(gNa*m^3*h*j*(V - ENa) + gK1*({r['aK']})/(({r['aK']}) + ({r['bK']}))*(V - EK1))/Cm", + "m": f"{r['am']}*(1-m) - {r['bm']}*m", + "h": f"-{r['bh']}*h", + "j": f"-{r['bj']}*j", + } res = det(f, {"y": "V"}) assert (res.rank, res.dim) == (6, 9) gens = sorted(sorted(d["generator"]) for d in res.symmetries) diff --git a/tests/test_homotopy.py b/tests/test_homotopy.py index 7041c86..7164100 100644 --- a/tests/test_homotopy.py +++ b/tests/test_homotopy.py @@ -34,18 +34,23 @@ def test_series_kernel_of_a_row_with_series_entries(): N = 3 S = np.zeros((1, 2 * N), dtype=np.int64) S[0, 0] = 1 - S[0, N:N + 2] = [P - 1, P - 1] + S[0, N : N + 2] = [P - 1, P - 1] ns = series_null(S, 2, N, P) assert ns["free"] == [1] and ns["piv"] == [0] assert ns["V"][0].tolist() == [[1, 1, 0], [1, 0, 0]] -LIN2 = dict(f={"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, g={"y": "s*x2"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) -BIND = dict(f={"A": "ka - kd*A - kon*A*L", "C": "kon*A*L - koff*C"}, g={"y": "s*C"}, - conditions={"rows": ["a", "b"], "cols": {"L": [1, 2]}}) -SAT = dict(f={"x": "v*u*x/(K + x) + kb - d*x"}, g={"y": "s*x"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) +LIN2 = dict( + f={"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2"}, + g={"y": "s*x2"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, +) +BIND = dict( + f={"A": "ka - kd*A - kon*A*L", "C": "kon*A*L - koff*C"}, + g={"y": "s*C"}, + conditions={"rows": ["a", "b"], "cols": {"L": [1, 2]}}, +) +SAT = dict(f={"x": "v*u*x/(K + x) + kb - d*x"}, g={"y": "s*x"}, conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) def _expr(x): @@ -65,6 +70,7 @@ def first(self): if self.an.joint: out.extend(self.homotopy([{"closed_form": False} for _ in self.residual])) return run(self) + monkeypatch.setattr(Reconstruction, "run", first) symmetry_detection(**model, equilibrate=True, reconstruct=True) return [classify_direction(d) for d in out if d.get("closed_form")] @@ -80,9 +86,11 @@ def test_homotopy_fits_entries_in_the_parameters(monkeypatch): def test_homotopy_replaces_linear_resting_states(monkeypatch): dirs = homotopy_directions(LIN2, monkeypatch) - want = [{"k1": "k1^2 + k1*kl", "k2": "k1*k2 + k2*kl", "kb": "k1*kb", "kin": "k1*kin"}, - {"k1": "k1", "k2": "k2", "kl": "-k1"}, - {"k1": "k1^2 + k1*kl", "k2": "k2*kl"}] + want = [ + {"k1": "k1^2 + k1*kl", "k2": "k1*k2 + k2*kl", "kb": "k1*kb", "kin": "k1*kin"}, + {"k1": "k1", "k2": "k2", "kl": "-k1"}, + {"k1": "k1^2 + k1*kl", "k2": "k2*kl"}, + ] assert len(dirs) == 3 for d, w in zip(dirs, want): assert d["type"] == "general" and _same(d["vector"], w) @@ -90,9 +98,9 @@ def test_homotopy_replaces_linear_resting_states(monkeypatch): def test_homotopy_closes_what_the_other_routes_leave_open(): def general(hom): - r = symmetry_detection(**SAT, equilibrate=True, reconstruct=True, - control=reconst_control(homotopy=hom)) + r = symmetry_detection(**SAT, equilibrate=True, reconstruct=True, control=reconst_control(homotopy=hom)) return [d for d in r["symmetries"] if d["type"] == "general"] + assert [d.get("generator") for d in general(False)] == [None, None] on = general(True) assert [d["route"] for d in on] == ["homotopy fit in the parameters and the resting states"] * 2 @@ -117,6 +125,7 @@ def test_homotopy_directions_without_an_exact_proof_are_verified_on_the_resting_ def test_states_entering_a_resting_equation_linearly_are_eliminated(): from symident.detection.observability.homstate import reduce_relations + sat = "x = v*u*x/(K + x) + kb - d*x" core, rel = reduce_relations([sat, "z = k*x - c*z"], ["x", "z"]) assert core == ["x"] and len(rel) == 1 @@ -130,13 +139,16 @@ def test_states_entering_a_resting_equation_linearly_are_eliminated(): def test_homotopy_closes_a_saturating_state_seen_through_a_linear_one(): - m = dict(f={"x": "v*u*x/(K + x) + kb - d*x", "z": "k*x - c*z"}, g={"y": "s*z"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = dict( + f={"x": "v*u*x/(K + x) + kb - d*x", "z": "k*x - c*z"}, + g={"y": "s*z"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) def general(hom): - r = symmetry_detection(**m, equilibrate=True, reconstruct=True, - control=reconst_control(homotopy=hom)) + r = symmetry_detection(**m, equilibrate=True, reconstruct=True, control=reconst_control(homotopy=hom)) return [d for d in r["symmetries"] if d["type"] == "general"] + off = general(False) assert len(off) >= 2 and all(d.get("generator") is None for d in off) on = general(True) @@ -145,8 +157,12 @@ def general(hom): def test_homotopy_closes_a_direction_in_the_recast_coordinates_of_a_symbolic_exponent(): - m = dict(f={"R": "k_pr/(1 + k_fb*FB^nh) - k_dg*R", "FB": "k_pf*R - k_df*FB"}, - g={"R_obs": "s1*R", "FB_obs": "s2*FB"}, equilibrate=True, reconstruct=True) + m = dict( + f={"R": "k_pr/(1 + k_fb*FB^nh) - k_dg*R", "FB": "k_pf*R - k_df*FB"}, + g={"R_obs": "s1*R", "FB_obs": "s2*FB"}, + equilibrate=True, + reconstruct=True, + ) off = symmetry_detection(**m, control=reconst_control(homotopy=False)) assert [s["level"] for s in off["symmetries"]].count("open") == 1 on = symmetry_detection(**m) @@ -158,10 +174,14 @@ def test_homotopy_closes_a_direction_in_the_recast_coordinates_of_a_symbolic_exp def _guarded(recast=(), joint=True, gaps=False, ss=True, transient=False, at_one=False, tau="", **ctrl): rec = Reconstruction.__new__(Reconstruction) - rec.an = SimpleNamespace(recast=list(recast), joint=joint, transient=transient, znames=["k", "tau"], - multi={"tapes": [{"ver_time": tau}]}, - run=SimpleNamespace(ss_constraint=ss, has_gaps=gaps, series_gaps=False, timing=False, - leaf_names=["k"])) + rec.an = SimpleNamespace( + recast=list(recast), + joint=joint, + transient=transient, + znames=["k", "tau"], + multi={"tapes": [{"ver_time": tau}]}, + run=SimpleNamespace(ss_constraint=ss, has_gaps=gaps, series_gaps=False, timing=False, leaf_names=["k"]), + ) rec.sc = {"ref": {"at_one": at_one}} rec.ctrl = reconst_control(**ctrl) rec.residual = [3] @@ -170,15 +190,22 @@ def _guarded(recast=(), joint=True, gaps=False, ss=True, transient=False, at_one return rec.homotopy(interp) is interp and rec.attempts[0][0] == "homotopy" -@pytest.mark.parametrize("kw", [{"joint": False}, {"gaps": True, "at_one": True}, {"gaps": True, "tau": "tau"}, - {"homotopy": False}, {"joint": False, "ss": False, "transient": True}]) +@pytest.mark.parametrize( + "kw", + [ + {"joint": False}, + {"gaps": True, "at_one": True}, + {"gaps": True, "tau": "tau"}, + {"homotopy": False}, + {"joint": False, "ss": False, "transient": True}, + ], +) def test_homotopy_declines_where_it_does_not_apply(kw): assert _guarded(**kw) def test_open_directions_list_the_routes_tried(): - r = symmetry_detection(**SAT, equilibrate=True, reconstruct=True, - control=reconst_control(homotopy=False)) + r = symmetry_detection(**SAT, equilibrate=True, reconstruct=True, control=reconst_control(homotopy=False)) att = r["info"]["attempts"] assert len(att) == 2 assert all(["homotopy", "switched off (reconst_control(homotopy=False))"] in a["attempts"] for a in att) @@ -187,9 +214,14 @@ def test_open_directions_list_the_routes_tried(): def test_homotopy_degree_is_its_own_setting(): from symident.detection.observability.homotopy import Homotopy - rec = SimpleNamespace(an=SimpleNamespace(sys=SimpleNamespace(hom_prepare=lambda base: None, hom_params=[]), - run=SimpleNamespace(slot=lambda nm: None), - ctrl=reconst_control(degree_cap=1, homotopy_degree=5))) + + rec = SimpleNamespace( + an=SimpleNamespace( + sys=SimpleNamespace(hom_prepare=lambda base: None, hom_params=[]), + run=SimpleNamespace(slot=lambda nm: None), + ctrl=reconst_control(degree_cap=1, homotopy_degree=5), + ) + ) assert Homotopy(rec, [0], 1).d_cap == 5 with pytest.raises(ValueError): reconst_control(homotopy_degree=0) @@ -197,9 +229,10 @@ def test_homotopy_degree_is_its_own_setting(): def test_radical_initial_values_have_their_polynomial_relation(): from symident.sym.algebraic import radical_relation + x, a, b = spy.symbols("x a b") (f,) = radical_relation("x", "(b + sqrt(b^2 + 4*a))/2".replace("^", "**")) - assert spy.expand(f.xreplace({x: (b + spy.sqrt(b**2 + 4*a)) / 2})) == 0 + assert spy.expand(f.xreplace({x: (b + spy.sqrt(b**2 + 4 * a)) / 2})) == 0 (f,) = radical_relation("x", "sqrt(1 + sqrt(a))") assert spy.degree(f, x) == 4 (f,) = radical_relation("x", "a**(1/3) + b") @@ -210,6 +243,7 @@ def test_radical_initial_values_have_their_polynomial_relation(): def test_series_of_a_root_follows_the_kernel_branch(): from symident.gfp import sqrt_mod from symident.sym.taylor import _mul, series_of + a = spy.Symbol("a") p = 1000003 r = series_of(spy.sqrt(a), {a: [9, 3, 5]}, 5, p) @@ -219,13 +253,18 @@ def test_series_of_a_root_follows_the_kernel_branch(): def test_homotopy_closes_a_direction_of_a_start_with_radicals(): # the start is a resting state given in closed form through a square root b = "(v*u + kb - d*K)" - m = dict(f={"x": "v*u*x/(K + x) + kb - d*x"}, g={"y": "s*x"}, trafo={"x": f"({b} + sqrt({b}^2 + 4*d*kb*K))/(2*d)"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}) + m = dict( + f={"x": "v*u*x/(K + x) + kb - d*x"}, + g={"y": "s*x"}, + trafo={"x": f"({b} + sqrt({b}^2 + 4*d*kb*K))/(2*d)"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ) def run(hom): # with the jet route off, only the homotopy closes a start with radicals with si.switches(NOJET=True): return symmetry_detection(**m, reconstruct=True, control=reconst_control(homotopy=hom))["symmetries"] + assert not all(d["explicit"] for d in run(False)) on = run(True) assert all(d["explicit"] for d in on) and any(str(d["route"]).startswith("homotopy fit") for d in on) @@ -233,13 +272,18 @@ def run(hom): def test_homotopy_follows_lines_through_events_after_the_start(): # a resting state seen only through downstream states, with a dose at the start and one later - f = {"x": "v*u*x/(K + x) + kb - d*x", "Rec": "k*x - degRec*Rec - Bind*L*Rec", "L": "-Bind*L*Rec", - "A": "Bind*L*Rec - degA*A"} + f = { + "x": "v*u*x/(K + x) + kb - d*x", + "Rec": "k*x - degRec*Rec - Bind*L*Rec", + "L": "-Bind*L*Rec", + "A": "Bind*L*Rec - degA*A", + } cond = {"rows": ["a", "b"], "cols": {"u": [1, 2], "d0": [1, 2], "d1": [1, 1]}} - ev = [{"var": "L", "time": 0, "value": "d0", "method": "add"}, - {"var": "L", "time": 24, "value": "d1", "method": "add"}] - r = symmetry_detection(f=f, g={"y": "s*A"}, events=ev, conditions=cond, equilibrate=True, - reconstruct=True, cores=2) + ev = [ + {"var": "L", "time": 0, "value": "d0", "method": "add"}, + {"var": "L", "time": 24, "value": "d1", "method": "add"}, + ] + r = symmetry_detection(f=f, g={"y": "s*A"}, events=ev, conditions=cond, equilibrate=True, reconstruct=True, cores=2) gen = [d for d in r["symmetries"] if d["type"] == "general"] assert len(gen) == 2 and all(d["explicit"] for d in gen) assert {d["route"] for d in gen} == {"homotopy fit in the parameters and the resting states"} @@ -249,22 +293,35 @@ def test_continuation_moves_held_moiety_pivots_as_parameters(): from symident.sym.continuation import continue_resting_state a0 = 5 * 7 * pow(3, -1, P) % P - sol = continue_resting_state(["A = -k1*A + k2*B", "B = k1*A - k2*B"], ["A", "B"], ["k1", "k2"], - {"k1": 3, "k2": 5}, {"k1": 1}, {"A": a0, "B": 7}, P, 4, held={"B": 0}) + sol = continue_resting_state( + ["A = -k1*A + k2*B", "B = k1*A - k2*B"], + ["A", "B"], + ["k1", "k2"], + {"k1": 3, "k2": 5}, + {"k1": 1}, + {"A": a0, "B": 7}, + P, + 4, + held={"B": 0}, + ) assert sol["ok"] and sol["df_state_cols"] == ["A"] and sol["df_param_cols"] == ["k1", "k2", "B"] assert sol["val_by"]["A"] == [a0 * pow(-pow(3, -1, P), k, P) % P for k in range(5)] assert sol["val_by"]["B"] == [7, 0, 0, 0, 0] -@pytest.mark.parametrize("tail, at_one", [ - ({0: 1, 1: 1}, (1, P - pow(2, -1, P))), - ({0: 1}, (1, P - 1)), - (None, None), -]) +@pytest.mark.parametrize( + "tail, at_one", + [ + ({0: 1, 1: 1}, (1, P - pow(2, -1, P))), + ({0: 1}, (1, P - 1)), + (None, None), + ], +) def test_the_series_kernel_is_read_at_one_where_it_is_rational(tail, at_one): import math from symident import _core + N = 8 S = np.zeros((1, 2 * N), dtype=np.int64) if tail is None: diff --git a/tests/test_inputs.py b/tests/test_inputs.py index f4fee04..0c42078 100644 --- a/tests/test_inputs.py +++ b/tests/test_inputs.py @@ -16,10 +16,12 @@ def _model(odes=F, obs=G, **kw): CASES = { "stoichiometry rows for the species": lambda: si.Model( - reactions=dict(RX, stoichiometry=[[-1, 1], [1, -1], [0, 0]]), observables=G), + reactions=dict(RX, stoichiometry=[[-1, 1], [1, -1], [0, 0]]), observables=G + ), "stoichiometry transposed": lambda: si.Model(reactions=dict(RX, stoichiometry=[[-1], [1]]), observables=G), - "rates short": lambda: si.Model(reactions={"species": ["A", "B"], "stoichiometry": [[-1, 1]], "rates": []}, - observables=G), + "rates short": lambda: si.Model( + reactions={"species": ["A", "B"], "stoichiometry": [[-1, 1]], "rates": []}, observables=G + ), "empty right-hand side": lambda: _model({"x": ""}), "right-hand side None": lambda: _model({"x": None}), "empty observable": lambda: _model(obs={"y": " "}), diff --git a/tests/test_install.py b/tests/test_install.py index 1e22149..53fead7 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -19,9 +19,11 @@ def fake_msolve(path, version="0.10.1", answer=GOOD): # a script that answers the test system of msolve_check and reports `version` os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as fh: - fh.write(f'#!/bin/sh\nif [ "$1" = "-V" ]; then echo "{version}"; exit 0; fi\n' - 'while [ $# -gt 0 ]; do [ "$1" = "-o" ] && out="$2"; shift; done\n' - f"printf '%s' '{answer}' > \"$out\"\n") + fh.write( + f'#!/bin/sh\nif [ "$1" = "-V" ]; then echo "{version}"; exit 0; fi\n' + 'while [ $# -gt 0 ]; do [ "$1" = "-o" ] && out="$2"; shift; done\n' + f"printf '%s' '{answer}' > \"$out\"\n" + ) os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR) return path @@ -85,20 +87,22 @@ def test_cache_bins_complete_builds_only(tmp_path): for v in ("0.9.9", "0.10.1"): (cache / f"deps-msolve-{v}" / ".msolve-complete").touch() name = "msolve.exe" if sys.platform == "win32" else "msolve" - assert install._cache_bins() == [str(cache / f"deps-msolve-{v}" / "bin" / name) - for v in ("0.10.1", "0.9.9")] + assert install._cache_bins() == [str(cache / f"deps-msolve-{v}" / "bin" / name) for v in ("0.10.1", "0.9.9")] def tools(monkeypatch, have): monkeypatch.setattr(install.shutil, "which", lambda t: f"/bin/{t}" if t in have else None) -@pytest.mark.parametrize("platform, have, match", [ - ("win32", {"curl", "make", "m4"}, "does not build on Windows"), - ("linux", {"make", "m4"}, "needs curl or wget"), - ("linux", {"wget"}, "needs make and m4"), - ("linux", {"curl", "make"}, "needs m4 for"), -]) +@pytest.mark.parametrize( + "platform, have, match", + [ + ("win32", {"curl", "make", "m4"}, "does not build on Windows"), + ("linux", {"make", "m4"}, "needs curl or wget"), + ("linux", {"wget"}, "needs make and m4"), + ("linux", {"curl", "make"}, "needs m4 for"), + ], +) def test_install_msolve_preconditions(monkeypatch, platform, have, match): monkeypatch.setattr(sys, "platform", platform) tools(monkeypatch, have) @@ -126,6 +130,7 @@ def run(args, **kw): fake_msolve(os.path.join(prefix, "bin", "msolve"), answer=GOOD if working else "[1]") open(os.path.join(prefix, ".msolve-complete"), "w").close() return subprocess.CompletedProcess(args, returncode, stdout=f"building\n{prefix}\n") + monkeypatch.setattr(install.subprocess, "run", run) @@ -142,10 +147,13 @@ def test_install_msolve_builds_into_the_cache(monkeypatch, tmp_path, capsys): @posix_only -@pytest.mark.parametrize("returncode, working, match", [ - (1, True, "the msolve build failed"), - (0, False, "produced no working msolve"), -]) +@pytest.mark.parametrize( + "returncode, working, match", + [ + (1, True, "the msolve build failed"), + (0, False, "produced no working msolve"), + ], +) def test_install_msolve_build_errors(monkeypatch, returncode, working, match): tools(monkeypatch, {"curl", "make", "m4"}) stub_build(monkeypatch, returncode, working) @@ -155,6 +163,7 @@ def test_install_msolve_build_errors(monkeypatch, returncode, working, match): def test_install_msolve_takes_version_and_jobs_from_the_switches(monkeypatch, tmp_path): import symident as si + monkeypatch.setattr(sys, "platform", "linux") tools(monkeypatch, {"curl", "make", "m4"}) seen = {} @@ -162,6 +171,7 @@ def test_install_msolve_takes_version_and_jobs_from_the_switches(monkeypatch, tm def run(args, **kw): seen.update(kw["env"]) return subprocess.CompletedProcess(args, 1, stdout="") + monkeypatch.setattr(install.subprocess, "run", run) with si.switches(MSOLVE_VERSION="0.9.9", JOBS=3), pytest.raises(RuntimeError, match="build failed"): install.install_msolve(dir=str(tmp_path), ask=False, quiet=True) diff --git a/tests/test_kernel_modes.py b/tests/test_kernel_modes.py index c4d52fc..530e843 100644 --- a/tests/test_kernel_modes.py +++ b/tests/test_kernel_modes.py @@ -8,9 +8,17 @@ from symident import _core from symident.gfp import null_residues -FUNS = ["sym_obs_null_multi", "sym_obs_null_batch", "sym_obs_rank_profile", "sym_obs_null_chain", - "sym_obs_chain_rank_profile", "sym_obs_chain_rows", "sym_obs_null_chain_seed_batch", - "sym_obs_null_chain_point_batch", "sym_segment_ranks"] +FUNS = [ + "sym_obs_null_multi", + "sym_obs_null_batch", + "sym_obs_rank_profile", + "sym_obs_null_chain", + "sym_obs_chain_rank_profile", + "sym_obs_chain_rows", + "sym_obs_null_chain_seed_batch", + "sym_obs_null_chain_point_batch", + "sym_segment_ranks", +] def ev(var, time, value, method): @@ -20,23 +28,31 @@ def ev(var, time, value, method): MODELS = { "rational": lambda: si.Model({"x": "v*x/(K + x) - d*x"}, {"y": "s*x"}), "start in closed form": lambda: si.Model( - {"x": "v*u*x/(K + x) + kb - d*x"}, {"y": "s*x"}, + {"x": "v*u*x/(K + x) + kb - d*x"}, + {"y": "s*x"}, trafo={"x": "(v*u + kb - d*K + sqrt((v*u + kb - d*K)^2 + 4*d*kb*K))/(2*d)"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}), + conditions={"rows": ["a", "b"], "cols": {"u": [1, 2]}}, + ), "unknown input": lambda: si.Model({"L": "-(c*T + L)/tau"}, {"y": "L"}, unknown_inputs=["T"]), "dose at an unknown time": lambda: si.Model( - {"D": "-ka*D", "A": "ka*D - k*A"}, {"y": "A"}, events=[ev("D", "tau", "d", "add")], - trafo={"D": "0", "A": "0"}), + {"D": "-ka*D", "A": "ka*D - k*A"}, {"y": "A"}, events=[ev("D", "tau", "d", "add")], trafo={"D": "0", "A": "0"} + ), "switch with a kink": lambda: si.Model( - {"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, {"y": "x"}, - events=[ev("u", 0, "0", "replace"), ev("u", "tau", "1", "replace")]), + {"x": "-k1*x + u*z", "z": "-(1-u)*k2*z", "u": "0"}, + {"y": "x"}, + events=[ev("u", 0, "0", "replace"), ev("u", "tau", "1", "replace")], + ), "scaled and reset state": lambda: si.Model( - {"A": "-k*A/(1 + A)"}, {"y": "s*A"}, events=[ev("A", 2, "f", "multiply"), ev("A", 4, "r", "replace")]), + {"A": "-k*A/(1 + A)"}, {"y": "s*A"}, events=[ev("A", 2, "f", "multiply"), ev("A", 4, "r", "replace")] + ), "switch at a given time": lambda: si.Model( - {"x": "piecewise(-a*x + c*z, time > 1, -b*x*z)", "z": "-d*z/(1 + z)"}, {"y": "s*x"}), + {"x": "piecewise(-a*x + c*z, time > 1, -b*x*z)", "z": "-d*z/(1 + z)"}, {"y": "s*x"} + ), "conditions in values": lambda: si.Model( - {"x": "k1*u - k2*x*z", "z": "k3*x - k4*z"}, {"y": "s*z"}, - conditions={"rows": ["a", "b", "c"], "cols": {"u": [1, 2, 0], "k4": ["k4", "k4", "k5"]}}), + {"x": "k1*u - k2*x*z", "z": "k3*x - k4*z"}, + {"y": "s*z"}, + conditions={"rows": ["a", "b", "c"], "cols": {"u": [1, 2, 0], "k4": ["k4", "k4", "k5"]}}, + ), } @@ -49,7 +65,9 @@ def spy(name): def call(*a, **k): seen.append((name, a, k)) return f(*a, **k) + return call + for name in FUNS: monkeypatch.setattr(_core, name, spy(name)) si.detect(model, **kw) @@ -101,8 +119,9 @@ def test_the_cases_reach_every_part_of_the_kernel(monkeypatch): def test_a_vanishing_reciprocal_fails_in_both_modes(monkeypatch): - _, (tapes, nl, ns, zs, pt, p, nt, *_), _ = [c for c in _calls(monkeypatch, MODELS["rational"]()) - if c[0] == "sym_obs_null_multi"][-1] + _, (tapes, nl, ns, zs, pt, p, nt, *_), _ = [ + c for c in _calls(monkeypatch, MODELS["rational"]()) if c[0] == "sym_obs_null_multi" + ][-1] a, b = _both(monkeypatch, "sym_obs_null_multi", (tapes, nl, ns, zs, np.zeros_like(pt), p, nt), {}) assert a["ok"] is False and b["ok"] is False @@ -151,4 +170,4 @@ def test_lanes_along_directions_equal_the_rows(monkeypatch): pad = np.concatenate([V, np.zeros((nz, nz), dtype=np.int64)], axis=1) for k, point in enumerate((pt, other)): rows = _core.sym_obs_annihilates(tapes, nl, ns, zs, point, p, nt, pad) - assert list(rows["zero"])[:V.shape[1]] == list(got[k]["zero"]) + assert list(rows["zero"])[: V.shape[1]] == list(got[k]["zero"]) diff --git a/tests/test_kernel_parity.py b/tests/test_kernel_parity.py index 7e912f5..087e5be 100644 --- a/tests/test_kernel_parity.py +++ b/tests/test_kernel_parity.py @@ -42,8 +42,7 @@ def same(a, b, path="result"): if aa.size == 0 and bb.size == 0: return assert aa.size == bb.size, f"{path}: size {aa.size} != {bb.size}" - np.testing.assert_array_equal(aa.reshape(bb.shape) if aa.shape != bb.shape else aa, bb, - err_msg=path) + np.testing.assert_array_equal(aa.reshape(bb.shape) if aa.shape != bb.shape else aa, bb, err_msg=path) def snake_keys(x): @@ -106,9 +105,12 @@ def test_the_line_mode_of_one_segment_matches_the_shared_series_axis(): assert line["rank_s"] == shared["rank_s"] and line["N"] == shared["N"] == T + 1 # the same series row space: the same kernel along the line from symident.detection.series import series_null + p, nz = int(args["p_in"]), len(args["z_slots"]) - ks = [series_null(np.asarray(o["S"], dtype=np.int64).reshape(int(o["rank_s"]), -1), nz, T + 1, p) - for o in (line, shared)] + ks = [ + series_null(np.asarray(o["S"], dtype=np.int64).reshape(int(o["rank_s"]), -1), nz, T + 1, p) + for o in (line, shared) + ] assert ks[0]["free"] == ks[1]["free"] for a, b in zip(ks[0]["V"], ks[1]["V"]): np.testing.assert_array_equal(np.asarray(a), np.asarray(b)) @@ -119,6 +121,7 @@ def test_the_line_mode_of_one_segment_matches_the_shared_series_axis(): def test_the_line_mode_keeps_the_gaps_formal_and_truncates_consistently(): from symident.detection.series import series_null + args = _chain_call("Detection_symObsNullChain_1762441_01") plain = _core.sym_obs_null_chain(**dict(args, Mtot=2)) zero = np.zeros((args["n_leaves"], 3), dtype=np.int64) @@ -140,8 +143,9 @@ def test_the_line_mode_keeps_the_gaps_formal_and_truncates_consistently(): def test_the_line_mode_refuses_an_event_time_that_moves_along_the_line(): args = _chain_call("Detection_symObsNullChain_1762441_01") - seg = dict(args["chains"][0][1], tm_op=[1], tm_a=[0], tm_b=[0], tm_cnum=["0"], tm_cden=["1"], - tm_out=[args["n_leaves"]]) + seg = dict( + args["chains"][0][1], tm_op=[1], tm_a=[0], tm_b=[0], tm_cnum=["0"], tm_cden=["1"], tm_out=[args["n_leaves"]] + ) args = dict(args, chains=[[args["chains"][0][0], seg]]) ser = np.ones((args["n_leaves"], 2), dtype=np.int64) assert not _core.sym_obs_null_chain(**dict(args, Mtot=1, point_ser=ser, ser_order=2))["ok"] diff --git a/tests/test_models.py b/tests/test_models.py index 9acf352..7eaf44c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -52,17 +52,27 @@ def plain(spec): so that a lifted generator can be checked on the equations directly.""" tr = spec.get("trafo") # a coordinate named like a state is the initial value of that state, which the lifted field moves apart - return (spec.get("positive") in (None, True) and isinstance(tr, dict) and set(spec["f"]) <= set(tr) - and not spec.get("conditions") and not spec.get("events") and not spec.get("forcings") - and not spec.get("equilibrate") and not spec.get("reduceCQ") and isinstance(spec.get("g"), dict) - and "piecewise" not in str(spec.get("f"))) + return ( + spec.get("positive") in (None, True) + and isinstance(tr, dict) + and set(spec["f"]) <= set(tr) + and not spec.get("conditions") + and not spec.get("events") + and not spec.get("forcings") + and not spec.get("equilibrate") + and not spec.get("reduceCQ") + and isinstance(spec.get("g"), dict) + and "piecewise" not in str(spec.get("f")) + ) def lifted_identities(spec, d): """The residuals of a lifted generator X: X(f_i) - sum_j f_j d(xi_i)/d(x_j), X(g_k), and xi_x - X(x0) at the initial values.""" + def sym(k): return spy.Symbol(k, positive=True) + f = {sym(k): parse(v, True) for k, v in spec["f"].items()} g = [parse(v, True) for v in spec["g"].values()] tr = {sym(k): parse(v, True) for k, v in (spec.get("trafo") or {}).items()} @@ -73,6 +83,7 @@ def sym(k): def X(e): return sum(c * spy.diff(e, k) for k, c in xi.items()) + out = [X(f[x]) - sum(f[y] * spy.diff(xi.get(x, 0), y) for y in f) for x in f] out += [X(e) for e in g] x0 = {x: tr[x] for x in f} @@ -114,8 +125,9 @@ def vanishes(e): if x in e.free_symbols: u = spy.Symbol(f"{x}_root", positive=True) e = e.xreplace({x: (u**2 - c) / a}) - e = e.replace(lambda x: x.is_Pow and x.exp == spy.Rational(1, 2), - lambda x: spy.sqrt(spy.factor(spy.together(x.base)))) + e = e.replace( + lambda x: x.is_Pow and x.exp == spy.Rational(1, 2), lambda x: spy.sqrt(spy.factor(spy.together(x.base))) + ) return False @@ -129,11 +141,18 @@ def test_reduction(path): res = symmetry_reduction(obj, **kw_of(g.get("args"))) except USER_ERRORS: return - gens = [{spy.Symbol(k): parse(v) for k, v in d["generator"].items()} - for d in obj["symmetries"] if d.get("generator") and d["type"] == "general"] + gens = [ + {spy.Symbol(k): parse(v) for k, v in d["generator"].items()} + for d in obj["symmetries"] + if d.get("generator") and d["type"] == "general" + ] # the curved blocks are reduced after the scalings are pinned - scal = {spy.Symbol(k): parse(v) for b in res["blocks"] if b["type"] == "scaling" and b["status"] == "reduced" - for k, v in (b.get("pins") or {}).items()} + scal = { + spy.Symbol(k): parse(v) + for b in res["blocks"] + if b["type"] == "scaling" and b["status"] == "reduced" + for k, v in (b.get("pins") or {}).items() + } gens = [{k: c.xreplace(scal) for k, c in xi.items() if k not in scal} for xi in gens] for b in res["blocks"]: assert b["status"] in ("reduced", "fixed", "invariant_only", "unresolved", "skipped") @@ -149,8 +168,13 @@ def test_reduction(path): real = {q for q, dom in (b.get("solved_domain") or {}).items() if dom == "real"} def own(e): - return e.xreplace({x: spy.Symbol(str(x), real=True) if str(x) in real else - spy.Symbol(str(x), positive=True) for x in e.free_symbols}) + return e.xreplace( + { + x: spy.Symbol(str(x), real=True) if str(x) in real else spy.Symbol(str(x), positive=True) + for x in e.free_symbols + } + ) + pins = {own(spy.Symbol(k)): own(parse(v)) for k, v in (b.get("pins") or {}).items()} for q, inv in (b.get("new_parameters") or {}).items(): back = own(parse(inv)).xreplace(pins) diff --git a/tests/test_monodromy.py b/tests/test_monodromy.py index 0da07aa..bc2264f 100644 --- a/tests/test_monodromy.py +++ b/tests/test_monodromy.py @@ -72,11 +72,12 @@ def test_the_orbit_polynomial_of_a_group_over_q_of_i_has_rational_coefficients() grp = [{k: k, x0: x0}, {k: spy.I * k, x0: x0}, {k: -k, x0: x0}, {k: -spy.I * k, x0: x0}] alpha, fs, _, others = generators(grp, [k, x0]) assert alpha == k and others == [] - assert {spy.expand(f) for f in fs} == {x0, -k ** 4} + assert {spy.expand(f) for f in fs} == {x0, -(k**4)} def test_the_paths_of_the_monodromy_stop_at_their_cap_with_the_cap_named(): from symident.detection import work + s = _series(si.Model({"x": "-k^4*x"}, {"y": "x"}, trafo={"x": "x0"})) meter = work.Meter("the monodromy", 0, "term products") info, _ = mono.propose(s, Fiber(s, [3], True), meter, target=4) diff --git a/tests/test_par.py b/tests/test_par.py index 05a9940..1214322 100644 --- a/tests/test_par.py +++ b/tests/test_par.py @@ -37,6 +37,7 @@ def fn(x): if x == 1: raise ValueError("bad item") return x + with state.switches(DEBUG="0"): assert process_map(fn, range(3), 1, on_error=lambda x: None) == [0, None, 2] with pytest.raises(ValueError): @@ -51,5 +52,6 @@ def fn(x): if x == 1: os._exit(1) return x + with pytest.raises(RuntimeError, match="died"): process_map(fn, range(4), 2) diff --git a/tests/test_petab.py b/tests/test_petab.py index a94479c..a30e783 100644 --- a/tests/test_petab.py +++ b/tests/test_petab.py @@ -54,8 +54,9 @@ def test_a_preequilibration_rests_and_a_later_period_switches_by_events(): m = v2("0009") assert m.equilibrate is True and m.inputs == ["k1_si_input"] assert "((3/10))+k1_si_input" in m.odes["A"] and m.odes["k1_si_input"] == "0" - assert m.events == [{"time": "0.0", "method": "replace", "cond": [0], "var": "k1_si_input", - "value": "((4/5)) - ((3/10))"}] + assert m.events == [ + {"time": "0.0", "method": "replace", "cond": [0], "var": "k1_si_input", "value": "((4/5)) - ((3/10))"} + ] assert m.reduce_cq is True and m.totals == {"total1": "A + B"} m = v2("0010") assert {"var": "B", "value": "1"}.items() <= next(e for e in m.events if e["var"] == "B").items() @@ -81,16 +82,20 @@ def _problem(tmp_path, build): libsbml.writeSBMLToFile(doc, str(tmp_path / "model.xml")) (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\tx\t1\n") (tmp_path / "measurements.tsv").write_text("observableId\texperimentId\ttime\tmeasurement\nobs\t\t1\t1\n") - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nk\tlog10\t0.1\t10\t1\t1\n") - (tmp_path / "p.yaml").write_text("format_version: 2.0.0\nparameter_files: [parameters.tsv]\n" - "model_files: {m: {language: sbml, location: model.xml}}\n" - "observable_files: [observables.tsv]\nmeasurement_files: [measurements.tsv]\n") + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue\testimate\nk\tlog10\t0.1\t10\t1\t1\n" + ) + (tmp_path / "p.yaml").write_text( + "format_version: 2.0.0\nparameter_files: [parameters.tsv]\n" + "model_files: {m: {language: sbml, location: model.xml}}\n" + "observable_files: [observables.tsv]\nmeasurement_files: [measurements.tsv]\n" + ) return si.read_petab(str(tmp_path / "p.yaml")) def _species(model, rule=None): import libsbml + c = model.createCompartment() c.setId("V"), c.setSize(2), c.setConstant(rule is None) x = model.createSpecies() @@ -122,6 +127,7 @@ def test_an_unsupported_feature_is_an_error(tmp_path): def algebraic(model): _species(model) model.createAlgebraicRule().setMath(libsbml.parseL3Formula("x - k")) + with pytest.raises(si.PEtabError, match="algebraic"): _problem(tmp_path, algebraic) @@ -134,8 +140,10 @@ def algebraic(model): "Lucarelli_CellSystems2018": [], "Weber_BMC2015": [], "Bachmann_MSB2011": [["init_EpoRJAK2"]], - "Raia_CancerResearch2011": [["CD274mRNA_production", "scaling_CD274mRNA"], - ["SOCS3_accumulation", "SOCS3mRNA_production", "scaling_SOCS3mRNA"]], + "Raia_CancerResearch2011": [ + ["CD274mRNA_production", "scaling_CD274mRNA"], + ["SOCS3_accumulation", "SOCS3mRNA_production", "scaling_SOCS3mRNA"], + ], } @@ -213,11 +221,13 @@ def build(model): p = model.createParameter() p.setId("lvl"), p.setValue(0), p.setConstant(True) model.getReaction(0).getKineticLaw().setMath(libsbml.parseL3Formula("piecewise(2, lvl > 0, 1)*k*x*V")) + _problem(tmp_path, build) (tmp_path / "conditions.tsv").write_text("conditionId\ttargetId\ttargetValue\nc0\tlvl\t0\nc1\tlvl\t1\n") (tmp_path / "experiments.tsv").write_text("experimentId\ttime\tconditionId\ne0\t0\tc0\ne1\t0\tc1\n") - (tmp_path / "measurements.tsv").write_text("observableId\texperimentId\ttime\tmeasurement\n" - "obs\te0\t1\t1\nobs\te1\t1\t1\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\texperimentId\ttime\tmeasurement\nobs\te0\t1\t1\nobs\te1\t1\t1\n" + ) y = (tmp_path / "p.yaml").read_text() (tmp_path / "p.yaml").write_text(y + "condition_files: [conditions.tsv]\nexperiment_files: [experiments.tsv]\n") m = si.read_petab(str(tmp_path / "p.yaml")) @@ -228,8 +238,9 @@ def _conditions(tmp_path, rows): """Two experiments e0 and e1 of the problem in `tmp_path`, with the condition table `rows`.""" (tmp_path / "conditions.tsv").write_text("conditionId\ttargetId\ttargetValue\n" + rows) (tmp_path / "experiments.tsv").write_text("experimentId\ttime\tconditionId\ne0\t0\tc0\ne1\t0\tc1\n") - (tmp_path / "measurements.tsv").write_text("observableId\texperimentId\ttime\tmeasurement\n" - "obs\te0\t1\t1\nobs\te1\t1\t1\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\texperimentId\ttime\tmeasurement\nobs\te0\t1\t1\nobs\te1\t1\t1\n" + ) y = (tmp_path / "p.yaml").read_text() (tmp_path / "p.yaml").write_text(y + "condition_files: [conditions.tsv]\nexperiment_files: [experiments.tsv]\n") return si.read_petab(str(tmp_path / "p.yaml")) @@ -248,6 +259,7 @@ def build(model): tr.setInitialValue(False), tr.setPersistent(True), tr.setMath(libsbml.parseL3Formula("time >= t_on")) a = e.createEventAssignment() a.setVariable("x"), a.setMath(libsbml.parseL3Formula("5")) + _problem(tmp_path, build) m = _conditions(tmp_path, "c0\tt_on\t1\nc1\tk\tk\n") assert [(e["time"], e["cond"]) for e in m.events] == [("(1)", [0]), ("(2)", [1])] @@ -262,11 +274,14 @@ def build(model): p = model.createParameter() p.setId(name), p.setValue(1), p.setConstant(True) model.getReaction(0).getKineticLaw().setMath(libsbml.parseL3Formula("_k*X_k*k*x*V")) + _problem(tmp_path, build) (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\t_s*x\t1\n") - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nk\tlog10\t0.1\t10\t1\t1\n_s\tlog10\t0.1\t10\t1\t1\n" - "_k\tlog10\t0.1\t10\t1\t1\nX_k\tlin\t0\t10\t3\t0\n") + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" + "\testimate\nk\tlog10\t0.1\t10\t1\t1\n_s\tlog10\t0.1\t10\t1\t1\n" + "_k\tlog10\t0.1\t10\t1\t1\nX_k\tlin\t0\t10\t3\t0\n" + ) m = _conditions(tmp_path, "c0\t_k\t_s\nc1\tpi\t2\n") assert m.petab["renamed"] == {"_k": "X_k_", "pi": "pi_", "_s": "X_s"} assert m.observables == [{"obs": "X_s*x"}] * 2 and sorted(m.petab["estimated"]) == ["X_k_", "X_s", "k"] @@ -276,12 +291,14 @@ def build(model): @pytest.mark.parametrize("name", sorted(BENCH)) def test_the_totals_of_a_benchmark_model_are_conserved_exactly(name): from symident.detection.cq import check_conserved + m = bench(name) check_conserved(dict(m.totals or {}), m.odes) def test_a_table_with_a_byte_order_mark_keeps_the_name_of_the_first_column(tmp_path): from symident.petab import _table + p = tmp_path / "conditions.tsv" p.write_bytes("conditionId\tk\nc1\t2\n".encode()) assert _table(p) == [{"conditionId": "c1", "k": "2"}] @@ -310,13 +327,18 @@ def test_a_parameter_named_by_an_initial_assignment_takes_the_value_of_the_condi libsbml.writeSBMLToFile(doc, str(tmp_path / "model.xml")) (tmp_path / "conditions.tsv").write_text("conditionId\tks\nc1\t\nc2\t0\n") (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\tx\t1\n") - (tmp_path / "measurements.tsv").write_text("observableId\tsimulationConditionId\ttime\tmeasurement\n" - "obs\tc1\t1\t1\nobs\tc2\t1\t1\n") - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nk\tlog10\t0.1\t10\t1\t1\nks\tlin\t0\t10\t2\t0\n") - (tmp_path / "p.yaml").write_text("format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" - "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" - " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\tsimulationConditionId\ttime\tmeasurement\nobs\tc1\t1\t1\nobs\tc2\t1\t1\n" + ) + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" + "\testimate\nk\tlog10\t0.1\t10\t1\t1\nks\tlin\t0\t10\t2\t0\n" + ) + (tmp_path / "p.yaml").write_text( + "format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" + "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" + " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n" + ) m = si.read_petab(str(tmp_path / "p.yaml")) vals = [str(t.get("m")).strip("()") for t in m.trafo] assert vals == ["2", "0"] and "ks" not in str(m.odes) + str(m.trafo) @@ -347,13 +369,18 @@ def test_a_parameter_that_no_period_changes_leaves_no_input(tmp_path, xi0): libsbml.writeSBMLToFile(doc, str(tmp_path / "model.xml")) (tmp_path / "conditions.tsv").write_text("conditionId\tks\tinh\npre\t1\t0\nsim\t2\t0\n") (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\tx + xi\t1\n") - (tmp_path / "measurements.tsv").write_text("observableId\tpreequilibrationConditionId\tsimulationConditionId" - "\ttime\tmeasurement\nobs\tpre\tsim\t1\t1\n") - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nk\tlog10\t0.1\t10\t1\t1\nkb\tlog10\t0.1\t10\t1\t1\n") - (tmp_path / "p.yaml").write_text("format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" - "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" - " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\tpreequilibrationConditionId\tsimulationConditionId\ttime\tmeasurement\nobs\tpre\tsim\t1\t1\n" + ) + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" + "\testimate\nk\tlog10\t0.1\t10\t1\t1\nkb\tlog10\t0.1\t10\t1\t1\n" + ) + (tmp_path / "p.yaml").write_text( + "format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" + "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" + " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n" + ) m = si.read_petab(str(tmp_path / "p.yaml")) assert "ks_si_input" in m.inputs and "inh_si_input" not in m.inputs assert "inh_si_input" not in str(m.odes) + str(m.events) @@ -385,13 +412,18 @@ def _rest_problem(tmp_path, times, conditions="conditionId\tks\nc1\t1\nc2\t2\n") libsbml.writeSBMLToFile(doc, str(tmp_path / "model.xml")) (tmp_path / "conditions.tsv").write_text(conditions) (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\tx\t1\n") - (tmp_path / "measurements.tsv").write_text("observableId\tsimulationConditionId\ttime\tmeasurement\n" + - "".join(f"obs\t{c}\t{t}\t1\n" for c, t in times)) - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nk\tlog10\t0.1\t10\t1\t1\nkp\tlog10\t0.1\t10\t1\t1\n") - (tmp_path / "p.yaml").write_text("format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" - "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" - " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\tsimulationConditionId\ttime\tmeasurement\n" + "".join(f"obs\t{c}\t{t}\t1\n" for c, t in times) + ) + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" + "\testimate\nk\tlog10\t0.1\t10\t1\t1\nkp\tlog10\t0.1\t10\t1\t1\n" + ) + (tmp_path / "p.yaml").write_text( + "format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" + "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" + " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n" + ) return si.read_petab(str(tmp_path / "p.yaml")) @@ -405,8 +437,7 @@ def test_an_experiment_measured_only_at_inf_is_a_readout_at_rest(tmp_path): assert [sorted(s.support) for s in r.symmetries] == [["k", "kp"]] -@pytest.mark.parametrize("times", [[("c1", "1"), ("c1", "inf"), ("c2", "1")], - [("c1", "inf"), ("c2", "2")]]) +@pytest.mark.parametrize("times", [[("c1", "1"), ("c1", "inf"), ("c2", "1")], [("c1", "inf"), ("c2", "2")]]) def test_an_experiment_with_a_finite_time_keeps_the_trajectory(tmp_path, times): # an experiment with a finite measurement time is a trajectory; with one of them in the problem, an # experiment measured only at inf is a trajectory as well, since every condition starts alike @@ -443,13 +474,18 @@ def test_a_readout_at_rest_starts_from_the_values_of_its_condition(tmp_path): libsbml.writeSBMLToFile(doc, str(tmp_path / "model.xml")) (tmp_path / "conditions.tsv").write_text("conditionId\tA\nc1\t3\nc2\t5\n") (tmp_path / "observables.tsv").write_text("observableId\tobservableFormula\tnoiseFormula\nobs\tA\t1\n") - (tmp_path / "measurements.tsv").write_text("observableId\tsimulationConditionId\ttime\tmeasurement\n" - "obs\tc1\tinf\t1\nobs\tc2\tinf\t1\n") - (tmp_path / "parameters.tsv").write_text("parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" - "\testimate\nkf\tlog10\t0.1\t10\t1\t1\nkb\tlog10\t0.1\t10\t1\t1\n") - (tmp_path / "p.yaml").write_text("format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" - "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" - " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n") + (tmp_path / "measurements.tsv").write_text( + "observableId\tsimulationConditionId\ttime\tmeasurement\nobs\tc1\tinf\t1\nobs\tc2\tinf\t1\n" + ) + (tmp_path / "parameters.tsv").write_text( + "parameterId\tparameterScale\tlowerBound\tupperBound\tnominalValue" + "\testimate\nkf\tlog10\t0.1\t10\t1\t1\nkb\tlog10\t0.1\t10\t1\t1\n" + ) + (tmp_path / "p.yaml").write_text( + "format_version: 1\nparameter_file: parameters.tsv\nproblems:\n" + "- condition_files: [conditions.tsv]\n measurement_files: [measurements.tsv]\n" + " observable_files: [observables.tsv]\n sbml_files: [model.xml]\n" + ) m = si.read_petab(str(tmp_path / "p.yaml")) assert m.equilibrate is True and not m.events and m.totals tot = next(iter(m.totals)) diff --git a/tests/test_projections.py b/tests/test_projections.py index f1908c5..16480e5 100644 --- a/tests/test_projections.py +++ b/tests/test_projections.py @@ -29,6 +29,7 @@ def _captured(model, monkeypatch): def record(*args, **kw): got.append((args, kw)) return {"exact": False, "why": "off", "generators": [], "seconds": 0.0} + with monkeypatch.context() as m: m.setattr(fieldproof, "exact_fiber", record) si.detect(model, mode="global", cores=1) @@ -36,15 +37,24 @@ def record(*args, **kw): return got[0] -def _search_by_projections(model, monkeypatch, cap=10 ** 10): +def _search_by_projections(model, monkeypatch, cap=10**10): """The exact count in this process with the dense relations off: only projections give relations.""" args, kw = _captured(model, monkeypatch) series, orders, grp, syms, inputs = args[:5] monkeypatch.setattr(fieldproof, "io_functions", lambda *a, **k: iter(())) monkeypatch.setattr(fieldproof, "state_relation", lambda *a, **k: None) fieldproof._REL.clear() - return fieldproof._exact_fiber(series, list(orders), grp, list(syms), cap, list(inputs), random.Random(1), - list(kw.get("known", args[5] if len(args) > 5 else ())), []) + return fieldproof._exact_fiber( + series, + list(orders), + grp, + list(syms), + cap, + list(inputs), + random.Random(1), + list(kw.get("known", args[5] if len(args) > 5 else ())), + [], + ) def test_rational_reconstruction_of_one_variable_finds_unbalanced_degrees(): @@ -55,6 +65,7 @@ def test_rational_reconstruction_of_one_variable_finds_unbalanced_degrees(): def ev(c, t): return sum(x * pow(t, k, p) for k, x in enumerate(c)) % p + ts = list(range(1, 15)) got = ioproj.ratrec1(ts, [ev(N, t) * pow(ev(D, t), -1, p) % p for t in ts], p) assert got is not None and got[1] == D and len(got[0]) == len(N) @@ -68,6 +79,7 @@ def test_sparse_numerators_find_the_terms_of_a_polynomial(): def f(x, p): return np.array([sum(c * math.prod(pow(xi, e, p) for xi, e in zip(x, m)) for m, c in terms.items()) % p]) + co = ioproj.Coefficients(None, 4, random.Random(3), math.inf) got = co._sparse(f, np.array([1]), [(0, 0, 0, 0)], [ioproj._box(4, 4, [2, 2, 2, 2])], q) assert got == [{m: c % q for m, c in terms.items()}] @@ -87,11 +99,11 @@ def test_a_projection_is_proven_and_a_wrong_coefficient_fails(monkeypatch): h = fieldproof._profiles(rel, rng)[0] assert h == [2] pr = ioproj.Projection.output(rel, h, 0, pos, rng) - S = pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10 ** 10) + S = pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10**10) # x'' + 2 a x x' + c x' + a c x^2 assert sorted(S) == sorted([(0, 0, 1), (1, 1, 0), (0, 1, 0), (2, 0, 0)]) assert ioproj.series_rank(rel, pr, S, syms, rng, p) == len(S) - 1 - co = ioproj.Coefficients(pr, len(idx), rng, work.ticks() + 10 ** 10) + co = ioproj.Coefficients(pr, len(idx), rng, work.ticks() + 10**10) assert co.run() assert ioproj.identity(rel, pr, co, pos) k = next(iter(co.nums[0])) @@ -122,7 +134,7 @@ def test_the_start_of_an_unobserved_state_has_a_state_projection(monkeypatch): series, syms = args[0], args[3] fieldproof._REL.clear() z0 = next(s for s in syms if str(s) == "z0") - got = fieldproof.state_projection(series, syms, z0, random.Random(1), work.ticks() + 10 ** 10) + got = fieldproof.state_projection(series, syms, z0, random.Random(1), work.ticks() + 10**10) # z = x' + a x: linear in z, with a coefficient that reads a assert got is not None and {str(s) for s in got["reads"]} == {"a"} and got["terms"] == 3 @@ -134,13 +146,14 @@ def test_a_start_quadratic_below_the_profile_has_a_state_projection_with_the_nex series, syms = args[0], args[3] fieldproof._REL.clear() z0 = next(s for s in syms if str(s) == "z0") - got = fieldproof.state_projection(series, syms, z0, random.Random(1), work.ticks() + 10 ** 10) + got = fieldproof.state_projection(series, syms, z0, random.Random(1), work.ticks() + 10**10) assert got is not None and {str(s) for s in got["reads"]} == {"a", "b"} and got["terms"] == 3 @pytest.mark.skipif(not _has_msolve(), reason="needs msolve") def test_the_exact_output_coefficients_are_the_taylor_coefficients_of_a_rational_model(monkeypatch): import sympy as spy + m = si.Model({"x": "-a*x/(k + x) + z", "z": "-c*z"}, {"y": "x/(1 + z)"}, trafo={"x": "x0", "z": "1"}) args, _ = _captured(m, monkeypatch) series, orders = args[0], args[1] @@ -151,6 +164,7 @@ def test_the_exact_output_coefficients_are_the_taylor_coefficients_of_a_rational def expr(q): den = spy.prod([F.fac[k].as_expr() ** e for k, e in q[1].items()]) return (q[0].as_expr() / den).xreplace(t) + a, k, c, x, z, x0 = (spy.Symbol(n) for n in ("a", "k", "c", "x", "z", "x0")) f = {x: -a * x / (k + x) + z, z: -c * z} d = x / (1 + z) @@ -182,14 +196,14 @@ def test_counts_of_points_bound_the_newton_polytope_of_a_projection(monkeypatch) pos = [rel.names.index(str(syms[k])) for k in idx] pr = ioproj.Projection.output(rel, [2], 0, pos, rng) theta = [rng.randrange(1, p) for _ in idx] - mons = pr.polytope(theta, p, work.ticks() + 10 ** 10) + mons = pr.polytope(theta, p, work.ticks() + 10**10) # x'' + 2 a x x' + c x' + a c x^2: degrees 2, 1, 1 in x, x', x'', total 2, weighted by order 3 assert pr.newton[(1, 1, 1)] == (1, 2) assert [pr.newton[ioproj._unit(3, v)][1] for v in range(3)] == [2, 1, 1] assert pr.newton[(1, 2, 3)][1] == 3 assert {(0, 0, 1), (1, 1, 0), (0, 1, 0), (2, 0, 0)} <= set(mons) # with boxes too small for the projection the support comes from the polytope - S = pr.search(theta, p, work.ticks() + 10 ** 10, cap=4) + S = pr.search(theta, p, work.ticks() + 10**10, cap=4) assert sorted(S) == sorted([(0, 0, 1), (1, 1, 0), (0, 1, 0), (2, 0, 0)]) @@ -207,7 +221,7 @@ def test_a_projection_of_higher_degree_in_the_start_is_not_searched_for_a_linear k = next(j for j, x in enumerate(rel.X) if str(x) == "z") pr = ioproj.Projection.state(rel, [2], k, pos, rng) # z^2 = x' + a x: degree two in z, so no relation linear in z below the profile - assert pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10 ** 10, cap=4, top_degree=1) is None + assert pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10**10, cap=4, top_degree=1) is None assert pr.newton[ioproj._unit(pr.nb, pr.top)][1] == 2 @@ -220,7 +234,7 @@ def test_relations_skip_derivatives_of_derivatives_above_the_term_limit(monkeypa J = ioproj.jets_of(rel) monkeypatch.setattr(ioproj, "_JET", 4) z0 = next(s for s in syms if str(s) == "z0") - fieldproof.state_relation(series, syms, z0, random.Random(1), work.ticks() + 10 ** 9, cap=40) + fieldproof.state_relation(series, syms, z0, random.Random(1), work.ticks() + 10**9, cap=40) # no derivative is taken of one with more than four terms lst = J._obs[(0, str(rel.y[0]))][0] assert all(len(N) <= 4 for N, _, _ in lst[:-1]) @@ -241,7 +255,7 @@ def test_no_projection_reads_the_derivative_of_one_above_the_term_limit(monkeypa @pytest.mark.skipif(not _has_msolve(), reason="needs msolve") def test_coefficients_above_the_height_of_the_engine_primes_are_rebuilt(monkeypatch): # a constant of 200 bits in the coefficients: beyond the rational reconstruction of the engine primes - K = 2 ** 200 + 235 + K = 2**200 + 235 m = si.Model({"x": "-a*x^2 + z", "z": f"-{K}*c*z"}, {"y": "x"}, trafo={"x": "x0", "z": "1"}) args, _ = _captured(m, monkeypatch) series, syms = args[0], args[3] @@ -252,14 +266,14 @@ def test_coefficients_above_the_height_of_the_engine_primes_are_rebuilt(monkeypa idx = [k for k, s in enumerate(syms) if s in set(series.params)] pos = [rel.names.index(str(syms[k])) for k in idx] pr = ioproj.Projection.output(rel, [2], 0, pos, rng) - assert len(pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10 ** 10)) == 4 - co = ioproj.Coefficients(pr, len(idx), rng, work.ticks() + 10 ** 10) + assert len(pr.search([rng.randrange(1, p) for _ in idx], p, work.ticks() + 10**10)) == 4 + co = ioproj.Coefficients(pr, len(idx), rng, work.ticks() + 10**10) assert co.run() assert ioproj.identity(rel, pr, co, pos) assert any(abs(c.numerator) >= K for d in co.nums for c in d.values()) -def _search_by_elimination(model, monkeypatch, cap=10 ** 10): +def _search_by_elimination(model, monkeypatch, cap=10**10): """The exact count in this process with the dense relations, the projections and the relations of the starts off: only the elimination gives relations and starts.""" args, kw = _captured(model, monkeypatch) @@ -269,8 +283,17 @@ def _search_by_elimination(model, monkeypatch, cap=10 ** 10): monkeypatch.setattr(fieldproof, "state_relation", lambda *a, **k: None) monkeypatch.setattr(fieldproof, "state_projection", lambda *a, **k: None) fieldproof._REL.clear() - return fieldproof._exact_fiber(series, list(orders), grp, list(syms), cap, list(inputs), random.Random(1), - list(kw.get("known", args[5] if len(args) > 5 else ())), []) + return fieldproof._exact_fiber( + series, + list(orders), + grp, + list(syms), + cap, + list(inputs), + random.Random(1), + list(kw.get("known", args[5] if len(args) > 5 else ())), + [], + ) def _saturable(): @@ -281,6 +304,7 @@ def test_the_elimination_gives_the_relation_of_the_observable(monkeypatch): import sympy as spy from symident.detection import elim + args, _ = _captured(_saturable(), monkeypatch) series, syms = args[0], args[3] fieldproof._REL.clear() @@ -297,6 +321,7 @@ def test_the_elimination_gives_the_relation_of_the_observable(monkeypatch): def test_the_elimination_drops_a_factor_nonzero_along_a_trajectory(monkeypatch): from symident.detection import elim + args, _ = _captured(_saturable(), monkeypatch) series, syms = args[0], args[3] fieldproof._REL.clear() @@ -314,8 +339,9 @@ def test_the_elimination_drops_a_factor_nonzero_along_a_trajectory(monkeypatch): def test_the_exact_count_holds_with_a_relation_by_elimination(monkeypatch): out = _search_by_elimination(_saturable(), monkeypatch) assert out["exact"] is True - assert any(r.startswith("elimination of observable 0") and r.endswith("coefficients proven") - for r in out["relations"]) + assert any( + r.startswith("elimination of observable 0") and r.endswith("coefficients proven") for r in out["relations"] + ) # the start of the unobserved state from the equation of degree one in it where it is eliminated assert "x2" in {g["function"] for g in out["generators"] if g["numerator"] == "elimination"} @@ -324,6 +350,7 @@ def test_the_first_subresultant_gives_the_common_root(): import flint from symident.detection import elim + ctx = flint.fmpz_mpoly_ctx.get(("v", "a", "b", "c"), "lex") v, a, b, c = ctx.gens() f, g = (v - a) * (v - b) * (v + 1), (v - a) * (v - c) @@ -334,6 +361,7 @@ def test_the_first_subresultant_gives_the_common_root(): def test_the_elimination_stops_at_its_cap_on_terms(monkeypatch): from symident.detection import elim + args, _ = _captured(_saturable(), monkeypatch) series, syms = args[0], args[3] fieldproof._REL.clear() @@ -347,13 +375,16 @@ def test_the_relation_by_elimination_names_its_cap_in_the_log(monkeypatch): with work.caps(elimination_terms=2): out = _search_by_elimination(_saturable(), monkeypatch) assert out["exact"] is False - assert any(r.startswith("elimination: a polynomial of") and r.endswith("past the cap elimination_terms of 2") - for r in out["relations"]) + assert any( + r.startswith("elimination: a polynomial of") and r.endswith("past the cap elimination_terms of 2") + for r in out["relations"] + ) @pytest.mark.skipif(not _has_msolve(), reason="needs msolve") def test_the_exact_search_ends_at_its_cap_on_entries_with_the_cap_named(monkeypatch): out = _search_by_elimination(_saturable(), monkeypatch, cap=0) assert out["exact"] is False - assert out["why"].endswith("before the end of the search: the search reached the cap search_entries of 0 " - "entries of the matrices reduced") + assert out["why"].endswith( + "before the end of the search: the search reached the cap search_entries of 0 entries of the matrices reduced" + ) diff --git a/tests/test_reconstruct.py b/tests/test_reconstruct.py index 3c97506..3e4ac54 100644 --- a/tests/test_reconstruct.py +++ b/tests/test_reconstruct.py @@ -11,17 +11,21 @@ def core(two=False, mode="equilibrate", basal=True): """A receptor inhibited by S (and T), each made from a transcript and, with `basal`, from a basal source; L is dosed at 0 and again at 24.""" inh = "(1 + kinh*S)" + ("*(1 + kinh3*T)" if two else "") - odes = {"L": f"-Bind*L*Rec/{inh}", - "Rec": f"prodRec - degRec*Rec - degRecS*Rec*S - Bind*L*Rec/{inh}", - "A": f"Bind*L*Rec/{inh} - degA*A - degAS*A*S", - "M": "synthM*A - hlM*M", - "S": "synthS*M + bS - dS*S" if basal else "synthS*M - dS*S"} + odes = { + "L": f"-Bind*L*Rec/{inh}", + "Rec": f"prodRec - degRec*Rec - degRecS*Rec*S - Bind*L*Rec/{inh}", + "A": f"Bind*L*Rec/{inh} - degA*A - degAS*A*S", + "M": "synthM*A - hlM*M", + "S": "synthS*M + bS - dS*S" if basal else "synthS*M - dS*S", + } obs = {"y1": "s1*A", "y2": "M"} if two: odes.update(N="synthN*A - hlN*N", T="synthT*N + bT - dT*T") obs["y3"] = "N" - ev = [{"var": "L", "time": 0, "value": "d0", "method": "add"}, - {"var": "L", "time": 24, "value": "d1", "method": "add"}] + ev = [ + {"var": "L", "time": 0, "value": "d0", "method": "add"}, + {"var": "L", "time": 24, "value": "d1", "method": "add"}, + ] cond = {"rows": ["a", "b", "c"], "cols": {"d0": [1, 2, 1], "d1": [0, 1, 2]}} if mode == "equilibrate": return si.Model(odes, obs, events=ev, conditions=cond), {"equilibrate": True} @@ -71,20 +75,26 @@ def test_inhibitor_without_basal_source_is_a_scaling(mode): def test_an_entry_past_degree_cap_is_fitted_at_the_degree_found(): # the entries of these directions have a degree above the default degree_cap - m = si.Model({"x1": "v1 - k*x1/(K + x1)", "x2": "v2 - k*x2/(K + x2)"}, {"y": "s*(x1 + x2)"}, - conditions={"rows": ["c1", "c2"], "cols": {"k": ["k1", "k2"]}}) + m = si.Model( + {"x1": "v1 - k*x1/(K + x1)", "x2": "v2 - k*x2/(K + x2)"}, + {"y": "s*(x1 + x2)"}, + conditions={"rows": ["c1", "c2"], "cols": {"k": ["k1", "k2"]}}, + ) r = si.detect(m, reconstruct=True, equilibrate=True, cores=2) assert all(s.explicit for s in r.symmetries) and len(r.symmetries) == r.dim - r.rank == 4 - low = si.detect(m, reconstruct=True, equilibrate=True, cores=2, - control=si.reconst_control(degree_cap_max=4, homotopy=False)) + low = si.detect( + m, reconstruct=True, equilibrate=True, cores=2, control=si.reconst_control(degree_cap_max=4, homotopy=False) + ) assert not all(s.explicit for s in low.symmetries) @pytest.mark.parametrize("reconstruct", [False, True]) def test_every_direction_is_reported_once(reconstruct): - models = [({"A": "-k1*A + k2*B", "B": "k1*A - k2*B"}, {"y": "s*A"}), - ({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, {"y": "s*x2"}), - ({"x": "v*u^n/(K^n + u^n) - d*x", "u": "-e*u"}, {"y": "x"})] + models = [ + ({"A": "-k1*A + k2*B", "B": "k1*A - k2*B"}, {"y": "s*A"}), + ({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, {"y": "s*x2"}), + ({"x": "v*u^n/(K^n + u^n) - d*x", "u": "-e*u"}, {"y": "x"}), + ] for f, g in models: r = si.detect(si.Model(f, g), reconstruct=reconstruct) assert len(r.symmetries) == r.dim - r.rank @@ -95,13 +105,30 @@ def test_every_direction_is_reported_once(reconstruct): def test_a_constant_entry_lifts_from_the_primes_where_the_base_point_has_a_kernel(): from symident.detection.interp import interpolate_direction from symident.gfp import PRIMES + point0 = [3, 5] + # a resting state without a root modulo a prime leaves no kernel at that prime def kcall(pt, p, nt): if p == PRIMES[2] and list(pt) == point0: return {"ok": False} return {"ok": True, "R": [1, 1], "pivots": [0], "rank": 1, "dim": 2} + ref = kcall(point0, PRIMES[0], 1) - d = interpolate_direction(1, ref, [0], ["a", "b"], [0, 1], ["a", "b"], 2, point0, None, 0, 1, kcall, - rel_probe=[{"rp": ref, "zvals": None}] * 2, ctrl={}) + d = interpolate_direction( + 1, + ref, + [0], + ["a", "b"], + [0, 1], + ["a", "b"], + 2, + point0, + None, + 0, + 1, + kcall, + rel_probe=[{"rp": ref, "zvals": None}] * 2, + ctrl={}, + ) assert d["entry"].get("closed_form") and d["entry"]["vector"] == {"a": "-1", "b": "1"} diff --git a/tests/test_reduce.py b/tests/test_reduce.py index 773ec71..60ce100 100644 --- a/tests/test_reduce.py +++ b/tests/test_reduce.py @@ -15,8 +15,16 @@ import symident as si from symident import report -_FUNS = {"exp": math.exp, "log": math.log, "sqrt": math.sqrt, "atan": math.atan, "abs": abs, - "exp10": lambda x: 10.0 ** x, "log10": math.log10, "log1p": math.log1p} +_FUNS = { + "exp": math.exp, + "log": math.log, + "sqrt": math.sqrt, + "atan": math.atan, + "abs": abs, + "exp10": lambda x: 10.0**x, + "log10": math.log10, + "log1p": math.log1p, +} _IDENT = re.compile(r"[A-Za-z_.][A-Za-z0-9_.]*") @@ -44,8 +52,13 @@ def mkdir(gen, type="polynomial", weights=None): def mkobj(dirs, coords): - return {"identifiable": False, "rank": 1, "dim": len(coords), "symmetries": dirs, - "info": {"engine": "modular", "settings": {}, "coordinates": list(coords)}} + return { + "identifiable": False, + "rank": 1, + "dim": len(coords), + "symmetries": dirs, + "info": {"engine": "modular", "settings": {}, "coordinates": list(coords)}, + } def network(*reactions): @@ -70,8 +83,7 @@ def ev(expr, pt): def variables(expr): - return [m.group(0) for m in _IDENT.finditer(str(expr)) - if not str(expr)[m.end():].lstrip().startswith("(")] + return [m.group(0) for m in _IDENT.finditer(str(expr)) if not str(expr)[m.end() :].lstrip().startswith("(")] def expr_equal(a, b): @@ -91,8 +103,11 @@ def lie_at(gen, inv, pt, eps=1e-7): def replace_symbols(expr, table): - return re.sub(r"(? 0 @@ -401,14 +455,14 @@ def test_section_from_product_of_two_summand_balances(): assert "certified positive" in curved["gauge_note"] # the pinned scaling coordinate is out of the ansatz and of the block report assert not any("ktx" in s for s in curved["invariants"] + (curved.get("section") or [])) - z = {nm: ev(e, {"q_1": 2.3, "q_2": 0.7, "pP": 1.4, "s": 0.9, "dm": 1.1, "m": 0.5}) - for nm, e in r.trafo.items()} + z = {nm: ev(e, {"q_1": 2.3, "q_2": 0.7, "pP": 1.4, "s": 0.9, "dm": 1.1, "m": 0.5}) for nm, e in r.trafo.items()} assert all(z[k] > 0 for k in ("P", "k_p", "k_d")) assert identifiable(f, g, trafo=r.trafo) def test_section_candidates_put_summand_balances_before_monomial_pairs(): from symident.reduction.sections import section_cands + cands = section_cands(["x", "y", "z"], [["F*x", "y", "x*z"]]) first_pair = cands.index(["x", "y"]) assert cands[:3] == [["x", "1"], ["y", "1"], ["z", "1"]] @@ -426,8 +480,7 @@ def test_balances_through_fixed_names_push_no_coordinate_section_out(): def test_invariants_verified_against_other_blocks(): - f = {"P1": "-k1*P1 + k2*pP1", "pP1": "k1*P1 - k2*pP1", - "P2": "-k3*P2 + k4*pP2", "pP2": "k3*P2 - k4*pP2"} + f = {"P1": "-k1*P1 + k2*pP1", "pP1": "k1*P1 - k2*pP1", "P2": "-k3*P2 + k4*pP2", "pP2": "k3*P2 - k4*pP2"} g = {"y1": "pP1", "y2": "pP2"} r = red(det(f, g, reconstruct=True)) curved = blocks_of(r, "curved") @@ -715,8 +768,9 @@ def test_face_section_switches_leaks_off(): assert any("face section" in c for c in b["certificates"]) # the face is a zero set every orbit reaches zb = blocks_of(red(res, zero_limits=True), "curved")[0] - assert any(row["verdict"] == "yes" and row["coordinates"] == ", ".join(sorted(zeros)) - for row in zb["zero_compatibility"]) + assert any( + row["verdict"] == "yes" and row["coordinates"] == ", ".join(sorted(zeros)) for row in zb["zero_compatibility"] + ) tr2 = {**tr, **{k: v for k, v in r.trafo.items() if k not in tr}} assert identifiable(f, {"y": "x1"}, trafo=tr2) # each rate the face keeps becomes a fresh q_ @@ -751,8 +805,10 @@ def test_translation_group_searched_in_sum(): assert not r.remaining cb = blocks_of(r, "curved")[0] assert any("translation-group" in c for c in cb["certificates"]) - assert any(expr_equal(iv, "kdg/(Km + R1 + R2) + ksec") - or expr_equal(iv, "(Km + R1 + R2)/(kdg + ksec*(Km + R1 + R2))") for iv in cb["invariants"]) + assert any( + expr_equal(iv, "kdg/(Km + R1 + R2) + ksec") or expr_equal(iv, "(Km + R1 + R2)/(kdg + ksec*(Km + R1 + R2))") + for iv in cb["invariants"] + ) pt = {"Km": 0.7, "kdg": 2.3, "ksec": 1.9, "ktl": 0.31, "R1": 1.7, "R2": 0.45} for iv in cb["invariants"]: assert abs(lie_at(g1, iv, pt)) < 1e-4 @@ -764,8 +820,7 @@ def test_unmoved_monomial_searched_as_one_symbol(): W = "R1*R2*R3" g1 = {"Km": f"Km + {W}", "kdg": "kdg"} g2 = {"Km": f"ksec*(Km + {W})^2", "ksec": f"{W}*kdg*ksec", "ktl": f"-{W}*kdg*ktl"} - obj = mkobj([mkdir(g1, "general"), mkdir(g2, "general")], - ["Km", "kdg", "ksec", "ktl", "R1", "R2", "R3"]) + obj = mkobj([mkdir(g1, "general"), mkdir(g2, "general")], ["Km", "kdg", "ksec", "ktl", "R1", "R2", "R3"]) r = red(obj) assert not r.remaining cb = blocks_of(r, "curved")[0] @@ -783,12 +838,14 @@ def test_section_search_stops_at_its_work_cap(): pos = ["c", "k0", "kd", "w", "b", "x"] res = det(f, {"y": "x"}, gauge=None, reconstruct=True, positive=pos) r = red(res, positive=pos, work_cap=0) - assert any(b["status"] == "invariant_only" and "work_cap" in (b.get("reason") or "") - for b in blocks_of(r, "curved")) + assert any( + b["status"] == "invariant_only" and "work_cap" in (b.get("reason") or "") for b in blocks_of(r, "curved") + ) def test_square_root_of_a_perfect_square_is_taken(): from symident.reduction.core import _tidy_root + assert _tidy_root("sqrt(16*q_2^2 + 8*q_2*q_3 + q_3^2)") == "4*q_2 + q_3" assert _tidy_root("sqrt(4*kb2 + q_1^2)") == "sqrt(4*kb2 + q_1^2)" @@ -800,18 +857,23 @@ def test_partial_chart_is_named_in_the_verdict(): def test_the_declared_positive_names_of_the_detection_need_not_be_coordinates(): - res = si.detect(si.Model({"x": "-k*f*x"}, {"y": "s*x"}, fixed=["f"]), positive=["x", "k", "s", "f"], - reconstruct=True) + res = si.detect( + si.Model({"x": "-k*f*x"}, {"y": "s*x"}, fixed=["f"]), positive=["x", "k", "s", "f"], reconstruct=True + ) with warnings.catch_warnings(): warnings.filterwarnings("error", message="no effect") res.reduce() def test_labels_partition_the_directions(): - rx = {"species": ["A", "B", "C"], "stoichiometry": [[1, -1, 0], [0, -1, 1], [0, 1, -1]], - "rates": ["k1*B", "k2*B", "k3*C"]} - red = si.detect(si.Model(reactions=rx, observables={"y": "B"}), equilibrate=True, reduce_cq=True, - reconstruct=True).reduce() + rx = { + "species": ["A", "B", "C"], + "stoichiometry": [[1, -1, 0], [0, -1, 1], [0, 1, -1]], + "rates": ["k1*B", "k2*B", "k3*C"], + } + red = si.detect( + si.Model(reactions=rx, observables={"y": "B"}), equilibrate=True, reduce_cq=True, reconstruct=True + ).reduce() labels = red.removed + red.remaining assert len(labels) == len(set(labels)) == 3 assert red.remaining == [] @@ -822,18 +884,31 @@ def test_dependent_scaling_is_named_not_reduced(): def mk(g, w): return {"type": "scaling", "generator": g, "weights": w, "support": list(g), "explicit": True} - obj = {"identifiable": False, "rank": 0, "dim": 2, - "info": {"engine": "modular", "settings": {}, "coordinates": ["k1", "k2"]}, - "symmetries": [mk({"k1": "k1"}, {"k1": "1"}), mk({"k2": "k2"}, {"k2": "1"}), - mk({"k1": "k1", "k2": "k2"}, {"k1": "1", "k2": "1"})]} + + obj = { + "identifiable": False, + "rank": 0, + "dim": 2, + "info": {"engine": "modular", "settings": {}, "coordinates": ["k1", "k2"]}, + "symmetries": [ + mk({"k1": "k1"}, {"k1": "1"}), + mk({"k2": "k2"}, {"k2": "1"}), + mk({"k1": "k1", "k2": "k2"}, {"k1": "1", "k2": "1"}), + ], + } r = symmetry_reduction(obj) assert (r["removed"], r["remaining"], r["dependent"]) == (["X₁", "X₂"], [], ["X₃"]) def test_alternative_charts_are_valid_and_ranked(): from symident.reduction.core import _chart_valid - m = si.Model({"x": "kin*u - (k1 - k2)*x"}, {"y": "s*x"}, trafo={"x": "0"}, - conditions={"rows": ["a", "b"], "cols": {"u": [1, 3]}}) + + m = si.Model( + {"x": "kin*u - (k1 - k2)*x"}, + {"y": "s*x"}, + trafo={"x": "0"}, + conditions={"rows": ["a", "b"], "cols": {"u": [1, 3]}}, + ) det = si.detect(m, reconstruct=True) red = det.reduce(alternatives=True) assert _chart_valid(red._raw, det.dim) and red.alternatives @@ -849,6 +924,7 @@ def test_an_error_in_the_chart_is_raised_not_hidden(monkeypatch): def broken(*a, **k): raise KeyError("broken chart") + res = det({"x": "-k*x"}, {"y": "s*x"}, reconstruct=True) monkeypatch.setattr(core, "red_coordinates", broken) with pytest.raises(KeyError, match="broken chart"): @@ -861,25 +937,31 @@ def test_amgm_certificate_is_exact_for_rational_coefficients(): import numpy as np from symident.reduction.sign import absorb + e = np.array([[2, 0], [1, 1], [0, 2]], dtype=float) assert any(b > 0 for b in absorb(e, [Fr(1), Fr(-1), Fr(1)])) # no budget left where the polynomial reaches zero, no certificate where it falls below, by any margin assert not any(b > 0 for b in absorb(e, [Fr(1), Fr(-2), Fr(1)])) - assert absorb(e, [Fr(1), Fr(-2) - Fr(1, 10 ** 12), Fr(1)]) is None + assert absorb(e, [Fr(1), Fr(-2) - Fr(1, 10**12), Fr(1)]) is None def test_exact_rank_of_rationals(): from fractions import Fraction as Fr from symident.reduction.invariants import exact_rank + assert exact_rank([[1, 2], [2, 4]]) == 1 assert exact_rank([[Fr(1, 3), 1], [1, Fr(1, 3)]]) == 2 assert exact_rank([[1.5, 2]]) == 1 and exact_rank([["x", 1]]) is None def test_the_reduction_reads_the_level_of_the_directions(): - m = si.Model({"A": "-k1*A + k2*B", "B": "k1*A - k2*B"}, {"Aobs": "alpha*A"}, trafo={"k1": "k2*B/A"}, - events=[{"var": "A", "time": 0, "value": "1", "method": "add"}]) + m = si.Model( + {"A": "-k1*A + k2*B", "B": "k1*A - k2*B"}, + {"Aobs": "alpha*A"}, + trafo={"k1": "k2*B/A"}, + events=[{"var": "A", "time": 0, "value": "1", "method": "add"}], + ) r = si.detect(m, reconstruct=True) assert [s.level for s in r.symmetries] == ["exact"] # the level of the detection as a verified closed form would leave it @@ -904,18 +986,32 @@ def test_the_reduction_reads_the_level_of_the_directions(): def test_the_trafo_is_checked_back_and_the_loop_closed(): r = red(det(F_AB, {"y": "s*A"}, reconstruct=True)) assert r.checks["pins"] is True and r.checks["invariants"] is True and r.checks["failed"] == [] - assert r.checks["loop"] == {"directions": 0, "expected": 0, "rank": 3, "dim": 3, "rank_status": "proven", - "ok": True} + assert r.checks["loop"] == { + "directions": 0, + "expected": 0, + "rank": 3, + "dim": 3, + "rank_status": "proven", + "ok": True, + } assert "loop" not in red(det(F_AB, {"y": "s*A"}, reconstruct=True), check=False).checks - bad = {"removed": ["X₁"], "remaining": [], "blocks": [], "trafo": {"a": "1"}, - "checks": {"failed": ["q_1 = a*b"], "loop": {"directions": 1, "expected": 0, "rank": 1, "dim": 2, - "rank_status": "proven", "ok": False}}} + bad = { + "removed": ["X₁"], + "remaining": [], + "blocks": [], + "trafo": {"a": "1"}, + "checks": { + "failed": ["q_1 = a*b"], + "loop": {"directions": 1, "expected": 0, "rank": 1, "dim": 2, "rank_status": "proven", "ok": False}, + }, + } text = " ".join(report.reduction_lines(bad, width=80)).replace(" ", " ") assert "Check failed over Q: q_1 = a*b." in text and "the reduced model has 1 direction, 0 expected" in text def test_roots_are_taken_only_of_positive_symbols(): from symident.reduction.core import _tidy_root + assert _tidy_root("sqrt(x^2*y)", {"x", "y"}) == "x*sqrt(y)" assert _tidy_root("sqrt(x^2*y)", {"y"}) == "sqrt(x^2*y)" @@ -923,12 +1019,14 @@ def test_roots_are_taken_only_of_positive_symbols(): def test_invariants_are_checked_against_the_generators_as_detected(): r = red(det(F_AB, {"y": "s*A"}, reconstruct=True)) curved = [b for b in r.blocks if b["type"] != "scaling"] - assert curved and all("verified: X(I) = 0 exactly for every generator as detected" in b["certificates"] - for b in curved) + assert curved and all( + "verified: X(I) = 0 exactly for every generator as detected" in b["certificates"] for b in curved + ) def test_independence_of_invariants_with_exp_is_certified(): from symident.reduction.blocks import independent_set + assert independent_set(["exp(a)*b", "exp(2*a)*b^2", "c*exp(b)"], ["a", "b", "c"], 2) == ["exp(a)*b", "c*exp(b)"] @@ -940,8 +1038,11 @@ def test_the_invariant_count_says_whether_it_is_exact(): def test_signs_of_numbers_are_exact(): from symident.reduction.sign import num_sign, sgn_poly + assert num_sign(spy.sqrt(2) - 1) == 1 and num_sign(spy.pi - spy.Rational(355, 113)) == -1 - assert num_sign(spy.exp(1) * spy.exp(-1) - 1) == 0 and num_sign((spy.sqrt(2) + 1)**2 - 3 - 2 * spy.sqrt(2)) is None + assert ( + num_sign(spy.exp(1) * spy.exp(-1) - 1) == 0 and num_sign((spy.sqrt(2) + 1) ** 2 - 3 - 2 * spy.sqrt(2)) is None + ) x, y = spy.symbols("x y") assert sgn_poly(spy.sqrt(2) * x + spy.pi * y) == 1 # an algebraic coefficient never enters a float budget @@ -951,15 +1052,20 @@ def test_signs_of_numbers_are_exact(): def test_the_rank_of_a_weight_matrix_is_exact(): from symident.gfp import PRIMES from symident.reduction.scaling import rank_modp + p = PRIMES[0] W = np.array([[1, 0], [0, p]], dtype=object) assert rank_modp(W) == 2 and rank_modp(W, p) == 1 def test_a_face_section_is_proven_where_the_model_is_continuous_up_to_the_face(): - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, {"y": "s*x2"}, - inputs=["u"], events=[{"var": "u", "time": 0, "value": "dose", "method": "replace"}], - conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, + {"y": "s*x2"}, + inputs=["u"], + events=[{"var": "u", "time": 0, "value": "dose", "method": "replace"}], + conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}, + ) r = red(si.detect(m, equilibrate=True, reconstruct=True)) scal, curved = r.blocks assert scal["level"] == "exact" and scal["unproven"] == [] @@ -971,10 +1077,12 @@ def test_a_face_section_is_proven_where_the_model_is_continuous_up_to_the_face() def test_continuity_up_to_a_face_is_checked_on_the_model(): from symident.reduction.sections import face_regular + co, su = ["kb", "k1", "kl"], ["k1", "kl"] def why(*a, **kw): return face_regular(*a, **kw)[0] + lin = {"x1": "kb - (k1 + kl)*x1"} assert face_regular(["kl"], list(lin.values()), lin, True, co, su) == (None, "exact") sq = {"x1": "kb - (k1 + kl)*x1^2"} @@ -995,8 +1103,9 @@ def test_section_search_stops_at_its_work_cap_and_says_so(): pos = ["c", "k0", "kd", "w", "b", "x"] res = det(f, {"y": "x"}, gauge=None, reconstruct=True, positive=pos) r = red(res, positive=pos, work_cap=0) - assert any(b["status"] == "invariant_only" and "work_cap" in (b.get("reason") or "") - for b in blocks_of(r, "curved")) + assert any( + b["status"] == "invariant_only" and "work_cap" in (b.get("reason") or "") for b in blocks_of(r, "curved") + ) assert any("reduce(work_cap=0) reached" in lim for lim in r.limits) assert red(res, positive=pos).trafo == red(res, positive=pos).trafo @@ -1011,14 +1120,25 @@ def test_a_product_at_one_covers_orbits_that_a_pin_misses(): def test_a_section_claim_without_proof_is_named(): from symident.reduction.core import unproven_of - b = {"status": "reduced", "type": "curved", "pins": {"a": "q_1"}, "section": ["a*b = c"], - "transversal": ["a", "b"], "face": False, "count": "exact"} - assert unproven_of(b) == ["every level set of the invariants is one orbit", - "each orbit meets the section a*b = c at most once"] + + b = { + "status": "reduced", + "type": "curved", + "pins": {"a": "q_1"}, + "section": ["a*b = c"], + "transversal": ["a", "b"], + "face": False, + "count": "exact", + } + assert unproven_of(b) == [ + "every level set of the invariants is one orbit", + "each orbit meets the section a*b = c at most once", + ] def test_real_coordinates_are_not_claimed_positive(): from symident.reduction.sign import set_positive, sgn_poly + x, y = spy.symbols("x y") old = set_positive(["y"]) try: @@ -1035,6 +1155,7 @@ def test_real_coordinates_are_not_claimed_positive(): def test_a_sampled_vector_is_checked_before_it_is_chosen(monkeypatch): import symident.reduction.invariants as ri from symident.reduction.expr import gen_prep + preps = [gen_prep({"generator": {"x": "x", "y": "-y"}})] vars_ = ["x", "y"] expts = np.array([[1, 0], [1, 1]]) @@ -1043,6 +1164,7 @@ def test_a_sampled_vector_is_checked_before_it_is_chosen(monkeypatch): def fake(rows_at, n, eval_vars, min_rows=0): calls.append(min_rows) return {"basis": np.array([[1, 0], [0, 1]], dtype=np.int64), "rows": 3} + monkeypatch.setattr(ri, "modular_nullspace", fake) ns = ri._checked_nullspace(preps, vars_, expts, 2) assert calls == [0, 4 * 2 + 20] @@ -1051,6 +1173,7 @@ def fake(rows_at, n, eval_vars, min_rows=0): def test_a_constant_pin_of_one_monotone_generator_is_proven(): from symident.reduction.core import monotone_pins, unproven_of + b = {"status": "reduced", "type": "curved", "pins": {"a": "1", "c": "q_1"}, "face": False, "count": "exact"} assert monotone_pins(b, [{"generator": {"a": "a*b", "c": "-c"}}]) == ["a"] assert monotone_pins(b, [{"generator": {"a": "a - b", "c": "-c"}}]) == [] @@ -1060,6 +1183,7 @@ def test_a_constant_pin_of_one_monotone_generator_is_proven(): def test_a_direction_without_state_components_lifts_tangent_to_the_resting_variety(): from symident.reduction.core import lifted_generators + rhs = {"x1": "kb - (k1 + kl)*x1", "u": "0"} gen = {"X1": {"generator": {"kb": "kb", "k1": "k1", "kl": "kl"}}} (g,), level = lifted_generators(["X1"], gen, rhs) @@ -1073,6 +1197,7 @@ def test_a_direction_without_state_components_lifts_tangent_to_the_resting_varie def test_a_real_carrier_has_no_sign_unless_the_carriers_are_taken_positive(): from symident.reduction.sign import DOMAIN, carriers_real, sgn + c = spy.Symbol("si_red_c1") old = DOMAIN["positive"] DOMAIN["positive"] = None @@ -1088,10 +1213,11 @@ def test_a_real_carrier_has_no_sign_unless_the_carriers_are_taken_positive(): def test_the_sign_changes_of_undecided_coefficients_are_counted_without_enumeration(): from symident.reduction.sections import _interval, _max_variations from symident.reduction.sign import carriers_real + assert _max_variations([{1}, {1, -1}, {1}]) == 2 and _max_variations([{1}, {1}, {-1}]) == 1 x, a = spy.symbols("x si_red_c1") with carriers_real(["si_red_c1"]): - assert _interval(spy.Poly(-x**2 + a * x + 1, x), False) + assert _interval(spy.Poly(-(x**2) + a * x + 1, x), False) assert not _interval(spy.Poly(x**3 + a * x**2 + a * x + 1, x), True) assert _interval(spy.Poly(sum((a**2 + 1) * x**k for k in range(1, 12)) - 1, x), True) @@ -1099,6 +1225,7 @@ def test_the_sign_changes_of_undecided_coefficients_are_counted_without_enumerat def test_the_work_cap_of_a_reduction_ends_with_the_call(): from symident.reduction.expr import tri_solve from symident.reduction.sign import DOMAIN + f = {"c": "k0 - kd*c", "x": "w*(q + b*c) - x"} pos = ["c", "k0", "kd", "w", "b", "x"] red(det(f, {"y": "x"}, gauge=None, reconstruct=True, positive=pos), positive=pos, work_cap=0) @@ -1110,6 +1237,7 @@ def test_the_work_cap_of_a_reduction_ends_with_the_call(): def test_a_triangular_solve_says_when_a_branch_may_be_missing(): from symident.reduction.expr import tri_solve + x, y = spy.symbols("x y") info = {"complete": True} assert len(tri_solve([x**2 - 2, y - x], ["x", "y"], info)) == 2 and info["complete"] @@ -1123,6 +1251,7 @@ def test_a_triangular_solve_says_when_a_branch_may_be_missing(): def test_a_triangular_solve_drops_a_large_branch_over_a_radical(monkeypatch): from symident.reduction import expr from symident.reduction.expr import tri_solve + monkeypatch.setattr(expr, "RADICAL_NODES", 20) x, y, a = spy.symbols("x y a") big = (x + a) ** 3 / (x - 1) + (x - a) ** 2 / (x + 2) @@ -1134,6 +1263,7 @@ def test_a_triangular_solve_drops_a_large_branch_over_a_radical(monkeypatch): def test_a_rank_of_exact_numbers_is_certified(): from symident.reduction.invariants import certified_rank + assert certified_rank([[1, 2], [2, 4]]) == 1 assert certified_rank([[spy.sqrt(2), 1], [2, spy.sqrt(2)]]) == 1 assert certified_rank([[spy.exp(1), 1], [1, spy.pi]]) == 2 @@ -1144,6 +1274,7 @@ def test_a_ratio_with_a_real_coordinate_to_an_odd_power_has_no_sign(): from symident.reduction.expr import red_locals from symident.reduction.sections import section_monotone from symident.reduction.sign import set_positive + loc = red_locals(["a", "b"]) pr = {"comps": {"a": "a", "b": "-b"}} xi = [{spy.Symbol("a"): spy.Symbol("a"), spy.Symbol("b"): -spy.Symbol("b")}] @@ -1160,19 +1291,28 @@ def test_a_ratio_with_a_real_coordinate_to_an_odd_power_has_no_sign(): def test_a_resting_state_without_a_point_over_the_field_is_redrawn(): from symident.reduction.sections import rest_checked + assert rest_checked({"x": "a - b*x^2"}, [], []) assert not rest_checked({"x": "a"}, [], []) def test_an_undecided_zero_limit_is_unknown_not_no(): from symident.reduction.zero import zero_compat - b = {"support": ["a", "b"], "invariants": ["a**3 + a**2*b + b**3 + 2*a"], "status": "reduced", - "type": "curved", "preps": None, "target": None} + + b = { + "support": ["a", "b"], + "invariants": ["a**3 + a**2*b + b**3 + 2*a"], + "status": "reduced", + "type": "curved", + "preps": None, + "target": None, + } assert {r["verdict"] for r in zero_compat(b)} == {"unknown"} def test_a_checked_direction_or_a_failed_saturation_warns_and_is_an_error_only_on_request(): from symident.reduction.core import check_levels + failed = {"symmetries": [{"level": "exact"}], "info": {"verification": {"ok": False, "reason": "r"}}} with pytest.raises(ValueError, match="allow_checked"): check_levels({"symmetries": [{"level": "checked"}]}, allow_checked=False) @@ -1197,6 +1337,7 @@ def idle(): def refused(): raise ValueError("... anything else is not rational.\n E = sqrt(q)") + assert loop_outcome(idle, 0)["ok"] is False out = loop_outcome(refused, 0) assert out["ok"] is None and "not rational" in out["reason"] @@ -1208,8 +1349,10 @@ def test_the_closed_loop_applies_the_trafo_to_symbolic_grid_cells(): c = {"rows": ["a1", "a2"], "cols": {"tau": ["t11", "t12"], "KA": ["K11", "K12"]}} with warnings.catch_warnings(record=True) as rec: warnings.simplefilter("always") - r = si.detect(si.Model({"A": "1"}, {"E": "Em*tau*A/(KA + (1+tau)*A)"}, trafo={"A": "1", "t11": "1"}, - conditions=c), cores=1) + r = si.detect( + si.Model({"A": "1"}, {"E": "Em*tau*A/(KA + (1+tau)*A)"}, trafo={"A": "1", "t11": "1"}, conditions=c), + cores=1, + ) assert not any("had no effect" in str(w.message) for w in rec) and "t11" not in r.info["coordinates"] @@ -1231,8 +1374,7 @@ def test_the_closed_loop_applies_a_pin_of_a_renamed_column_in_the_grid(): rename = {"rows": ["a", "b"], "cols": {"s": ["s", "s2"]}} r = si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}, conditions=rename), reconstruct=True) assert r.reduce().trafo["s"] == "1" - ref = si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}, conditions={"rows": ["a", "b"], - "cols": {"s": ["1", "s2"]}})) + ref = si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}, conditions={"rows": ["a", "b"], "cols": {"s": ["1", "s2"]}})) assert _loop_matches(r, ref) with pytest.warns(UserWarning, match="condition column"): si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}, conditions=rename, trafo={"s": "1"})) @@ -1258,6 +1400,7 @@ def test_the_closed_loop_of_moieties_and_resting_values(): def test_a_resting_value_pinned_to_an_expression_is_no_model(): from symident.api import reduced_model + rm = reduced_model({"z": "-k*u*z", "u": "0"}, {"y": "z"}, None, None, None, {"z": "q_1", "k": "k"}, True) assert rm["why"] is not None and "resting value of z" in rm["why"] rm = reduced_model({"z": "-k*u*z", "u": "0"}, {"y": "z"}, None, None, None, {"z": "1", "k": "k"}, True) @@ -1276,6 +1419,7 @@ def test_a_result_keeps_the_model_it_detected_and_its_reduction(): def test_a_direction_at_rest_is_verified_unless_a_resting_branch_is_undecided(monkeypatch): from symident.detection.observability.joint import JointSystem + ev = [{"var": "u", "time": 0, "value": "1", "method": "replace"}] m = si.Model({"z": "-k*u*z", "w": "-j*u*w", "u": "0"}, {"y": "z*w"}, inputs=["u"], events=ev) # without field routes the direction comes from a route checked at random points @@ -1297,6 +1441,7 @@ def test_a_direction_at_rest_is_verified_unless_a_resting_branch_is_undecided(mo def test_atoms_count_positive_only_where_proven(): from symident.reduction.sign import set_positive, sgn + x, y = spy.symbols("x y") old = set_positive(None) try: @@ -1308,12 +1453,13 @@ def test_atoms_count_positive_only_where_proven(): def test_am_gm_keeps_a_strict_sign_only_with_budget_left(): from symident.reduction.sign import set_positive, sgn_poly + x, y, r_, s_ = spy.symbols("x y r s") old = set_positive(["x", "y"]) try: - assert sgn_poly((1 - r_**2)**2 + s_**2) == 0 - assert sgn_poly((x - y)**2 + r_**2) == 0 - assert [sgn_poly(e) for e in (x**2 + y**2 - x*y, (x - y)**2 + 1, (x - y)**2 + x)] == [1, 1, 1] + assert sgn_poly((1 - r_**2) ** 2 + s_**2) == 0 + assert sgn_poly((x - y) ** 2 + r_**2) == 0 + assert [sgn_poly(e) for e in (x**2 + y**2 - x * y, (x - y) ** 2 + 1, (x - y) ** 2 + x)] == [1, 1, 1] finally: set_positive(old) @@ -1329,6 +1475,7 @@ def test_a_direction_along_one_coordinate_is_pinned_where_its_component_keeps_a_ def test_alternatives_rank_by_level_first(): from symident.reduction.core import _chart_rank + rational_open = {"removed": ["X1"], "trafo": {"a": "q_1"}, "level": "open"} radical_exact = {"removed": ["X1"], "trafo": {"a": "sqrt(q_1)"}, "level": "exact"} assert sorted([rational_open, radical_exact], key=_chart_rank)[0] is radical_exact @@ -1337,6 +1484,7 @@ def test_alternatives_rank_by_level_first(): def test_a_failed_denominator_publishes_no_complete_form(): from symident.detection.finalize import complete, denominator + assert denominator({"x": "1/(a +* b)"}) is None (d,) = complete([{"type": "general", "generator": {"x": "1/(a +* b)"}}]) assert d["complete_generator"] is None and d["factor"] is None @@ -1373,6 +1521,7 @@ def test_a_section_whose_entries_take_both_signs_covers_the_orbits_where_they_ar def test_lift_of_parameters_the_resting_state_does_not_read(): from symident.reduction.core import lifted_generators + # parameters that enter only with an input zero at rest lift exactly, however large the model rhs = {f"x{i}": f"a{i}*x{i - 1} - b{i}*x{i}" for i in range(1, 30)} rhs["x0"] = "k*u/(1 + K*u) + c - d*x0" @@ -1393,8 +1542,12 @@ def test_an_invariant_of_a_resting_state_is_no_trafo_entry(): def test_a_system_of_invariants_past_the_degree_cap_is_a_limit_not_a_hang(): f = {"A": "-k1*A*B + k2*C", "B": "-k1*A*B + k2*C", "C": "k1*A*B - k2*C"} - m = si.Model(f, {"Aobs": "alpha*A"}, trafo={"k1": "k2*C/(A*B)"}, - events=[{"var": "A", "time": 0, "value": "1", "method": "add"}]) + m = si.Model( + f, + {"Aobs": "alpha*A"}, + trafo={"k1": "k2*C/(A*B)"}, + events=[{"var": "A", "time": 0, "value": "1", "method": "add"}], + ) red = si.detect(m, reconstruct=True).reduce(check=False) assert any("above 32" in lim for lim in red.limits) # another gauge coordinate gives a system within the cap @@ -1416,6 +1569,7 @@ def positive_domain(): def declare(names): set_positive(list(names)) + old = set_positive(None) yield declare set_positive(old) @@ -1424,6 +1578,7 @@ def declare(names): def test_a_scaling_pins_a_positive_coordinate_before_a_signed_one(): # a scaling keeps the sign of a coordinate, so only a positive pin meets every orbit from symident.reduction import symmetry_reduction + obj = mkobj([mkdir({"x0": "x0", "c": "-c"}, "scaling", {"x0": "1", "c": "-1"})], ["x0", "c"]) r = symmetry_reduction(obj, positive=["c"]) assert r["blocks"][0]["pins"] == {"c": "1"} and r["blocks"][0].get("coverage") is None @@ -1432,6 +1587,7 @@ def test_a_scaling_pins_a_positive_coordinate_before_a_signed_one(): def test_curved_directions_combine_with_the_scalings_to_leave_their_pins_unmoved(positive_domain): from symident.reduction.core import _rebased from symident.reduction.scaling import scaling_block + positive_domain(["a1", "a2", "b", "c"]) blk = scaling_block(np.array([[1, -1, 1]]), ["a2", "b", "P"], ["X1"], [], allowed=["b"]) curved_dir = {"type": "general", "generator": {"a1": "b*P", "a2": "c*P - a2", "b": "b"}} @@ -1443,13 +1599,21 @@ def test_curved_directions_combine_with_the_scalings_to_leave_their_pins_unmoved def test_a_signed_invariant_proposes_products_with_a_jacobian_of_one_sign(positive_domain): from symident.reduction.expr import red_locals, red_sympify from symident.reduction.sections import section_jacobian, section_monotone, split_products + positive_domain(["a1", "a2", "b11", "b21", "b22"]) a1, a2, b11, b22 = spy.symbols("a1 a2 b11 b22") - assert split_products([a1 * b22 - a2, b11 + b22], ["a1", "a2", "b11", "b22"]) == \ - [["a1*a2", "1"], ["a2*b22", "1"]] - gens = [{"a1": "1", "a2": "b22", "P2": "1"}, - {"a1": "b11*P2 - b21*P1 - b22*P2", "a2": "a1*b21 + b11*b22*P2 - b21*b22*P1 - b22^2*P2", - "b11": "-b21", "b22": "b21", "b21": "b11*b21 - b21*b22", "P2": "b11*P2 - b22*P2"}] + assert split_products([a1 * b22 - a2, b11 + b22], ["a1", "a2", "b11", "b22"]) == [["a1*a2", "1"], ["a2*b22", "1"]] + gens = [ + {"a1": "1", "a2": "b22", "P2": "1"}, + { + "a1": "b11*P2 - b21*P1 - b22*P2", + "a2": "a1*b21 + b11*b22*P2 - b21*b22*P1 - b22^2*P2", + "b11": "-b21", + "b22": "b21", + "b21": "b11*b21 - b21*b22", + "P2": "b11*P2 - b22*P2", + }, + ] preps = [{"comps": {k: v.replace("^", "**") for k, v in g.items()}} for g in gens] loc = red_locals([x for p in preps for x in p["comps"].values()] + ["a1*a2"]) xi_of = [{k: red_sympify(v, loc) for k, v in p["comps"].items()} for p in preps] @@ -1462,6 +1626,7 @@ def test_a_signed_invariant_proposes_products_with_a_jacobian_of_one_sign(positi def test_a_section_under_a_square_root_is_injective_where_the_radicand_is_a_square(positive_domain): from symident.reduction import sign from symident.reduction.sections import section_injective + positive_domain(["a1", "a2", "b11", "b21", "b22"]) old = sign.DOMAIN["real_carriers"] sign.DOMAIN["real_carriers"] = ["t3", "t4"] @@ -1470,8 +1635,14 @@ def test_a_section_under_a_square_root_is_injective_where_the_radicand_is_a_squa t1, t2, t3, t4 = spy.symbols("t1 t2 t3 t4") inv = [b11 + b22, b11**2 + 2 * b21 + b22**2, a1 * b22 - a2, a1 - P2 - b11 * P1] r = spy.sqrt(2 * t1 + t3**2) - sol = {"a1": (t3 + r) / t1, "a2": (r - t3) / 2, "b11": t1 / 2, "b22": t1 / 2, "b21": t2 / 2 - t1**2 / 4, - "P2": (t3 + r) / t1 - t1 * P1 / 2 - t4} + sol = { + "a1": (t3 + r) / t1, + "a2": (r - t3) / 2, + "b11": t1 / 2, + "b22": t1 / 2, + "b21": t2 / 2 - t1**2 / 4, + "P2": (t3 + r) / t1 - t1 * P1 / 2 - t4, + } assert section_injective(inv, sol, ["t1", "t2", "t3", "t4"], [], [(a1 * a2, spy.Integer(1)), (b11, b22)]) finally: sign.DOMAIN["real_carriers"] = old @@ -1479,6 +1650,7 @@ def test_a_section_under_a_square_root_is_injective_where_the_radicand_is_a_squa def test_charts_with_total_coverage_rank_before_rational_ones(): from symident.reduction.core import _chart_rank + total = {"level": "exact", "removed": ["X1"], "trafo": {"a": "sqrt(q_1)"}, "blocks": [{"coverage": "total"}]} part = {"level": "exact", "removed": ["X1"], "trafo": {"a": "q_1"}, "blocks": [{"coverage": "partial"}]} assert sorted([part, total], key=_chart_rank)[0] is total @@ -1489,6 +1661,7 @@ def test_the_carriers_are_solved_without_the_unbounded_solver(monkeypatch): def refuse(*a, **k): raise AssertionError("unbounded solver") + monkeypatch.setattr(solve.spy, "solve", refuse) q1, q2, a1, a2, b = spy.symbols("q1 q2 a1 a2 b") br = solve._carrier_branches([a1 * b - a2 - q1, a1 + a2**2 - q2], ["a1", "a2"], 2) @@ -1501,13 +1674,23 @@ def refuse(*a, **k): def test_a_section_met_once_is_its_own_rational_chart(positive_domain): from symident.reduction.solve import _section_chart + positive_domain(["a1", "a2", "b11", "b22"]) a1, a2, b11, b22, t1, t2 = spy.symbols("a1 a2 b11 b22 t1 t2") # the section point solved from the invariants holds a root; the coordinates of the section are rational r = spy.sqrt(t2**2 + 4 * t1) es = {"a1": (t2 + r) / t1, "a2": (r - t2) / 2, "b11": t1 / 2, "b22": t1 / 2} - sc = _section_chart(["a1", "a2", "b11", "b22"], ["a1", "a2", "b11", "b22"], es, [(a1 * a2, 1), (b11, b22)], - ["t1", "t2"], ["q_1", "q_2"], [b11 + b22, a1 * b22 - a2], {}, []) + sc = _section_chart( + ["a1", "a2", "b11", "b22"], + ["a1", "a2", "b11", "b22"], + es, + [(a1 * a2, 1), (b11, b22)], + ["t1", "t2"], + ["q_1", "q_2"], + [b11 + b22, a1 * b22 - a2], + {}, + [], + ) assert sc["pins"] == {"a1": "1/q_1", "a2": "q_1", "b11": "q_2", "b22": "q_2"} assert sc["solved_domain"] == {"q_1": "positive", "q_2": "positive"} assert spy.sympify(sc["meaning"]["q_2"]) == (b11 + b22) / 2 @@ -1515,7 +1698,10 @@ def test_a_section_met_once_is_its_own_rational_chart(positive_domain): def test_the_reduced_model_declares_the_domains_of_the_new_parameters(): from symident.api import _reduced_positive - red = {"trafo": {"a": "q_1", "b": "c*sqrt(q_2)", "d": "q_3"}, - "blocks": [{"solved_domain": {"q_1": "positive", "q_2": "real"}}, {"solved_domain": {"q_3": "positive"}}]} + + red = { + "trafo": {"a": "q_1", "b": "c*sqrt(q_2)", "d": "q_3"}, + "blocks": [{"solved_domain": {"q_1": "positive", "q_2": "real"}}, {"solved_domain": {"q_3": "positive"}}], + } assert _reduced_positive(True, red, ["x"]) == ["c", "q_1", "q_3", "x"] assert _reduced_positive(["a", "c"], red, ["x"]) == ["c", "q_1", "q_3"] diff --git a/tests/test_reduce_linear.py b/tests/test_reduce_linear.py index 08451bf..62d053f 100644 --- a/tests/test_reduce_linear.py +++ b/tests/test_reduce_linear.py @@ -16,15 +16,22 @@ def red(obj, **kw): def mkobj(gens, coords, positive, rhs=None, unknown=None): - dirs = [{"type": "general", "generator": g, "weights": None, "support": list(g), "explicit": True, - "level": "exact"} for g in gens] + dirs = [ + {"type": "general", "generator": g, "weights": None, "support": list(g), "explicit": True, "level": "exact"} + for g in gens + ] info = {"engine": "modular", "settings": {"positive": positive}, "coordinates": list(coords)} if rhs is not None: info["model_rhs"] = rhs if unknown is not None: info["unknown_inputs"] = {"names": list(unknown), "jets": {w: [w, f"{w}_d1"] for w in unknown}} - return {"identifiable": False, "rank": len(coords) - len(gens), "dim": len(coords), "symmetries": dirs, - "info": info} + return { + "identifiable": False, + "rank": len(coords) - len(gens), + "dim": len(coords), + "symmetries": dirs, + "info": info, + } def offset_model(off="c", rev="E"): @@ -66,7 +73,7 @@ def test_two_directions_one_block(): assert len(bs) == 1 and bs[0]["stage"] == "linear flow" b = bs[0] assert len(b["pins"]) == 2 and b["injective"] and b["reach"] - (q, inv), = b["new_parameters"].items() + ((q, inv),) = b["new_parameters"].items() p_, q_, r_, u_ = spy.symbols("p q r u") e = spy.sympify(inv) for g in ({p_: 1, q_: 1}, {q_: u_, r_: 1}): @@ -88,6 +95,7 @@ def test_not_a_linear_flow(): from symident.reduction.expr import gen_prep from symident.reduction.linear import linear_flow from symident.reduction.sign import set_positive + old = set_positive(None) try: pr = gen_prep({"generator": {"p": "1", "q": "-1"}}) @@ -105,9 +113,13 @@ def test_not_a_linear_flow(): def test_unknown_input_directions_named(): # a direction whose components depend on states and unknown inputs has no chart in the parameters - obj = mkobj([{"k1": "k1*n*x2^n", "w1": "-(w1 + 1)*(x2^n + (w1 + 1)^n)"}], - ["w1", "x1", "x2", "k1", "n"], True, - rhs={"x1": "k1/(1 + (x2/(1 + w1))^n) - x1", "x2": "1 - x2", "w1": "w1_d1"}, unknown=["w1"]) + obj = mkobj( + [{"k1": "k1*n*x2^n", "w1": "-(w1 + 1)*(x2^n + (w1 + 1)^n)"}], + ["w1", "x1", "x2", "k1", "n"], + True, + rhs={"x1": "k1/(1 + (x2/(1 + w1))^n) - x1", "x2": "1 - x2", "w1": "w1_d1"}, + unknown=["w1"], + ) x = red(obj) b = x.to_dict()["blocks"][0] assert b["status"] == "unresolved" and b.get("absorbed_by_inputs") @@ -119,7 +131,9 @@ def test_interval_minor_exact_coefficients(): # dependent invariants with rational coefficients are not certified independent by rounding assert independent_set(["exp(a/3)*b", "exp(a)*b^3"], ["a", "b"], 2) == ["exp(a/3)*b"] assert independent_set(["exp(a/7)*b^(1/3)", "exp(3*a/7)*b"], ["a", "b"], 2) == ["exp(a/7)*b^(1/3)"] - assert independent_set(["exp(a/7)*b^(1/3)", "exp(3*a/7)*b^2"], ["a", "b"], 2) == \ - ["exp(a/7)*b^(1/3)", "exp(3*a/7)*b^2"] + assert independent_set(["exp(a/7)*b^(1/3)", "exp(3*a/7)*b^2"], ["a", "b"], 2) == [ + "exp(a/7)*b^(1/3)", + "exp(3*a/7)*b^2", + ] # a function without interval version is evaluated exactly assert independent_set(["atan(a)*exp(b/3)", "exp(b)*atan(a)^3"], ["a", "b"], 2) == ["atan(a)*exp(b/3)"] diff --git a/tests/test_report.py b/tests/test_report.py index 4d0df77..347a0a4 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -3,14 +3,20 @@ from symident import report SCAL = {"type": "scaling", "generator": {"x": "x", "s": "-s"}} -GEN = {"type": "general", "generator": {"k1": "k1*k2 - 1.5e-3*k1", "k2": "-(a - b)*k2"}, - "route": "quadrature"} +GEN = {"type": "general", "generator": {"k1": "k1*k2 - 1.5e-3*k1", "k2": "-(a - b)*k2"}, "route": "quadrature"} SUPP = {"type": "general", "generator": None, "support": ["a", "b"], "reason": "too large"} def res(syms, **kw): - out = {"method": "observability", "rank": 3, "dim": 5, "identifiable": not syms, - "symmetries": syms, "gauge": None, "info": {"engine": "modular", "settings": {}}} + out = { + "method": "observability", + "rank": 3, + "dim": 5, + "identifiable": not syms, + "symmetries": syms, + "gauge": None, + "info": {"engine": "modular", "settings": {}}, + } out.update(kw) return out @@ -52,21 +58,31 @@ def test_reduction_hints_singular_and_plural(): def test_result_line_per_method(): assert report.result_lines(res([], rank=5)) == ["Result: structurally locally identifiable (rank 5 / 5)"] - assert report.result_lines(res([SCAL]), width=80)[0] == \ - "Result: rank 3 / 5 | 1 non-identifiable direction" - assert report.result_lines(res([SCAL, SCAL], method="scalings"), width=80)[0] == \ - "Result: 2 scaling symmetries (exact integer kernel)" + assert report.result_lines(res([SCAL]), width=80)[0] == "Result: rank 3 / 5 | 1 non-identifiable direction" + assert ( + report.result_lines(res([SCAL, SCAL], method="scalings"), width=80)[0] + == "Result: 2 scaling symmetries (exact integer kernel)" + ) def test_summary_computation_lines(): - info = {"engine": "modular", "lie_order_used": 3, "lie_order_driver": 1, "gap_order_used": None, - "lie_plateau": 2, "lie_uncertified": [0, 2], "conditions": 2, "segments": 3, - "switching": {"surfaces": ["c - x = 0"], "regimes": [[1], [-1]], "excluded": [[0]]}, - "settings": {"reconstruct": True, "verify": True}, "verification": {"ok": False, "reason": "r"}, - "elapsed": 1.25, - "gauge_suggestion": {"gauge": ["k"], "sizes": [2], "plain": ["s"], "plain_sizes": [4]}} + info = { + "engine": "modular", + "lie_order_used": 3, + "lie_order_driver": 1, + "gap_order_used": None, + "lie_plateau": 2, + "lie_uncertified": [0, 2], + "conditions": 2, + "segments": 3, + "switching": {"surfaces": ["c - x = 0"], "regimes": [[1], [-1]], "excluded": [[0]]}, + "settings": {"reconstruct": True, "verify": True}, + "verification": {"ok": False, "reason": "r"}, + "elapsed": 1.25, + "gauge_suggestion": {"gauge": ["k"], "sizes": [2], "plain": ["s"], "plain_sizes": [4]}, + } out = report.summary_lines(res([SCAL], info=info), width=80) - comp = out[out.index("Computation:") + 1:out.index("")] + comp = out[out.index("Computation:") + 1 : out.index("")] assert comp == [ " Lie order 3 (gap order 0), set by condition 2", " saturation: certified except condition 1, 3 (rank bound not reached)", @@ -76,20 +92,24 @@ def test_summary_computation_lines(): "only where it is free in every allowed regime, from any point of a switching surface", " settings: reconstruct=True", " saturation guard: FAILED (r; directions may be over-reported)", - " elapsed: 1.2s"] + " elapsed: 1.2s", + ] assert out[1] == "detect | observability engine: modular (GF(p) + CRT)" def test_summary_saturation_and_guard_variants(): def comp(**info): out = report.summary_lines(res([], info={"engine": "x", **info}), width=80) - return out[out.index("Computation:") + 1:out.index("")] if "Computation:" in out else [] + return out[out.index("Computation:") + 1 : out.index("")] if "Computation:" in out else [] + assert comp(rank_proven=2, rank_proof="proven symmetries") == [" rank: proven (2 directions, proven symmetries)"] - assert comp(rank_fields=2) == [" rank: lower bound (2 directions, invariant fields at random points " - "without an error bound)"] - assert comp(rank_fields=2, rank_fields_bound={"probability": 3e-12}) == \ - [" rank: verified (2 directions, invariant fields at random points, probability of a wrong pass at " - "most 3.0e-12)"] + assert comp(rank_fields=2) == [ + " rank: lower bound (2 directions, invariant fields at random points without an error bound)" + ] + assert comp(rank_fields=2, rank_fields_bound={"probability": 3e-12}) == [ + " rank: verified (2 directions, invariant fields at random points, probability of a wrong pass at " + "most 3.0e-12)" + ] assert comp(lie_plateau=2, lie_certified=True)[0].startswith(" saturation: certified (every") assert comp(lie_plateau=2) == [" saturation: provisional (plateau 2, no rank bound reached)"] assert comp(verification={"ok": True, "reason": "ok"}) == [" saturation guard: PASSED (ok)"] @@ -98,49 +118,112 @@ def comp(**info): def test_reduction_verdict(): - x = {"removed": ["X₁", "X₂"], "remaining": ["X₃"], "dependent": ["X₄"], - "blocks": [{"coverage": "partial", "status": "reduced", "labels": ["X₂"]}, - {"coverage": "partial", "status": "kept", "labels": ["X₃"]}]} - assert report.red_verdict(x) == ("Reduced 2 of 3 directions (X₃ remaining); X₄ depends on the others; " - "the section of X₂ covers only part of the positive orthant.") + x = { + "removed": ["X₁", "X₂"], + "remaining": ["X₃"], + "dependent": ["X₄"], + "blocks": [ + {"coverage": "partial", "status": "reduced", "labels": ["X₂"]}, + {"coverage": "partial", "status": "kept", "labels": ["X₃"]}, + ], + } + assert report.red_verdict(x) == ( + "Reduced 2 of 3 directions (X₃ remaining); X₄ depends on the others; " + "the section of X₂ covers only part of the positive orthant." + ) assert report.red_verdict({"removed": ["X₁"], "remaining": []}) == "Reduced 1 of 1 direction." -SEC = {"removed": ["X₁", "X₂", "X₃", "X₄"], "remaining": [], "blocks": [ - {"labels": ["X₁"], "type": "scaling", "status": "reduced", "support": ["K", "P"], - "transversal": ["P"], "pins": {"P": "1"}}, - {"labels": ["X₂"], "type": "curved", "status": "reduced", "support": ["kL", "kS"], "face": True, - "section": ["kL = 0"], "pins": {"kL": "0", "kS": "q_1"}, "new_parameters": {"q_1": "kL + kS"}, - "coverage": "total"}, - {"labels": ["X₃"], "type": "curved", "status": "reduced", "support": ["c", "k"], "face": False, - "section": ["c*k = 1"], "pins": {"k": "sqrt(q_2)"}, "new_parameters": {"q_2": "k/c"}, - "coverage": "total", "gauge_note": "a solved entry contains a square root"}, - {"labels": ["X₄"], "type": "curved", "status": "reduced", "support": ["a", "b"], "face": False, - "transversal": ["a"], "pins": {"a": "1", "b": "q_3"}, "new_parameters": {"q_3": "a - b"}, - "coverage": "partial", "solved_domain": {"q_3": "real"}}]} +SEC = { + "removed": ["X₁", "X₂", "X₃", "X₄"], + "remaining": [], + "blocks": [ + { + "labels": ["X₁"], + "type": "scaling", + "status": "reduced", + "support": ["K", "P"], + "transversal": ["P"], + "pins": {"P": "1"}, + }, + { + "labels": ["X₂"], + "type": "curved", + "status": "reduced", + "support": ["kL", "kS"], + "face": True, + "section": ["kL = 0"], + "pins": {"kL": "0", "kS": "q_1"}, + "new_parameters": {"q_1": "kL + kS"}, + "coverage": "total", + }, + { + "labels": ["X₃"], + "type": "curved", + "status": "reduced", + "support": ["c", "k"], + "face": False, + "section": ["c*k = 1"], + "pins": {"k": "sqrt(q_2)"}, + "new_parameters": {"q_2": "k/c"}, + "coverage": "total", + "gauge_note": "a solved entry contains a square root", + }, + { + "labels": ["X₄"], + "type": "curved", + "status": "reduced", + "support": ["a", "b"], + "face": False, + "transversal": ["a"], + "pins": {"a": "1", "b": "q_3"}, + "new_parameters": {"q_3": "a - b"}, + "coverage": "partial", + "solved_domain": {"q_3": "real"}, + }, + ], +} def test_sections_short_list_the_equations_and_point_to_the_details(): out = report.red_section_lines(SEC, 80) - assert out == ["", "Sections:", " {X₁} P = 1", " {X₂} kL = 0", " {X₃} c*k = 1", " {X₄} a = 1", - " summary(detailed=True) explains each section."] - assert report.red_section_lines(SEC, 80, detail_call="summary(x, detailed = TRUE)")[-1] == \ - " summary(x, detailed = TRUE) explains each section." + assert out == [ + "", + "Sections:", + " {X₁} P = 1", + " {X₂} kL = 0", + " {X₃} c*k = 1", + " {X₄} a = 1", + " summary(detailed=True) explains each section.", + ] + assert ( + report.red_section_lines(SEC, 80, detail_call="summary(x, detailed = TRUE)")[-1] + == " summary(x, detailed = TRUE) explains each section." + ) assert "explains each section." in " ".join(report.reduction_summary_lines(SEC, width=80)) def test_a_section_of_several_generators_is_explained_by_its_proof(): - b = {"labels": ["X₁", "X₂"], "type": "curved", "status": "reduced", "support": ["a", "b", "c"], - "face": False, "section": ["a = b", "b = 1"], "transversal": ["a", "b"], - "pins": {"a": "1", "b": "1", "c": "q_1"}, "new_parameters": {"q_1": "a*b*c"}, "coverage": "total"} + b = { + "labels": ["X₁", "X₂"], + "type": "curved", + "status": "reduced", + "support": ["a", "b", "c"], + "face": False, + "section": ["a = b", "b = 1"], + "transversal": ["a", "b"], + "pins": {"a": "1", "b": "1", "c": "q_1"}, + "new_parameters": {"q_1": "a*b*c"}, + "coverage": "total", + } x = {"removed": ["X₁", "X₂"], "remaining": [], "blocks": [b]} txt = "\n".join(report.reduction_summary_lines(x, width=200, detailed=True)) assert "at most once is not proven" in txt - txt = "\n".join(report.reduction_summary_lines({**x, "blocks": [dict(b, injective=True)]}, - width=200, detailed=True)) + txt = "\n".join( + report.reduction_summary_lines({**x, "blocks": [dict(b, injective=True)]}, width=200, detailed=True) + ) assert "The invariants determine each point with a = b, b = 1" in txt and "at most once." in txt - txt = "\n".join(report.reduction_summary_lines({**x, "blocks": [dict(b, reach=True)]}, - width=200, detailed=True)) + txt = "\n".join(report.reduction_summary_lines({**x, "blocks": [dict(b, reach=True)]}, width=200, detailed=True)) assert "graph of these values over a connected set of a, b, and X₁, X₂ are independent" in txt @@ -158,8 +241,11 @@ def test_sections_detailed_explain_each_choice(): def test_a_rank_that_is_not_proven_names_what_it_rests_on(): pj = {"status": "verified", "of": "the unknown inputs", "probability": 1e-8} - rs = {"status": "verified", "probability": 1e-8, - "why": "full rank at a point; the rank modulo the unknown inputs holds at a random point modulo a prime"} + rs = { + "status": "verified", + "probability": 1e-8, + "why": "full rank at a point; the rank modulo the unknown inputs holds at a random point modulo a prime", + } info = {"engine": "modular", "settings": {}, "rank_status": rs, "projection": pj} lines = report.result_lines(res([], rank=5, info=info), width=200) assert lines[0] == "Result: structurally locally identifiable (rank 5 / 5)" diff --git a/tests/test_rest_nonrational.py b/tests/test_rest_nonrational.py index 9a1549d..d312e41 100644 --- a/tests/test_rest_nonrational.py +++ b/tests/test_rest_nonrational.py @@ -35,13 +35,21 @@ def parameter_form(d, drop=()): # ---- Hodgkin-Huxley neuron in current clamp: rest, then a current step -RATES = {"m": ("am*exp(V/kam)", "bm*exp(-V/kbm)"), "h": ("ah*exp(-V/kah)", "bh*exp(V/kbh)"), - "n": ("an*exp(V/kan)", "bn*exp(-V/kbn)")} -HH = {"V": "(Iapp - gNa*m^3*h*(V - ENa) - gK*n^4*(V - EK) - gL*(V - EL))/C", "Iapp": "0", - **{g: f"{a}*(1 - {g}) - {b}*{g}" for g, (a, b) in RATES.items()}} +RATES = { + "m": ("am*exp(V/kam)", "bm*exp(-V/kbm)"), + "h": ("ah*exp(-V/kah)", "bh*exp(V/kbh)"), + "n": ("an*exp(V/kan)", "bn*exp(-V/kbn)"), +} +HH = { + "V": "(Iapp - gNa*m^3*h*(V - ENa) - gK*n^4*(V - EK) - gL*(V - EL))/C", + "Iapp": "0", + **{g: f"{a}*(1 - {g}) - {b}*{g}" for g, (a, b) in RATES.items()}, +} HH_POS = ["C", "gNa", "gK", "gL"] + [p + g for g in "mhn" for p in ("a", "b", "ka", "kb")] -HH_EVENTS = [{"var": "Iapp", "time": "1", "value": "10", "method": "replace"}, - {"var": "Iapp", "time": "6", "value": "0", "method": "replace"}] +HH_EVENTS = [ + {"var": "Iapp", "time": "1", "value": "10", "method": "replace"}, + {"var": "Iapp", "time": "6", "value": "0", "method": "replace"}, +] def hh(obs, equilibrate): @@ -52,10 +60,10 @@ def hh(obs, equilibrate): for g, (a, b) in RATES.items(): a0, b0 = a.replace("V", "V0"), b.replace("V", "V0") trafo[g] = f"({a0})/(({a0}) + ({b0}))" - trafo["EL"] = (f"V0 + (gNa*({trafo['m']})^3*({trafo['h']})*(V0 - ENa) + " - f"gK*({trafo['n']})^4*(V0 - EK))/gL") - return det(HH, obs, trafo=trafo, events=HH_EVENTS, inputs=["Iapp"], equilibrate=equilibrate, - positive=HH_POS, cores=4) + trafo["EL"] = f"V0 + (gNa*({trafo['m']})^3*({trafo['h']})*(V0 - ENa) + gK*({trafo['n']})^4*(V0 - EK))/gL" + return det( + HH, obs, trafo=trafo, events=HH_EVENTS, inputs=["Iapp"], equilibrate=equilibrate, positive=HH_POS, cores=4 + ) def test_hodgkin_huxley_at_rest(): @@ -74,8 +82,18 @@ def test_hodgkin_huxley_offset_at_rest(): assert d["level"] == "exact" assert set(d["support"]) == {"EK", "EL", "ENa", "Vlj", "am", "bm", "ah", "bh", "an", "bn"} # the direction of the offset in closed form - shift = {"EK": "1", "EL": "1", "ENa": "1", "Vlj": "-1", "am": "-am/kam", "bm": "bm/kbm", "ah": "ah/kah", - "bh": "-bh/kbh", "an": "-an/kan", "bn": "bn/kbn"} + shift = { + "EK": "1", + "EL": "1", + "ENa": "1", + "Vlj": "-1", + "am": "-am/kam", + "bm": "bm/kbm", + "ah": "ah/kah", + "bh": "-bh/kbh", + "an": "-an/kan", + "bn": "bn/kbn", + } assert same_direction(d["generator"], shift) # the same direction with the resting state given through the trafo hand = hh({"y": "V + Vlj"}, False) @@ -87,18 +105,40 @@ def test_hodgkin_huxley_offset_at_rest(): def test_hodgkin_huxley_offset_banks_per_entry(monkeypatch): # each entry fitted on points that move only the leaves of the entry from the base point import symident.detection.forward as fw + monkeypatch.setattr(fw, "_UNION_CAP", 0) - eq = det(HH, {"y": "V + Vlj"}, events=HH_EVENTS, inputs=["Iapp"], equilibrate=True, positive=HH_POS, - cores=4, control=si.reconst_control(relevance_cap_dir=1)) + eq = det( + HH, + {"y": "V + Vlj"}, + events=HH_EVENTS, + inputs=["Iapp"], + equilibrate=True, + positive=HH_POS, + cores=4, + control=si.reconst_control(relevance_cap_dir=1), + ) (d,) = eq.symmetries assert d["level"] == "exact" and eq.info["rank_status"]["status"] == "proven" - assert same_direction(d["generator"], {"EK": "1", "EL": "1", "ENa": "1", "Vlj": "-1", "am": "-am/kam", - "bm": "bm/kbm", "ah": "ah/kah", "bh": "-bh/kbh", "an": "-an/kan", - "bn": "bn/kbn"}) + assert same_direction( + d["generator"], + { + "EK": "1", + "EL": "1", + "ENa": "1", + "Vlj": "-1", + "am": "-am/kam", + "bm": "bm/kbm", + "ah": "ah/kah", + "bh": "-bh/kbh", + "an": "-an/kan", + "bn": "bn/kbn", + }, + ) # ---- small models: a trigonometric and a logarithmic term of a state at rest + def test_trigonometric_state_at_rest(): f = {"x": "p - k*sin(x - phi) + u", "u": "0"} eq = det(f, {"y": "x + c"}, equilibrate=True, positive=["k"]) @@ -113,8 +153,7 @@ def test_logarithmic_state_at_rest(): f = {"x": "a*(1 + u) - b*x*log(x/K)", "u": "0"} pos = ["a", "b", "K", "s", "x"] eq = det(f, {"y": "s*x"}, equilibrate=True, positive=pos) - hand = det(f, {"y": "s*x"}, trafo={"x": "x0", "a": "b*x0*log(x0/K)", "u": "0"}, - positive=["b", "K", "s", "x", "x0"]) + hand = det(f, {"y": "s*x"}, trafo={"x": "x0", "a": "b*x0*log(x0/K)", "u": "0"}, positive=["b", "K", "s", "x", "x0"]) assert (eq.rank, eq.dim) == (hand.rank, hand.dim) == (3, 4) (d,) = eq.symmetries assert d["type"] == "scaling" and set(d["generator"]) == {"a", "K", "s"} @@ -154,6 +193,7 @@ def test_state_only_inside_a_term_is_drawn_as_by_hand(): # ---- models without a resting state + def test_no_resting_state(): with pytest.raises(InputError, match="balance of x at rest"): det({"x": "k + u", "z": "x - d*z", "u": "0"}, {"y": "z"}, equilibrate=True) diff --git a/tests/test_rjson.py b/tests/test_rjson.py index cb02558..b3abab9 100644 --- a/tests/test_rjson.py +++ b/tests/test_rjson.py @@ -12,9 +12,15 @@ def test_kwargs_of_maps_host_spellings(): - kw = rjson.kwargs_of({"f": {"x": "-k*x"}, "trafo": None, "gauge_preference": "AUTO", - "control": {"term_cap": 7, "degree_cap": None}, - "unknown": 1}) + kw = rjson.kwargs_of( + { + "f": {"x": "-k*x"}, + "trafo": None, + "gauge_preference": "AUTO", + "control": {"term_cap": 7, "degree_cap": None}, + "unknown": 1, + } + ) assert set(kw) == {"f", "gauge_preference", "control"} assert kw["gauge_preference"] is None assert kw["control"]["term_cap"] == 7 @@ -22,10 +28,21 @@ def test_kwargs_of_maps_host_spellings(): def test_dumps_cleans_values_json_cannot_hold(): - out = json.loads(rjson._dumps({"a": float("inf"), 1: (1, 2), "f": len, "n": np.int64(3), - "r": np.float64(0.5), "v": np.arange(2), "s": {5}, "q": Fraction(1, 2)})) - assert out == {"a": "inf", "1": [1, 2], "n": 3, "r": 0.5, "v": [0, 1], "s": [5], - "q": "1/2"} + out = json.loads( + rjson._dumps( + { + "a": float("inf"), + 1: (1, 2), + "f": len, + "n": np.int64(3), + "r": np.float64(0.5), + "v": np.arange(2), + "s": {5}, + "q": Fraction(1, 2), + } + ) + ) + assert out == {"a": "inf", "1": [1, 2], "n": 3, "r": 0.5, "v": [0, 1], "s": [5], "q": "1/2"} def test_detect_and_reduce_round_trip(monkeypatch): @@ -67,6 +84,7 @@ def test_the_json_loop_composes_a_model_trafo(): def test_the_json_reduction_takes_the_declared_domain_of_the_detection(): import symident as si + f, g, pos = {"x": "-k*x", "z": "a*x - e*z"}, {"y": "s*z"}, ["k", "e", "s", "a"] r = si.detect(si.Model(f, g, positive=pos), reconstruct=True) out = rjson.detect_json(json.dumps({"f": f, "g": g, "positive": pos, "reconstruct": True})) diff --git a/tests/test_select.py b/tests/test_select.py index 995ee8f..bd5b893 100644 --- a/tests/test_select.py +++ b/tests/test_select.py @@ -18,8 +18,13 @@ def model(extra=None, obs=None, odes=None, rest=False): if extra is not None: observables[extra[0]] = extra[1] start = {} if rest else {"x": "0"} - return si.Model(odes or {"x": "k1*u - k2*x"}, observables, trafo=[dict(start, u=str(c + 1)) for c in range(K)], - conditions={"rows": [f"c{c}" for c in range(K)], "cols": {}}, equilibrate=rest) + return si.Model( + odes or {"x": "k1*u - k2*x"}, + observables, + trafo=[dict(start, u=str(c + 1)) for c in range(K)], + conditions={"rows": [f"c{c}" for c in range(K)], "cols": {}}, + equilibrate=rest, + ) def run(m, monkeypatch, on): @@ -78,6 +83,7 @@ def test_a_direction_that_fails_on_a_condition_left_out_brings_the_condition_bac def drop_29(sel): sel["kept"] = [c for c in sel["kept"] if c != 29] return sel + monkeypatch.setattr(select, "choose", lambda *a, **k: drop_29(choose(*a, **k))) monkeypatch.setattr(select, "choose_resting", lambda *a, **k: drop_29(choose_resting(*a, **k))) on = run(m, monkeypatch, True) @@ -89,6 +95,10 @@ def drop_29(sel): def test_few_conditions_are_all_analyzed(monkeypatch): - m = si.Model({"x": "k1*u - k2*x"}, [{"y": "s*x"}] * 3, trafo=[{"x": "0", "u": str(c + 1)} for c in range(3)], - conditions={"rows": ["a", "b", "c"], "cols": {}}) + m = si.Model( + {"x": "k1*u - k2*x"}, + [{"y": "s*x"}] * 3, + trafo=[{"x": "0", "u": str(c + 1)} for c in range(3)], + conditions={"rows": ["a", "b", "c"], "cols": {}}, + ) assert run(m, monkeypatch, True).info["selection"] is None diff --git a/tests/test_series_start.py b/tests/test_series_start.py index de35b1b..9497e05 100644 --- a/tests/test_series_start.py +++ b/tests/test_series_start.py @@ -22,6 +22,7 @@ def supports(res): # ---- an independent evaluation: truncated series in t with gradients, by Picard steps ---- + class _Ser: """Series sum_j c[j] t^(lo + j) mod P; every c[j] holds the value and the gradient.""" @@ -214,11 +215,14 @@ def test_ratio_matches_shifted_start(): F_POW = {"x": "p - m*x"} -@pytest.mark.parametrize("obs, rank, dim, sup", [ - ("x^a", 3, 3, []), - ("q*x^a + x", 4, 4, []), - ("x^a/(g^a + x^a)", 3, 4, [("g", "p")]), -]) +@pytest.mark.parametrize( + "obs, rank, dim, sup", + [ + ("x^a", 3, 3, []), + ("q*x^a + x", 4, 4, []), + ("x^a/(g^a + x^a)", 3, 4, [("g", "p")]), + ], +) def test_power_of_state_at_zero(obs, rank, dim, sup): res = det(F_POW, {"y": obs}, trafo={"x": "0"}) assert (res.rank, res.dim) == (rank, dim) @@ -238,10 +242,13 @@ def test_power_with_a_second_state(): assert supports(res) == [("g", "p")] -@pytest.mark.parametrize("f, g", [ - (F_POW, {"y": "x^a/(g^a + x^a)"}), - ({"x": "p - m*x", "z": "n*x^a/(g^a + x^a) - k*z"}, {"y": "z"}), -]) +@pytest.mark.parametrize( + "f, g", + [ + (F_POW, {"y": "x^a/(g^a + x^a)"}), + ({"x": "p - m*x", "z": "n*x^a/(g^a + x^a) - k*z"}, {"y": "z"}), + ], +) def test_power_scaling_exact(f, g): # the scaling of the base moves the power by the weight times the exponent; it bounds the rank res = det(f, g, trafo={x: "0" for x in f}) diff --git a/tests/test_settings.py b/tests/test_settings.py index 5b00886..39731a8 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -27,8 +27,7 @@ def test_result_records_control_switches_and_primes(): with warnings.catch_warnings(): warnings.simplefilter("error") with si.switches(NOJET=True): - r = si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}), - control=si.reconst_control(degree_cap=3, seed=5)) + r = si.detect(si.Model({"x": "-k*x"}, {"y": "s*x"}), control=si.reconst_control(degree_cap=3, seed=5)) st = r.info["settings"] assert st["control"]["degree_cap"] == 3 and st["control"]["seed"] == 5 assert st["switches"]["NOJET"] == "1" @@ -40,10 +39,14 @@ def test_route_errors_are_recorded_or_raised(monkeypatch): def broken(*a, **k): raise RuntimeError("broken field setup") + monkeypatch.setattr(reconstruct, "field_setup", broken) - model = si.Model({"R": "-kR*R", "S": "kact*R/(1 + kinh*I) - kd*S", "I": "b + ks*S - dI*I"}, - {"z": "s2*S"}, events=[{"var": "R", "time": 0, "value": "d0", "method": "add"}], - conditions={"rows": ["a", "b"], "cols": {"d0": [1, 2]}}) + model = si.Model( + {"R": "-kR*R", "S": "kact*R/(1 + kinh*I) - kd*S", "I": "b + ks*S - dI*I"}, + {"z": "s2*S"}, + events=[{"var": "R", "time": 0, "value": "d0", "method": "add"}], + conditions={"rows": ["a", "b"], "cols": {"d0": [1, 2]}}, + ) with si.switches(DEBUG="0"): r = si.detect(model, reconstruct=True, equilibrate=True) assert any("broken field setup" in e for e in r.info["errors"]) @@ -62,6 +65,7 @@ def test_a_retired_route_switch_is_unknown(): import symident as si from symident import state + assert "NOFORK" not in state.SWITCHES and "NOFWDSEED" in state.SWITCHES with si.switches(NOFORK=True), pytest.warns(UserWarning, match="NOFORK"): si.detect(si.Model({"x": "-k*x"}, {"y": "x"})) diff --git a/tests/test_switching.py b/tests/test_switching.py index 21cfa0e..b3db2a2 100644 --- a/tests/test_switching.py +++ b/tests/test_switching.py @@ -15,9 +15,16 @@ def det(f, g, **kw): kw.setdefault("cores", 1) - model = si.Model(f, g, trafo=kw.pop("trafo", None), fixed=kw.pop("fixed", ()), - events=kw.pop("events", None), inputs=kw.pop("inputs", ()), - conditions=kw.pop("conditions", None), regimes=kw.pop("regimes", None)) + model = si.Model( + f, + g, + trafo=kw.pop("trafo", None), + fixed=kw.pop("fixed", ()), + events=kw.pop("events", None), + inputs=kw.pop("inputs", ()), + conditions=kw.pop("conditions", None), + regimes=kw.pop("regimes", None), + ) return si.detect(model, **kw) @@ -35,8 +42,8 @@ def same_span(res, expected): pt = {spy.Symbol(z): spy.Rational(rng.randint(2, 60), rng.randint(2, 60)) for z in coords} def col(g): - return spy.Matrix([spy.sympify(str(g.get(z, 0)).replace("^", "**")).xreplace(pt) - for z in coords]) + return spy.Matrix([spy.sympify(str(g.get(z, 0)).replace("^", "**")).xreplace(pt) for z in coords]) + got = [col(s.sympy()) for s in res.symmetries] want = [col(g) for g in expected] assert len(got) == len(want) == res.dim - res.rank @@ -45,34 +52,49 @@ def col(g): assert A.rank() == B.rank() == spy.Matrix.hstack(A, B).rank() == len(want) -@pytest.mark.parametrize("text, point, expect", [ - ("piecewise(a, x > t1 && x < t2, b)", {"x": "1.5", "t1": "1", "t2": "2"}, "a"), - ("piecewise(a, x > t1 && x < t2, b)", {"x": "3", "t1": "1", "t2": "2"}, "b"), - ("piecewise(a, x < t1 || x > t2, b)", {"x": "3", "t1": "1", "t2": "2"}, "a"), - ("piecewise(a, x < t1, b, x < t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "b"), - ("piecewise(a, x < t1, b, x < t2)", {"x": "3", "t1": "1", "t2": "2"}, "0"), - ("ifelse(!(x > t1), a, b)", {"x": "3", "t1": "1"}, "b"), - ("Heaviside(x - t1)*a", {"x": "3", "t1": "1"}, "a"), - ("sign(t1 - x)*a", {"x": "3", "t1": "1"}, "-a"), - ("abs(t1 - x)", {"x": "3", "t1": "1"}, "2"), - ("max(x, t1, t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "2"), - ("min(x, t1, t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "1"), - ("-x^2 + (x >= t1)", {"x": "3", "t1": "1"}, "-8"), -]) +@pytest.mark.parametrize( + "text, point, expect", + [ + ("piecewise(a, x > t1 && x < t2, b)", {"x": "1.5", "t1": "1", "t2": "2"}, "a"), + ("piecewise(a, x > t1 && x < t2, b)", {"x": "3", "t1": "1", "t2": "2"}, "b"), + ("piecewise(a, x < t1 || x > t2, b)", {"x": "3", "t1": "1", "t2": "2"}, "a"), + ("piecewise(a, x < t1, b, x < t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "b"), + ("piecewise(a, x < t1, b, x < t2)", {"x": "3", "t1": "1", "t2": "2"}, "0"), + ("ifelse(!(x > t1), a, b)", {"x": "3", "t1": "1"}, "b"), + ("Heaviside(x - t1)*a", {"x": "3", "t1": "1"}, "a"), + ("sign(t1 - x)*a", {"x": "3", "t1": "1"}, "-a"), + ("abs(t1 - x)", {"x": "3", "t1": "1"}, "2"), + ("max(x, t1, t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "2"), + ("min(x, t1, t2)", {"x": "1.5", "t1": "1", "t2": "2"}, "1"), + ("-x^2 + (x >= t1)", {"x": "3", "t1": "1"}, "-8"), + ], +) def test_parse(text, point, expect): sw = Switches(True) e = sw.parse(text) got = value(sw, e, point) - assert spy.simplify(got - spy.sympify(expect).xreplace( - {spy.Symbol(k): spy.Rational(v) for k, v in point.items()})) == 0 - - -@pytest.mark.parametrize("text, expect", [ - ("log(x, 2)", "log(x)/log(2)"), ("log10(x)", "log(x)/log(10)"), ("log2(x)", "log(x)/log(2)"), - ("exp10(x)", "10**x"), ("sin(x)", "sin(x)"), ("foo(x)", "foo(x)"), - ("ln(x)", "log(x)"), ("exp2(x)", "2**x"), ("acot(x)", "atan(1/x)"), - ("pow(x, 3) + cbrt(x)", "x**3 + x**(1/3)"), ("cot(x) + erf(x)", "cot(x) + erf(x)"), -]) + assert ( + spy.simplify(got - spy.sympify(expect).xreplace({spy.Symbol(k): spy.Rational(v) for k, v in point.items()})) + == 0 + ) + + +@pytest.mark.parametrize( + "text, expect", + [ + ("log(x, 2)", "log(x)/log(2)"), + ("log10(x)", "log(x)/log(10)"), + ("log2(x)", "log(x)/log(2)"), + ("exp10(x)", "10**x"), + ("sin(x)", "sin(x)"), + ("foo(x)", "foo(x)"), + ("ln(x)", "log(x)"), + ("exp2(x)", "2**x"), + ("acot(x)", "atan(1/x)"), + ("pow(x, 3) + cbrt(x)", "x**3 + x**(1/3)"), + ("cot(x) + erf(x)", "cot(x) + erf(x)"), + ], +) def test_parse_functions_without_switch(text, expect): sw = Switches(True) assert sw.parse(text) == spy.sympify(expect) @@ -134,8 +156,7 @@ def test_hidden_state_across_thresholds(): # (ii) a parameter that acts only in one regime, on a state hidden there, is identifiable # once another regime observes that state: a field commuting with both regimes keeps # their mixed Lie derivatives - f = {"x": "-k*x + piecewise(0, x > c1, z)", - "z": "piecewise(-a*z, x > c1, -b*z, x > c2, 0)"} + f = {"x": "-k*x + piecewise(0, x > c1, z)", "z": "piecewise(-a*z, x > c1, -b*z, x > c2, 0)"} r = det(f, {"y": "x"}, trafo={"x": "2", "z": "1"}) assert r.identifiable and r.info["coordinates"] == ["a", "b", "c1", "c2", "k"] @@ -163,14 +184,18 @@ def test_surface_kept_or_moved(): def test_time_event_and_input(): # (v) events on an input: a symmetry keeps the event times and the input values f = {"x": "b*u - piecewise(k1, x > c, k2)*x", "u": "0"} - ev = [{"var": "u", "time": 0, "value": 0, "method": "replace"}, - {"var": "u", "time": 1, "value": 1, "method": "replace"}] + ev = [ + {"var": "u", "time": 0, "value": 0, "method": "replace"}, + {"var": "u", "time": 1, "value": 1, "method": "replace"}, + ] r = det(f, {"y": "s*x"}, inputs=["u"], events=ev, reconstruct=True) assert (r.rank, r.dim) == (5, 6) same_span(r, [{"x": "x", "b": "b", "c": "c", "s": "-s"}]) # an event time in a parameter is kept fixed by every symmetry - ev = [{"var": "u", "time": 0, "value": 0, "method": "replace"}, - {"var": "u", "time": "te", "value": 1, "method": "replace"}] + ev = [ + {"var": "u", "time": 0, "value": 0, "method": "replace"}, + {"var": "u", "time": "te", "value": 1, "method": "replace"}, + ] r = det(f, {"y": "s*x"}, inputs=["u"], events=ev, reconstruct=True) assert (r.rank, r.dim) == (6, 7) same_span(r, [{"x": "x", "b": "b", "c": "c", "s": "-s"}]) @@ -208,8 +233,7 @@ def test_infeasible_regime_is_excluded(): sw = r.info["switching"] assert len(sw["regimes"]) == 3 and len(sw["excluded"]) == 1 assert r.info["coordinates"] == ["x", "c1", "d", "k1", "k3"] - assert sw["conditions"][0]["visibility"] == {"c1 - x = 0": "visible", - "c1 + d - x = 0": "invisible"} + assert sw["conditions"][0]["visibility"] == {"c1 - x = 0": "visible", "c1 + d - x = 0": "invisible"} assert (r.rank, r.dim) == (4, 5) same_span(r, [{"d": "1"}]) @@ -241,8 +265,7 @@ def test_named_regimes(): assert list(r.info["assumptions"]["starts"].values()) == [["c - x < 0 at the start"]] # a start that contradicts the known initial values is an error with pytest.raises(ValueError, match="initial values give"): - det({"x": "piecewise(-k1*x, x > 1, -k2*x)"}, {"y": "x"}, trafo={"x": "2"}, - regimes=["x < 1"]) + det({"x": "piecewise(-k1*x, x > 1, -k2*x)"}, {"y": "x"}, trafo={"x": "2"}, regimes=["x < 1"]) # both regimes named: the result of the rule over all regimes r = det(f, {"y": "x"}, trafo={"x": "2"}, regimes=["x > c", "x < c"]) assert r.identifiable @@ -260,25 +283,34 @@ def test_unsupported(): _ROOT2 = [{"var": "x", "root": "(x - c)*(x - d)", "value": "0", "method": "replace"}] -@pytest.mark.parametrize("f, kw, match", [ - (_SW, {"free_initial": ["x"]}, "does not support `free_initial`"), - (_SW, {"engine": "symbolic"}, 'needs engine="modular"'), - ({"time": "1", **_SW}, {}, "clashes with the clock"), - (_SW, {"regimes": {"zz": ["x > c"]}}, "unknown conditions: zz"), - (_SW, {"regimes": "x > c"}, "a list of regimes or a dict"), - (_SW, {"regimes": ["x > d"]}, "names no switching surface"), - (_SW, {"regimes": [["x > c", "x < c"]]}, "names both sides of c - x = 0"), - ({"x": "-k*x"}, {"regimes": ["x > c"]}, "has no switch that the declared signs leave open"), - ({"x": "piecewise(-k1*x, x > c1, -k2*x, x > c1 + d, -k3*x)"}, - {"regimes": [["x < c1", "x > c1 + d"]]}, "names no feasible regime"), - ({"x": "ifelse(x > c, -k1*x)"}, {}, r"ifelse\(\) needs three arguments"), - ({"x": "piecewise(-k1*x, k1 - k2, -k2*x)"}, {}, "is not a comparison"), - ({"x": "piecewise(-k1*x, abs(x - c) > d, -k2*x)"}, {}, "condition on a switched expression"), - ({"x": "a - k*x"}, {"trafo": {"x": "0"}, "events": _ROOT2}, "is not one switching surface"), - ({"x": "-k*x + " + " + ".join(f"piecewise(a{i}, x > c{i}, 0)" for i in range(13))}, {}, - "8192 sign patterns, more than 4096"), - ({"x": "b - piecewise(k1*x^5 + x, x > c, k2*x)"}, {"equilibrate": True}, "has no closed form"), -]) +@pytest.mark.parametrize( + "f, kw, match", + [ + (_SW, {"free_initial": ["x"]}, "does not support `free_initial`"), + (_SW, {"engine": "symbolic"}, 'needs engine="modular"'), + ({"time": "1", **_SW}, {}, "clashes with the clock"), + (_SW, {"regimes": {"zz": ["x > c"]}}, "unknown conditions: zz"), + (_SW, {"regimes": "x > c"}, "a list of regimes or a dict"), + (_SW, {"regimes": ["x > d"]}, "names no switching surface"), + (_SW, {"regimes": [["x > c", "x < c"]]}, "names both sides of c - x = 0"), + ({"x": "-k*x"}, {"regimes": ["x > c"]}, "has no switch that the declared signs leave open"), + ( + {"x": "piecewise(-k1*x, x > c1, -k2*x, x > c1 + d, -k3*x)"}, + {"regimes": [["x < c1", "x > c1 + d"]]}, + "names no feasible regime", + ), + ({"x": "ifelse(x > c, -k1*x)"}, {}, r"ifelse\(\) needs three arguments"), + ({"x": "piecewise(-k1*x, k1 - k2, -k2*x)"}, {}, "is not a comparison"), + ({"x": "piecewise(-k1*x, abs(x - c) > d, -k2*x)"}, {}, "condition on a switched expression"), + ({"x": "a - k*x"}, {"trafo": {"x": "0"}, "events": _ROOT2}, "is not one switching surface"), + ( + {"x": "-k*x + " + " + ".join(f"piecewise(a{i}, x > c{i}, 0)" for i in range(13))}, + {}, + "8192 sign patterns, more than 4096", + ), + ({"x": "b - piecewise(k1*x^5 + x, x > c, k2*x)"}, {"equilibrate": True}, "has no closed form"), + ], +) def test_documented_errors(f, kw, match): # each unsupported or contradictory input stops before any analysis with pytest.raises(ValueError, match=match): @@ -292,13 +324,18 @@ def test_surface_without_a_rational_point_is_undecided(): assert r.info["switching"]["conditions"][0]["visibility"] == {"x^2 - 2 = 0": "undecided"} -@pytest.mark.parametrize("f, g, events, weights", [ - ({"x": "-k*x"}, {"y": "piecewise(s1*x, x > c, s2*x)"}, None, - {"c": "1", "s1": "-1", "s2": "-1", "x": "1"}), - ({"x": "piecewise(-k1*x, x > c, -k2*x)"}, {"y": "s*x"}, - [{"var": "x", "time": "1", "value": "2", "method": "multiply", "root": None}], - {"c": "1", "s": "-1", "x": "1"}), -]) +@pytest.mark.parametrize( + "f, g, events, weights", + [ + ({"x": "-k*x"}, {"y": "piecewise(s1*x, x > c, s2*x)"}, None, {"c": "1", "s1": "-1", "s2": "-1", "x": "1"}), + ( + {"x": "piecewise(-k1*x, x > c, -k2*x)"}, + {"y": "s*x"}, + [{"var": "x", "time": "1", "value": "2", "method": "multiply", "root": None}], + {"c": "1", "s": "-1", "x": "1"}, + ), + ], +) def test_scaling_through_a_switched_observable_or_event(f, g, events, weights): # a joint scaling of state and threshold survives a switched observable and a # multiplicative event alike @@ -316,8 +353,14 @@ def test_heaviside_jump_observed_directly(): def test_regimes_per_condition(): # each condition keeps to the regime it names, so neither sees a surface cg = {"rows": ["a", "b"], "cols": {"x0": [3, 1]}} - r = det({"x": "piecewise(-k1*x, x > 2, -k2*x)"}, {"y": "x"}, trafo={"x": "x0"}, fixed=["x0"], - conditions=cg, regimes={"a": ["x > 2"], "b": ["x < 2"]}) + r = det( + {"x": "piecewise(-k1*x, x > 2, -k2*x)"}, + {"y": "x"}, + trafo={"x": "x0"}, + fixed=["x0"], + conditions=cg, + regimes={"a": ["x > 2"], "b": ["x < 2"]}, + ) assert r.identifiable and r.info["coordinates"] == ["k1", "k2"] assert [c["visibility"] for c in r.info["switching"]["conditions"]] == [{}, {}] @@ -344,6 +387,7 @@ def test_root_event(): def test_visibility_of_a_step_input_is_shared_across_switching_times(monkeypatch): # the jets that show a switch are computed once for conditions that differ only in the switching time from symident.detection import hybrid + calls = [] series = hybrid.output_series monkeypatch.setattr(hybrid, "output_series", lambda *a, **k: calls.append(1) or series(*a, **k)) @@ -356,6 +400,7 @@ def test_visibility_of_a_step_input_is_shared_across_switching_times(monkeypatch def test_output_series_are_the_taylor_coefficients_modulo_p(): from symident.sym.taylor import NoSeriesError, output_series + x, k, s = spy.symbols("x k s") p = 1000003 (h,) = output_series({x: -k * x}, [s * x / (1 + x)], {x: 2, k: 3, s: 5}, 3, p) @@ -367,13 +412,22 @@ def test_output_series_are_the_taylor_coefficients_modulo_p(): def test_a_switched_input_model_at_rest_keeps_its_directions(): f = {"x1": "kb + kin*u - (k1 + piecewise(kl, x1 > thr, kl2))*x1", "x2": "k1*x1 - k2*x2", "u": "0"} - m = si.Model(f, {"y": "s*x2"}, inputs=["u"], regimes=["x1 > thr"], - events=[{"var": "u", "time": 0, "value": "dose", "method": "replace"}], - conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}) + m = si.Model( + f, + {"y": "s*x2"}, + inputs=["u"], + regimes=["x1 > thr"], + events=[{"var": "u", "time": 0, "value": "dose", "method": "replace"}], + conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}, + ) r = si.detect(m, equilibrate=True, reconstruct=True) assert (r.rank, r.dim) == (4, 8) - assert sorted(sorted(s.support) for s in r.symmetries) == \ - [["k1", "kb", "kin", "kl"], ["kb", "kin", "s"], ["kl2"], ["thr"]] + assert sorted(sorted(s.support) for s in r.symmetries) == [ + ["k1", "kb", "kin", "kl"], + ["kb", "kin", "s"], + ["kl2"], + ["thr"], + ] def test_a_field_with_integer_weights_is_a_scaling(): @@ -384,8 +438,11 @@ def test_a_field_with_integer_weights_is_a_scaling(): def test_a_direction_the_rule_does_not_prove_is_a_candidate_not_a_symmetry(): - m = si.Model({"x": "-k*x", "z": "a"}, {"y": "s*x"}, - events=[{"var": "x", "root": "z - c", "value": "x0", "method": "replace"}]) + m = si.Model( + {"x": "-k*x", "z": "a"}, + {"y": "s*x"}, + events=[{"var": "x", "root": "z - c", "value": "x0", "method": "replace"}], + ) r = si.detect(m, reconstruct=True) assert {s.level for s in r.symmetries} == {"exact"} cands = r.info["switching"]["candidates"] @@ -396,10 +453,16 @@ def test_a_direction_the_rule_does_not_prove_is_a_candidate_not_a_symmetry(): def test_directions_through_a_condition_and_a_root_are_proven(): - m = si.Model({"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, {"y": "s*x2"}, - inputs=["u"], events=[{"var": "u", "time": 0, "value": "dose", "method": "replace"}, - {"var": "x2", "root": "x1 - c", "value": "0", "method": "replace"}], - conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}) + m = si.Model( + {"x1": "kb + kin*u - (k1 + kl)*x1", "x2": "k1*x1 - k2*x2", "u": "0"}, + {"y": "s*x2"}, + inputs=["u"], + events=[ + {"var": "u", "time": 0, "value": "dose", "method": "replace"}, + {"var": "x2", "root": "x1 - c", "value": "0", "method": "replace"}, + ], + conditions={"rows": ["low", "high"], "cols": {"dose": [1, 10]}}, + ) r = si.detect(m, equilibrate=True, reconstruct=True) assert (r.rank, r.dim) == (5, 7) and {s.level for s in r.symmetries} == {"exact"} assert len(r.symmetries) == r.dim - r.rank and not r.info["switching"]["candidates"] @@ -407,8 +470,11 @@ def test_directions_through_a_condition_and_a_root_are_proven(): def test_a_direction_that_moves_a_root_surface_is_no_symmetry(): - m = si.Model({"x": "-k*x", "z": "a"}, {"y": "s*x"}, - events=[{"var": "x", "root": "z - c", "value": "x0", "method": "replace"}]) + m = si.Model( + {"x": "-k*x", "z": "a"}, + {"y": "s*x"}, + events=[{"var": "x", "root": "z - c", "value": "x0", "method": "replace"}], + ) r = si.detect(m, reconstruct=True) assert all(s.level == "exact" for s in r.symmetries) assert {"a", "z"} not in [set(s.support) for s in r.symmetries] @@ -437,17 +503,35 @@ def _brief(r): return r.rank, r.dim, r.info["coordinates"], sorted((s.type, s.level) for s in r.symmetries) -@pytest.mark.parametrize("clock, plain", [ - (dict(trafo={"x": "a + time"}), dict(trafo={"x": "a"})), - (dict(trafo={"x": "1"}, events=[{"var": "x", "time": 2, "value": "c2*time", "method": "add"}]), - dict(trafo={"x": "1"}, events=[{"var": "x", "time": 2, "value": "2*c2", "method": "add"}])), - (dict(trafo={"x": "1", "k1": "a*time"}), dict(trafo={"x": "1"}, f={"x": "piecewise(-a*time*x, x > thr, -k2*x)"})), - (dict(trafo={"x": "1"}, events=[{"var": "x", "time": "tau", "value": "c2", "method": "add"}], - conditions={"rows": ["a", "b"], "cols": {"tau": [0, 1]}}), - dict(trafo={"x": "1"}, events=[{"var": "x", "time": "0", "value": "c2", "method": "add", "cond": [0]}, - {"var": "x", "time": "1", "value": "c2", "method": "add", "cond": [1]}], - conditions={"rows": ["a", "b"], "cols": {}})), -]) +@pytest.mark.parametrize( + "clock, plain", + [ + (dict(trafo={"x": "a + time"}), dict(trafo={"x": "a"})), + ( + dict(trafo={"x": "1"}, events=[{"var": "x", "time": 2, "value": "c2*time", "method": "add"}]), + dict(trafo={"x": "1"}, events=[{"var": "x", "time": 2, "value": "2*c2", "method": "add"}]), + ), + ( + dict(trafo={"x": "1", "k1": "a*time"}), + dict(trafo={"x": "1"}, f={"x": "piecewise(-a*time*x, x > thr, -k2*x)"}), + ), + ( + dict( + trafo={"x": "1"}, + events=[{"var": "x", "time": "tau", "value": "c2", "method": "add"}], + conditions={"rows": ["a", "b"], "cols": {"tau": [0, 1]}}, + ), + dict( + trafo={"x": "1"}, + events=[ + {"var": "x", "time": "0", "value": "c2", "method": "add", "cond": [0]}, + {"var": "x", "time": "1", "value": "c2", "method": "add", "cond": [1]}, + ], + conditions={"rows": ["a", "b"], "cols": {}}, + ), + ), + ], +) def test_a_switch_reads_the_clock_and_the_event_times_of_each_condition(clock, plain): f = {"x": "piecewise(-k1*x, x > thr, -k2*x)"} clock, plain = dict(clock), dict(plain) @@ -457,15 +541,22 @@ def test_a_switch_reads_the_clock_and_the_event_times_of_each_condition(clock, p def test_every_copy_of_a_switch_starts_its_inputs_by_an_event(monkeypatch): from symident.detection import hybrid + rows, build = {}, hybrid._rows_model def keep(*a): rows.update(build(*a)) return rows + monkeypatch.setattr(hybrid, "_rows_model", keep) f = {"x": "piecewise(-k1*x*u, x > thr, -k2*x)", "u": "0"} - det(f, {"y": "c*x"}, inputs=["u"], trafo={"x": "1"}, - events=[{"var": "u", "time": 0, "value": "w", "method": "replace"}]) + det( + f, + {"y": "c*x"}, + inputs=["u"], + trafo={"x": "1"}, + events=[{"var": "u", "time": 0, "value": "w", "method": "replace"}], + ) starts = [e for e in rows["events"] if e["var"] == "u"] assert not any("u" in t for t in rows["trafo"]) and len(rows["trafo"]) > 4 assert sorted(e["cond"][0] for e in starts) == list(range(len(rows["trafo"]))) @@ -498,9 +589,14 @@ def test_every_regime_enters_a_start_and_a_switched_copy(): from types import SimpleNamespace from symident.detection.hybrid import _uncovered + cd = SimpleNamespace(name="c1", regimes=[[1], [-1]]) - full = [{"cd": cd, "sides": [1]}, {"cd": cd, "sides": [1], "switch": (1, [-1])}, - {"cd": cd, "sides": [-1]}, {"cd": cd, "sides": [-1], "switch": (1, [1])}] + full = [ + {"cd": cd, "sides": [1]}, + {"cd": cd, "sides": [1], "switch": (1, [-1])}, + {"cd": cd, "sides": [-1]}, + {"cd": cd, "sides": [-1], "switch": (1, [1])}, + ] st = SimpleNamespace(conds=[cd], unknown=[]) assert _uncovered(st, full) == [] assert _uncovered(st, full[:2]) == [("c1", [1], "switched"), ("c1", [-1], "start")] @@ -524,8 +620,7 @@ def test_fresh_coordinates_that_drop_rank_together_are_checked_at_a_random_point def test_rows_of_full_rank_without_fresh_coordinates_prove_the_rank(): k = "piecewise(k1, w > 1, k2)" - r = det({"w": "-w", "x1": f"-{k}*x1", "x2": f"-{k}*x2"}, {"y1": "w", "y2": "x1 + x2"}, - trafo={"w": "2", "x1": "1"}) + r = det({"w": "-w", "x1": f"-{k}*x1", "x2": f"-{k}*x2"}, {"y1": "w", "y2": "x1 + x2"}, trafo={"w": "2", "x1": "1"}) assert r.identifiable and r.dim == 3 assert r.info["projection"] is None and r.info["rank_status"]["status"] == "proven" @@ -547,8 +642,13 @@ def test_start_points_whose_fresh_columns_drop_rank_are_left_out_of_the_proof(): def test_an_event_of_one_condition_acts_in_that_condition_only(): f = {"x": "-k*x", "w": "piecewise(-a*w, w > h, -b*w)"} ev = [{"var": "x", "time": 1, "value": "1", "method": "replace", "cond": [0]}] - r = det(f, [{"y1": "x", "y2": "w"}, {"y1": "s*x", "y2": "w"}], trafo=[{"x": "1", "w": "1"}, {"x": "x0", "w": "1"}], - events=ev, conditions={"rows": ["A", "B"], "cols": {}}) + r = det( + f, + [{"y1": "x", "y2": "w"}, {"y1": "s*x", "y2": "w"}], + trafo=[{"x": "1", "w": "1"}, {"x": "x0", "w": "1"}], + events=ev, + conditions={"rows": ["A", "B"], "cols": {}}, + ) assert (r.rank, r.dim) == (5, 6) @@ -569,15 +669,15 @@ def test_a_state_that_every_regime_keeps_at_zero_leaves_the_model(): def test_a_state_driven_off_zero_through_a_chain_stays_in_the_model(): - f = {"x1": "-c*x1", "x2": "piecewise(a, x1 > h, -k*x2)", "x3": "x2 - d*x3", "x4": "x3 - d*x4", - "x5": "-e*x5"} + f = {"x1": "-c*x1", "x2": "piecewise(a, x1 > h, -k*x2)", "x3": "x2 - d*x3", "x4": "x3 - d*x4", "x5": "-e*x5"} r = det(f, {"y1": "x1", "y2": "x4 + x5"}, trafo={"x1": "1", "x2": "0", "x3": "0", "x4": "0", "x5": "0"}) assert r.info["zero_states"] == ["x5"] def _with_input(f, g, trafo, **kw): - m = si.Model(f, g, trafo=trafo, unknown_inputs=["w"], events=kw.pop("events", None), - conditions=kw.pop("conditions", None)) + m = si.Model( + f, g, trafo=trafo, unknown_inputs=["w"], events=kw.pop("events", None), conditions=kw.pop("conditions", None) + ) return si.detect(m, cores=1, reconstruct=True, **kw) @@ -593,8 +693,9 @@ def test_an_unknown_input_is_continuous_across_a_switch(): def test_an_unknown_input_takes_up_only_the_rates_of_what_it_drives(): - r = _with_input({"x": "w - k*x", "z": "piecewise(a, x < c, b)*x - d*z"}, {"y1": "x", "y2": "z"}, - {"x": "x0", "z": "z0"}) + r = _with_input( + {"x": "w - k*x", "z": "piecewise(a, x < c, b)*x - d*z"}, {"y1": "x", "y2": "z"}, {"x": "x0", "z": "z0"} + ) (s,) = r.symmetries assert s.support == ["k"] and s.level == "exact" and r.rank == r.dim - 1 and r.info["rank_proven"] == 1 @@ -609,8 +710,12 @@ def test_a_switch_that_a_kink_of_the_input_can_hide_is_not_visible(): def test_unknown_inputs_with_switches_refuse_later_events_and_switches_on_the_input(): with pytest.raises(ValueError, match="events after the start"): - _with_input({"x": "w - piecewise(k1, x < c, k2)*x"}, {"y": "x"}, {"x": "x0"}, - events=[{"var": "x", "time": 2, "value": 1, "method": "add"}]) + _with_input( + {"x": "w - piecewise(k1, x < c, k2)*x"}, + {"y": "x"}, + {"x": "x0"}, + events=[{"var": "x", "time": 2, "value": 1, "method": "add"}], + ) with pytest.raises(ValueError, match="switch on the unknown input"): _with_input({"x": "piecewise(a, w < c, b) - k*x"}, {"y": "x"}, {"x": "x0"}) f, cols = {"x": "s*w - piecewise(k1, x < c, k2)*x"}, {"s": [1, 2]} @@ -620,11 +725,21 @@ def test_unknown_inputs_with_switches_refuse_later_events_and_switches_on_the_in def test_an_unknown_input_of_its_own_per_condition_with_switches(): f, g = {"x": "s*w - piecewise(k1, x < c, k2)*x"}, {"y": "x"} - m = si.Model(f, g, trafo={"x": "x0"}, unknown_inputs=["w", "w2"], - conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}) + m = si.Model( + f, + g, + trafo={"x": "x0"}, + unknown_inputs=["w", "w2"], + conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}, + ) r = si.detect(m, cores=1, reconstruct=True) assert (r.rank, r.dim) == (3, 4) and r.info["rank_proven"] == 1 same_span(r, [{"k1": 1, "k2": 1}]) - m = si.Model(f, g, trafo={"x": "x0"}, unknown_inputs=["w"], - conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "0"]}}) + m = si.Model( + f, + g, + trafo={"x": "x0"}, + unknown_inputs=["w"], + conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "0"]}}, + ) assert si.detect(m, cores=1).identifiable diff --git a/tests/test_totals.py b/tests/test_totals.py index fd1ff45..6823143 100644 --- a/tests/test_totals.py +++ b/tests/test_totals.py @@ -27,18 +27,22 @@ def __init__(self, odes, obs, totals, point, events=U, inputs=("u",), fixed=()): self.events, self.inputs, self.fixed = events, list(inputs), list(fixed) def renamed(self, ren): - return Case({ren.get(k, k): _sub(v, ren) for k, v in self.odes.items()}, - {k: _sub(v, ren) for k, v in self.obs.items()}, - {k: _sub(v, ren) for k, v in self.totals.items()}, - {ren.get(k, k): v for k, v in self.point.items()}, - [dict(e, var=ren.get(e["var"], e["var"]), value=_sub(e["value"], ren)) for e in self.events], - [ren.get(x, x) for x in self.inputs], [ren.get(x, x) for x in self.fixed]) + return Case( + {ren.get(k, k): _sub(v, ren) for k, v in self.odes.items()}, + {k: _sub(v, ren) for k, v in self.obs.items()}, + {k: _sub(v, ren) for k, v in self.totals.items()}, + {ren.get(k, k): v for k, v in self.point.items()}, + [dict(e, var=ren.get(e["var"], e["var"]), value=_sub(e["value"], ren)) for e in self.events], + [ren.get(x, x) for x in self.inputs], + [ren.get(x, x) for x in self.fixed], + ) def detect(self, order=None, totals_order=None, **kw): odes = self.odes if order is None else {k: self.odes[k] for k in order} totals = self.totals if totals_order is None else {k: self.totals[k] for k in totals_order} - m = si.Model(odes=odes, observables=self.obs, totals=totals, events=self.events, inputs=self.inputs, - fixed=self.fixed) + m = si.Model( + odes=odes, observables=self.obs, totals=totals, events=self.events, inputs=self.inputs, fixed=self.fixed + ) kw.setdefault("equilibrate", True) kw.setdefault("reconstruct", True) kw.setdefault("cores", 1) @@ -56,9 +60,12 @@ def span(self, r, back=None): at[sym[t]] = spy.sympify(e.replace("^", "**"), locals=sym).subs(at) free = [c for c in coords if c in states] Y = [s for s in states if s not in free] - eqs = [spy.sympify(self.odes[s].replace("^", "**"), locals=sym).subs({sym.get(u, spy.Symbol(u)): 0 - for u in self.inputs}) - for s in states] + eqs = [ + spy.sympify(self.odes[s].replace("^", "**"), locals=sym).subs( + {sym.get(u, spy.Symbol(u)): 0 for u in self.inputs} + ) + for s in states + ] eqs += [spy.sympify(self.totals[c].replace("^", "**"), locals=sym) - sym[c] for c in coords if c in self.totals] GY = spy.Matrix([[spy.diff(e, sym[y]) for y in Y] for e in eqs]).subs(at) Gc = spy.Matrix([[spy.diff(e, sym[c]) for c in coords] for e in eqs]).subs(at) @@ -90,15 +97,42 @@ def _rest_ab(k1, k2, a): return {"A": a, "B": k1 * a / k2} -EXCHANGE = Case({"A": "-k1*(1+u)*A + k2*B", "B": "k1*(1+u)*A - k2*B", "u": "0"}, {"y": "s*B"}, {"T": "A + B"}, - dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), **_rest_ab(R(3, 7), R(5, 11), R(17, 5)))) -VOLUMES = Case({"A": "(-k1*(1+u)*A + k2*B)/V1", "B": "(k1*(1+u)*A - k2*B)/V2", "u": "0"}, {"y": "s*B"}, - {"T": "V1*A + V2*B"}, - dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), V1=R(2, 3), V2=R(7, 5), **_rest_ab(R(3, 7), R(5, 11), R(4)))) -TWO = Case({"A": "(-k1*(1+u)*A + k2*B)/V1", "B": "(k1*(1+u)*A - k2*B)/V2", "C": "(-k3*B*C + k4*D)/V1", - "D": "(k3*B*C - k4*D)/V2", "u": "0"}, {"y1": "s1*B", "y2": "D"}, {"T1": "V1*A + V2*B", "T2": "V1*C + V2*D"}, - dict(k1=R(3, 7), k2=R(5, 11), k3=R(2, 9), k4=R(7, 4), s1=R(13, 3), V1=R(2, 3), V2=R(7, 5), - A=R(4), B=R(3, 7) * 4 / R(5, 11), C=R(6), D=R(2, 9) * (R(3, 7) * 4 / R(5, 11)) * 6 / R(7, 4))) +EXCHANGE = Case( + {"A": "-k1*(1+u)*A + k2*B", "B": "k1*(1+u)*A - k2*B", "u": "0"}, + {"y": "s*B"}, + {"T": "A + B"}, + dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), **_rest_ab(R(3, 7), R(5, 11), R(17, 5))), +) +VOLUMES = Case( + {"A": "(-k1*(1+u)*A + k2*B)/V1", "B": "(k1*(1+u)*A - k2*B)/V2", "u": "0"}, + {"y": "s*B"}, + {"T": "V1*A + V2*B"}, + dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), V1=R(2, 3), V2=R(7, 5), **_rest_ab(R(3, 7), R(5, 11), R(4))), +) +TWO = Case( + { + "A": "(-k1*(1+u)*A + k2*B)/V1", + "B": "(k1*(1+u)*A - k2*B)/V2", + "C": "(-k3*B*C + k4*D)/V1", + "D": "(k3*B*C - k4*D)/V2", + "u": "0", + }, + {"y1": "s1*B", "y2": "D"}, + {"T1": "V1*A + V2*B", "T2": "V1*C + V2*D"}, + dict( + k1=R(3, 7), + k2=R(5, 11), + k3=R(2, 9), + k4=R(7, 4), + s1=R(13, 3), + V1=R(2, 3), + V2=R(7, 5), + A=R(4), + B=R(3, 7) * 4 / R(5, 11), + C=R(6), + D=R(2, 9) * (R(3, 7) * 4 / R(5, 11)) * 6 / R(7, 4), + ), +) @pytest.mark.parametrize("case", [EXCHANGE, VOLUMES, TWO], ids=["exchange", "volumes", "two totals"]) @@ -129,13 +163,20 @@ def test_the_result_does_not_depend_on_pivots_names_or_order(case): LINEAR = {"A": "-k1*A + k2*B", "B": "k1*A - k2*B"} -@pytest.mark.parametrize("var, time, method", [("A", 0, "add"), ("B", 0, "replace"), ("A", 1, "add"), - ("B", 0, "multiply")]) +@pytest.mark.parametrize( + "var, time, method", [("A", 0, "add"), ("B", 0, "replace"), ("A", 1, "add"), ("B", 0, "multiply")] +) def test_reduce_cq_applies_an_event_on_a_species_of_a_total(var, time, method): # the total changes by E(x) - x at the event; with y = s*B, A is eliminated - case = Case(LINEAR, {"y": "s*B"}, {"T": "A + B"}, - dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), dose=R(2), **_rest_ab(R(3, 7), R(5, 11), R(17, 5))), - events=[{"var": var, "time": time, "value": "dose", "method": method}], inputs=(), fixed=("dose",)) + case = Case( + LINEAR, + {"y": "s*B"}, + {"T": "A + B"}, + dict(k1=R(3, 7), k2=R(5, 11), s=R(13, 3), dose=R(2), **_rest_ab(R(3, 7), R(5, 11), R(17, 5))), + events=[{"var": var, "time": time, "value": "dose", "method": method}], + inputs=(), + fixed=("dose",), + ) pivots, reduced = case.detect(), case.detect(reduce_cq=True) assert reduced.info["settings"]["eliminated"] == ["A"] and "T" in reduced.info["coordinates"] assert summary(pivots) == summary(reduced) and pivots.rank == 3 @@ -144,8 +185,13 @@ def test_reduce_cq_applies_an_event_on_a_species_of_a_total(var, time, method): def test_a_dose_on_a_species_changes_the_total_in_later_segments(): # the dose at t = 1 raises the total: without it the total and the rates would share a scaling - m = si.Model(odes=LINEAR, observables={"y": "B"}, totals={"T": "A + B"}, - events=[{"var": "A", "time": 1, "value": "dose", "method": "add"}], fixed=["dose"]) + m = si.Model( + odes=LINEAR, + observables={"y": "B"}, + totals={"T": "A + B"}, + events=[{"var": "A", "time": 1, "value": "dose", "method": "add"}], + fixed=["dose"], + ) r = si.detect(m, equilibrate=True, reduce_cq=True, cores=1) assert (r.rank, r.dim) == (3, 3) and r.info["rank_status"]["status"] == "proven" @@ -154,8 +200,13 @@ def test_a_dose_on_a_species_changes_the_total_in_later_segments(): def _binding(**kw): - m = si.Model(odes=BINDING, observables={"y": "s*C"}, totals=kw.pop("totals", {"TA": "A + C", "TB": "B + C"}), - events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}], fixed=["dose"]) + m = si.Model( + odes=BINDING, + observables={"y": "s*C"}, + totals=kw.pop("totals", {"TA": "A + C", "TB": "B + C"}), + events=[{"var": "A", "time": 0, "value": "dose", "method": "add"}], + fixed=["dose"], + ) return si.detect(m, equilibrate=True, cores=1, **kw) @@ -168,11 +219,14 @@ def test_every_valid_pivot_set_of_totals_sharing_a_species_solves(pivots): assert sorted(r.info["settings"]["free_initial"]) == sorted(pivots) -@pytest.mark.parametrize("pivots, match", [ - (["C", "C"], "names C twice"), - (["A", "Z"], "Z, which is not a state"), - (["A", "C", "B"], "do not leave independent"), -]) +@pytest.mark.parametrize( + "pivots, match", + [ + (["C", "C"], "names C twice"), + (["A", "Z"], "Z, which is not a state"), + (["A", "C", "B"], "do not leave independent"), + ], +) def test_an_invalid_free_initial_is_refused(pivots, match): with pytest.raises(InputError, match=match): _binding(free_initial=pivots) @@ -192,8 +246,13 @@ def test_free_initial_takes_one_state_per_total(): def test_a_state_at_zero_at_rest_takes_the_free_value_where_free_initial_names_it(): # A + B -> 2B, B -> A: B rests at zero, or A = k2/k1 with B free - m = si.Model(odes=ACR, observables={"y": "s*B"}, totals={"T": "A + B"}, - events=[{"var": "B", "time": 0, "value": "dose", "method": "add"}], fixed=["dose"]) + m = si.Model( + odes=ACR, + observables={"y": "s*B"}, + totals={"T": "A + B"}, + events=[{"var": "B", "time": 0, "value": "dose", "method": "add"}], + fixed=["dose"], + ) zero = si.detect(m, equilibrate=True, reconstruct=True, cores=1) assert any("B rests at zero" in b and "free_initial=['B']" in b for b in zero.info["branches"]) assert zero.info["settings"]["free_initial"] == ["A"] @@ -202,14 +261,20 @@ def test_a_state_at_zero_at_rest_takes_the_free_value_where_free_initial_names_i away = si.detect(m, equilibrate=True, free_initial=["B"], cores=1) assert away.info["settings"]["free_initial"] == ["B"] and away.rank != zero.rank assert any("free_initial: B rests away from zero" in b for b in away.info["branches"]) - lost = si.Model(odes={"x": "-k*x", "y": "k*x"}, observables={"o": "s*y"}, totals={"T": "x + y"}, - events=[{"var": "x", "time": 0, "value": "d", "method": "add"}], fixed=["d"]) + lost = si.Model( + odes={"x": "-k*x", "y": "k*x"}, + observables={"o": "s*y"}, + totals={"T": "x + y"}, + events=[{"var": "x", "time": 0, "value": "d", "method": "add"}], + fixed=["d"], + ) with pytest.raises(InputError, match="x, which rests at zero at every resting state"): si.detect(lost, equilibrate=True, free_initial=["x"]) def test_the_totals_of_odes_are_nonnegative_in_every_order(): import itertools + seen = set() for order in itertools.permutations(BINDING): m = si.Model(odes={k: BINDING[k] for k in order}, observables={"y": "s*C"}) @@ -218,9 +283,17 @@ def test_the_totals_of_odes_are_nonnegative_in_every_order(): assert "-" not in t laws.add(frozenset(re.findall(r"[A-Z]", t))) seen.add(frozenset(laws)) - rx = si.Model(reactions={"species": list(order), "stoichiometry": [ - [{"A": -1, "B": -1, "C": 1}[s] for s in order], [{"A": 1, "B": 1, "C": -1}[s] for s in order]], - "rates": ["kon*A*B", "koff*C"]}, observables={"y": "s*C"}) + rx = si.Model( + reactions={ + "species": list(order), + "stoichiometry": [ + [{"A": -1, "B": -1, "C": 1}[s] for s in order], + [{"A": 1, "B": 1, "C": -1}[s] for s in order], + ], + "rates": ["kon*A*B", "koff*C"], + }, + observables={"y": "s*C"}, + ) assert {frozenset(re.findall(r"[A-Z]", t)) for t in rx.totals.values()} == laws assert seen == {frozenset({frozenset("AC"), frozenset("BC")})} # one relation between four nonnegative laws: three of them, all nonnegative @@ -229,8 +302,7 @@ def test_the_totals_of_odes_are_nonnegative_in_every_order(): def test_a_total_of_both_signs_is_noted_under_reduce_cq(): - m = si.Model(odes={"A": "k*(1+u)", "B": "k*(1+u)", "u": "0"}, observables={"y": "A + s*B"}, inputs=["u"], - events=U) + m = si.Model(odes={"A": "k*(1+u)", "B": "k*(1+u)", "u": "0"}, observables={"y": "A + s*B"}, inputs=["u"], events=U) assert m.totals["total1"] == "A - B" with warnings.catch_warnings(): warnings.simplefilter("ignore") diff --git a/tests/test_unknown_inputs.py b/tests/test_unknown_inputs.py index 76d621d..6e861f0 100644 --- a/tests/test_unknown_inputs.py +++ b/tests/test_unknown_inputs.py @@ -32,8 +32,11 @@ def test_an_unknown_input_absorbs_what_the_parameters_would_explain(): def test_a_time_varying_rate_as_an_unknown_input(): # Martinelli 2022, arXiv 2211.13507, Section 6 - m = si.Model({"TU": "lam - rho*TU - eta*TU*V", "TI": "eta*TU*V - delta*TI", "V": "N*delta*TI - c*V"}, - {"y1": "V", "y2": "TU + TI"}, unknown_inputs=["eta"]) + m = si.Model( + {"TU": "lam - rho*TU - eta*TU*V", "TI": "eta*TU*V - delta*TI", "V": "N*delta*TI - c*V"}, + {"y1": "V", "y2": "TU + TI"}, + unknown_inputs=["eta"], + ) r = si.detect(m, reconstruct=True) # eta cancels in the derivative of y2, so it enters from order 2 on: the jet columns that can enter the # rows have full rank, which proves the rank modulo the input @@ -57,11 +60,14 @@ def test_the_input_change_of_a_linear_input(): assert r.symmetries[0].state_components is None -@pytest.mark.parametrize("rhs, change", [ - ("-k*x + exp(w)", "k*x*exp(-w)"), - ("-k*x + a*w^2", "k*x/(2*a*w)"), - ("-k*x + w*log(x)", "k*x/log(x)"), -]) +@pytest.mark.parametrize( + "rhs, change", + [ + ("-k*x + exp(w)", "k*x*exp(-w)"), + ("-k*x + a*w^2", "k*x/(2*a*w)"), + ("-k*x + w*log(x)", "k*x/log(x)"), + ], +) def test_the_input_change_through_a_recast_or_a_log_chart(rhs, change): r = si.detect(si.Model({"x": rhs}, {"y": "x"}, unknown_inputs=["w"]), reconstruct=True) assert {s.level for s in r.symmetries} == {"exact"} and r.info["rank_status"]["status"] == "proven" @@ -74,12 +80,24 @@ def test_a_measured_unknown_input_leaves_the_model_identifiable(): def test_conditions_share_an_unknown_input_or_rename_it(): - shared = si.detect(si.Model({"x": "-k*x + s*w"}, {"y": "x"}, unknown_inputs=["w"], - conditions={"rows": ["a", "b"], "cols": {"s": [1, 2]}})) + shared = si.detect( + si.Model( + {"x": "-k*x + s*w"}, + {"y": "x"}, + unknown_inputs=["w"], + conditions={"rows": ["a", "b"], "cols": {"s": [1, 2]}}, + ) + ) assert shared.identifiable - own = si.detect(si.Model({"x": "-k*x + s*w"}, {"y": "x"}, unknown_inputs=["w", "w2"], - conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}), - reconstruct=True) + own = si.detect( + si.Model( + {"x": "-k*x + s*w"}, + {"y": "x"}, + unknown_inputs=["w", "w2"], + conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}, + ), + reconstruct=True, + ) assert (own.rank, own.dim) == (1, 2) and own.symmetries[0].level == "exact" ch = _change(own, "k") assert _same(ch["w"], "k*x") and _same(ch["w2"], "k*x/2") @@ -87,8 +105,7 @@ def test_conditions_share_an_unknown_input_or_rename_it(): def test_a_chain_below_the_lie_order_bounds_the_rank_from_below(): odes = {"x1": "w - k1*x1", "x2": "k1*x1 - k2*x2", "x3": "k2*x2 - k3*x3"} - r = si.detect(si.Model(odes, {"y": "x3"}, unknown_inputs=["w"]), - control=si.reconst_control(input_jet_order=2)) + r = si.detect(si.Model(odes, {"y": "x3"}, unknown_inputs=["w"]), control=si.reconst_control(input_jet_order=2)) assert r.info["unknown_inputs"]["short"] assert r.info["rank_status"]["status"] == "lower bound" assert "jet chains" in r.info["rank_status"]["why"] @@ -113,8 +130,9 @@ def test_an_event_tells_the_rate_from_a_continuous_input(): def test_an_unknown_input_is_zero_at_rest(): - r = si.detect(si.Model({"x": "p - k*x + b*w"}, {"y": "x"}, unknown_inputs=["w"]), equilibrate=True, - reconstruct=True) + r = si.detect( + si.Model({"x": "p - k*x + b*w"}, {"y": "x"}, unknown_inputs=["w"]), equilibrate=True, reconstruct=True + ) assert set(r.info["coordinates"]) == {"b", "k", "p"} and r.rank == 1 (s,) = [s for s in r.symmetries if "b" in s.generator] assert s.level == "exact" and _same(_change(r, "b")["w"], "-w") @@ -122,10 +140,13 @@ def test_an_unknown_input_is_zero_at_rest(): assert r.identifiable and set(r.info["coordinates"]) == {"b", "k", "p"} -@pytest.mark.parametrize("kw, what", [ - (dict(events=[{"var": "w", "time": 1, "value": 1, "method": "add"}]), "event changes the unknown input"), - (dict(trafo={"w": "w0"}), "trafo"), -]) +@pytest.mark.parametrize( + "kw, what", + [ + (dict(events=[{"var": "w", "time": 1, "value": 1, "method": "add"}]), "event changes the unknown input"), + (dict(trafo={"w": "w0"}), "trafo"), + ], +) def test_settings_without_unknown_inputs_are_refused(kw, what): with pytest.raises(ValueError, match=what): si.detect(si.Model({"x": "-k*x + w"}, {"y": "x"}, unknown_inputs=["w"], **kw)) @@ -164,8 +185,7 @@ def test_full_rank_with_unknown_inputs_is_verified(): def test_an_unknown_input_under_a_log_chart_is_no_coordinate(): - r = si.detect(si.Model({"x": "k0 + k/(1 + (x/(1 + w))^n) - x"}, {"y": "x"}, unknown_inputs=["w"]), - reconstruct=True) + r = si.detect(si.Model({"x": "k0 + k/(1 + (x/(1 + w))^n) - x"}, {"y": "x"}, unknown_inputs=["w"]), reconstruct=True) assert "w" not in r.info["coordinates"] and r.info["rank_status"]["status"] == "proven" assert {s.level for s in r.symmetries} == {"exact"} # the lift in the log coordinate of the input has no closed form in the input: no input change of zero @@ -192,13 +212,17 @@ def test_a_pointwise_lift_reduces_a_direction_the_input_absorbs(): (lf,) = b["inputs"]["lift"].values() a, bb, d, N, w = spy.symbols("a b d N w") loc = {"a": a, "b": bb, "d": d, "N": N, "w": w} - xi = {k: spy.sympify(v.replace("^", "**"), locals=loc) for part in ("params", "states", "inputs") - for k, v in lf[part].items()} + xi = { + k: spy.sympify(v.replace("^", "**"), locals=loc) + for part in ("params", "states", "inputs") + for k, v in lf[part].items() + } V = {spy.Symbol(k): v for k, v in xi.items()} f = {a: -w * a, bb: w * a - d * bb} def act(e): return sum(spy.diff(e, k) * v for k, v in V.items()) + for x, fx in f.items(): Dxi = sum(spy.diff(V.get(x, 0), y) * f[y] for y in f) assert spy.cancel(Dxi - act(fx)) == 0 @@ -250,8 +274,12 @@ def test_the_count_leaves_out_the_jets_the_output_does_not_read(): def test_a_direction_the_inputs_absorb_in_several_conditions_keeps_without_a_proof(): - m = si.Model({"x": "-k*x + s*w"}, {"y": "x"}, unknown_inputs=["w", "w2"], - conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}) + m = si.Model( + {"x": "-k*x + s*w"}, + {"y": "x"}, + unknown_inputs=["w", "w2"], + conditions={"rows": ["a", "b"], "cols": {"s": [1, 2], "w": ["w", "w2"]}}, + ) red = si.reduce(si.detect(m, reconstruct=True)) (b,) = red.to_dict()["blocks"] assert red.remaining and b["status"] == "unresolved" and "one condition" in b["reason"] diff --git a/tests/tjson.py b/tests/tjson.py index cd5419d..e36dbb4 100644 --- a/tests/tjson.py +++ b/tests/tjson.py @@ -22,8 +22,7 @@ def tdec(o): elif t == "int": a = np.array(d, dtype=np.int64) elif t == "dbl": - a = np.array([float(x) if x not in ("Inf", "-Inf", "NaN") else float(x.lower()) for x in d], - dtype=float) + a = np.array([float(x) if x not in ("Inf", "-Inf", "NaN") else float(x.lower()) for x in d], dtype=float) elif t == "chr": a = list(d) else: