diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d31a49a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +# The versions of the GitHub Actions, one pull request per month for all of them. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/wheels.yml b/.github/workflows/cd.yml similarity index 56% rename from .github/workflows/wheels.yml rename to .github/workflows/cd.yml index 421ad72..6e7fd40 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/cd.yml @@ -1,42 +1,58 @@ -# Wheels for Linux (manylinux x86_64 and aarch64), macOS (arm64) and Windows, -# the sdist, tests of the Linux wheel on Fedora and Debian, a source build on Fedora, and the -# msolve build on AlmaLinux 8 (glibc 2.28). -# Documentation goes to Pages from master. A published release builds nothing: it uploads to -# PyPI the wheels and the sdist of the successful push run on the released commit. +# Wheels (manylinux x86_64/aarch64, macOS arm64, Windows) and the sdist, tested by cibuildwheel; the Linux wheel +# also on Fedora and Debian Python, a source build with Fedora compilers, msolve on AlmaLinux 8 (glibc 2.28). Runs +# on build changes, weekly, on demand, and per published release, which uploads the wheels and the sdist to PyPI. name: wheels on: + pull_request: + paths: + - cpp/** + - CMakeLists.txt + - pyproject.toml + - src/symident/install.py + - src/symident/tools/** + - .github/workflows/cd.yml push: branches: [master] - pull_request: + paths: + - cpp/** + - CMakeLists.txt + - pyproject.toml + - src/symident/install.py + - src/symident/tools/** + - .github/workflows/cd.yml + schedule: + - cron: "0 3 * * 1" workflow_dispatch: release: types: [published] +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name != 'release' }} + jobs: wheels: name: wheels ${{ matrix.os }} - if: github.event_name != 'release' runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, windows-latest] steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v7 - uses: pypa/cibuildwheel@v4.3.5 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: wheels-${{ matrix.os }} path: wheelhouse/*.whl sdist: - if: github.event_name != 'release' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v7 - run: pipx run build --sdist - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: sdist path: dist/*.tar.gz @@ -46,7 +62,7 @@ jobs: distro: needs: wheels # runs when another platform's wheels failed; it needs only the ubuntu-latest wheel - if: ${{ !cancelled() && github.event_name != 'release' }} + if: ${{ !cancelled() }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -62,8 +78,8 @@ 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@v7 + - uses: actions/download-artifact@v8 with: name: wheels-ubuntu-latest path: wheelhouse @@ -80,26 +96,24 @@ jobs: # the msolve build script alone on glibc 2.28, where pthread is not part of libc msolve-glibc228: - if: github.event_name != 'release' runs-on: ubuntu-latest container: almalinux:8 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@v7 - name: Build msolve run: SYMIDENT_LIBS_CACHE=/tmp/msolve SYMIDENT_JOBS=4 sh src/symident/tools/build-msolve.sh # a source install on Fedora's own Python and compilers, as dMod2's CI installs it fedora: name: fedora - if: github.event_name != 'release' runs-on: ubuntu-latest container: fedora:latest 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@v7 - name: Install from source run: | python3 -m venv /opt/venv @@ -108,67 +122,22 @@ jobs: - name: Tests run: cd /tmp && /opt/venv/bin/python -m pytest -q -n auto "$GITHUB_WORKSPACE/tests" - # the documentation as HTML, built on every run and deployed to Pages from master - docs: - if: github.event_name != 'release' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - uses: actions/setup-python@v6 - 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 - with: - path: docs/_build/html - - pages: - if: github.event_name == 'push' && github.ref == 'refs/heads/master' - needs: docs - runs-on: ubuntu-latest - permissions: - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deploy.outputs.page_url }} - steps: - - id: deploy - uses: actions/deploy-pages@v4 - + # the artifacts of this run, uploaded only when every build and test above passed publish: + needs: [wheels, sdist, distro, msolve-glibc228, fedora] if: github.event_name == 'release' && github.event.action == 'published' runs-on: ubuntu-latest environment: pypi permissions: id-token: write - actions: read steps: - # the successful push run on the released commit, built and tested on every platform - - id: run - env: - GH_TOKEN: ${{ github.token }} - run: | - id=$(gh run list -R "$GITHUB_REPOSITORY" -w wheels.yml -e push -c "$GITHUB_SHA" -s success -L 1 \ - --json databaseId -q '.[0].databaseId') - if [ -z "$id" ]; then - echo "::error::no successful push run of wheels.yml on $GITHUB_SHA; rerun it, then this run" - exit 1 - fi - echo "id=$id" >> "$GITHUB_OUTPUT" - # the wheels and the sdist only, not the documentation for Pages - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: pattern: wheels-* path: dist merge-multiple: true - run-id: ${{ steps.run.outputs.id }} - github-token: ${{ github.token }} - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: name: sdist path: dist - run-id: ${{ steps.run.outputs.id }} - github-token: ${{ github.token }} - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5abd66a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +# The pre-commit hooks (ruff, file checks, no em dashes) and the test suite on a source build, on Linux, +# macOS and Windows with the oldest and the newest supported Python. +name: CI + +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - run: pipx run pre-commit run --all-files --show-diff-on-failure + + tests: + name: tests ${{ matrix.os }} Python ${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python: ["3.10", "3.15"] + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python }} + allow-prereleases: true + - name: Install from source + run: python -m pip install ".[test]" + # outside the checkout, so that the tests import the installed package + - name: Tests + working-directory: ${{ runner.temp }} + run: python -m pytest -q -n auto "${{ github.workspace }}/tests" diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..7c7a1df --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,54 @@ +# The documentation as HTML with warnings as errors, built on pull requests and deployed to Pages from +# master. +name: docs + +on: + pull_request: + paths: + - docs/** + - src/** + - README.md + - pyproject.toml + - .github/workflows/docs.yml + push: + branches: [master] + paths: + - docs/** + - src/** + - README.md + - pyproject.toml + - .github/workflows/docs.yml + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + # a deployment to Pages runs to the end + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - run: pip install ".[docs]" + - run: sphinx-build -W -b html docs docs/_build/html + - uses: actions/upload-pages-artifact@v5 + with: + path: docs/_build/html + + deploy: + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + steps: + - id: deploy + uses: actions/deploy-pages@v5 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..b93954c --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,28 @@ +# `pre-commit install` runs these on every commit; CI runs them on all files. +exclude: ^tests/data/ + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-merge-conflict + - id: check-toml + - id: check-yaml + - id: end-of-file-fixer + - id: mixed-line-ending + - id: trailing-whitespace + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.6 + hooks: + - id: ruff-check + + - repo: local + hooks: + - id: no-em-dash + name: no em dashes + language: pygrep + entry: "\u2014" + types: [text] diff --git a/CMakeLists.txt b/CMakeLists.txt index c114ed7..cb6df42 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ endif() find_package(Python REQUIRED COMPONENTS Interpreter Development.Module) find_package(pybind11 CONFIG REQUIRED) find_package(OpenMP COMPONENTS CXX) -pybind11_add_module(_core cpp/bindings.cpp cpp/kernel.cpp) +pybind11_add_module(_core cpp/bindings.cpp cpp/kernel.cpp cpp/ioproj.cpp) if(OpenMP_CXX_FOUND) target_link_libraries(_core PRIVATE OpenMP::OpenMP_CXX) else() diff --git a/NEWS.md b/NEWS.md index 57b418d..9378dfc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,105 @@ +# symident 0.18.0 + +## Global analysis + +* The count of `discrete()` is certified. `info["discrete"]["certificate"]["complete"]` is + `"exact"`, `"verified"`, `"axiom"`, `"no"` or `"open"`, and `info["discrete"]["count_bound"]` + is the probability that a generic point has more values than counted. +* Exact count: functions of the coordinates are proven to be rational functions of the output + coefficients, and the fiber of these functions is the orbit of the exact maps, shown by + identities of rational functions over Q. The input-output relations come from elimination of + the states by resultants over Z[theta] with python-flint, or from input-output projections per + observable whose support is found modulo a prime and whose coefficients are interpolated in the + parameters and checked as identities. A projection with more terms is verified at random points + with the Schwartz-Zippel bound. Where the search stops, the functions proven so far are counted + (`certificate["pinned"]`). +* Verified count: msolve counts over Q at a random integer point, with an error bound from the + Schwartz-Zippel lemma and the degrees of the output coefficients. +* Points of the fiber are proposed by numerical monodromy and enclosed by the Krawczyk operator; + a map read from them counts once it is proven exactly. +* A model with free starts is counted on several experiments with shared parameters + (`experiments=`), which bounds the fiber where the model has no nonconstant rational first + integral. The premise is proven at one point of the parameters from the eigenvalues of the + Jacobian at an equilibrium, by Galois groups from Frobenius cycle types. `info["experiments"]` + reports the route or why it does not apply. +* Models with unknown inputs are counted, the jets of the inputs as unknowns of the fiber that + are no coordinates; a map may change the input (`state_maps`). +* A result detected with `reduce_cq` is counted on the level sets of the conserved totals, with + the species solved through the totals in `info["discrete"]["eliminated"]`. +* Non-rational terms of the states become new states and new coordinates, the values of the + terms at the start (`info["discrete"]["relaxed"]`). Under `equilibrate`, the resting values + inside transcendental terms become coordinates of a resting chart. A free power of a state that + starts at 0 enters as a series in t and in the power (`info["discrete"]["start_powers"]`). +* Under `equilibrate`, resting balances whose Bezout number is past 4 or that couple more than 8 + states are not solved; the result is unsupported and names the cap (`rest_bezout`, `rest_block`). +* An open or unsupported result names the reason, in `info["discrete"]["unsupported"]`, the + certificate or `limits`. + +## Work limits instead of time limits + +* Nothing in the package stops on a clock: every search and count stops at a cap on steps, + points, terms or unknowns, so that the result is the same on every machine. A stage at a limit + names the limit and the value of the limit. +* `timeout` and `budget` are removed from `discrete()`, `solution_count()`, `reduce()` and + `reconst_control()`. New arguments of `discrete()` and keys of `global_options`: `memory`, + `experiments`, `msolve_entries`, `msolve_terms`, `search_entries` and `elimination_terms`. +* The switch `DIRECTSECS` is removed. New switches: `MSOLVE_GB`, `FIBER_TERMS`, `JETMB`, + `NOSHARED` and `NOSELECT`. +* `detect(discrete=)` is removed; use `mode="global"` and `global_options`. + +## Detection + +* The rank of a model with switches, modulo the fresh coordinates of the switch surfaces, is + proven on the copies whose start points keep full column rank, where it was a lower bound. +* Weights rational in the coordinates, such as those of a recast power, enter the proof of exact + scalings. +* A resting state is proven to exist where a simple point modulo a prime at an integer point + lifts by Hensel's lemma. Balances without a resting state raise an `InputError` with an error + bound. + +## Conditions and PEtab + +* With many conditions, the analysis runs on the conditions whose rows at a random point raise + the rank or first reach a coordinate. Each direction is then proven on the conditions left out + (`info["selection"]`). +* Conditions that differ only in the values of symbols share one tape, compiled once. +* A PEtab experiment in one period without a preequilibration whose measurements are all at + `inf` is read at rest under the condition of that period (`m.petab["at_rest"]`). + +## Large models + +* The kernel builds the rows in forward or in reverse mode, whichever sweeps fewer residues, and + keeps the jets of a detection for calls at higher orders. +* The state components of a direction are solved modulo a prime on the states the direction + reaches and proven by the identities of the field. +* The degrees of the output coefficients come from the series recursion run on degree bounds. +* Input-output projections over GF(p) run in C++ (`cpp/ioproj.cpp`). +* Lifts of many directions run in parallel workers. + +## Reduction + +* A direction of a model with unknown inputs is reduced where the inputs absorb it, proven per + direction by inversion (the input solved from the derivatives of the observables) or by a lift + of the field to the states and the input. The printout lists the inputs and the condition under + which the section gives the output of a point. +* `reduce()` prefers charts that cover the whole domain after charts without `sign_conditions`. + +## Documentation + +* The method is rewritten as a chapter in `docs/method/`: local analysis, conditions, proofs, + reduction and global analysis, with references through `refs.bib`. +* A guide page for the global analysis. +* The observables are written g(t; theta). + +## Packaging and CI + +* New dependency python-flint >= 0.7.0; the `docs` extra adds sphinxcontrib-bibtex. +* `ci.yml` runs the pre-commit hooks and the tests on a source build on Linux, macOS and Windows + with Python 3.10 and 3.15. `cd.yml` replaces `wheels.yml` and builds the wheels and the sdist, + uploaded to PyPI from the release run. `docs.yml` publishes the documentation to Pages. + Dependabot updates the GitHub Actions; `.pre-commit-config.yaml` holds ruff, file checks and a + check for em dashes. + # symident 0.17.0 ## Steady states diff --git a/README.md b/README.md index 29f0339..7e67e8a 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,33 @@ # symident -[![wheels](https://github.com/dModverse/symident/actions/workflows/wheels.yml/badge.svg)](https://github.com/dModverse/symident/actions/workflows/wheels.yml) -[![docs](https://img.shields.io/badge/docs-dmodverse.github.io%2Fsymident-blue)](https://dmodverse.github.io/symident/) +[![CI](https://github.com/dModverse/symident/actions/workflows/ci.yml/badge.svg)](https://github.com/dModverse/symident/actions/workflows/ci.yml) +[![PyPI](https://img.shields.io/pypi/v/symident)](https://pypi.org/project/symident/) +[![docs](https://github.com/dModverse/symident/actions/workflows/docs.yml/badge.svg)](https://dmodverse.github.io/symident/) [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE) -Structural identifiability of ODE models by Lie symmetries over finite fields. +Structural identifiability of ODE models by Lie symmetries over finite fields, local and global. -symident finds the non-identifiable directions of an ODE model with observables, -conditions, events and inputs, returns them as exact generators where possible, and -reduces the model to identifiable parameters. On request it counts the other parameter values -in the domain with the same output, the discrete symmetries, and returns them as rational maps. The rank of the OIM is computed over Fp in -a C++ kernel; closed forms are reconstructed by sparse interpolation and proven over ℚ, or -checked at random points modulo a large prime, with an error bound where one applies. +The **local analysis** computes the rank of the observability-identifiability matrix over +Fp in a C++ kernel, with the Lie order certified sufficient, and returns the +non-identifiable directions as exact generators. A rank and a closed form are proven over ℚ or +verified at random points with an error bound. The model is then reduced to identifiable +parameters, with sections certified on the declared domain. + +The **global analysis** counts the parameter values in the domain with the output of a generic +one and returns the maps between them, the discrete symmetries, as rational maps. The count is +certified exact, by the field of the output coefficients, or verified over ℚ with an error bound. + +Models have observables, conditions, events, known and unknown inputs, switches and resting +states; PEtab problems are read directly, readouts at rest included. Large models are analyzed +by kernels per chain of states over the columns each chain reads, with the jets reused across +orders. symident continues the Lie-symmetry analysis of dMod (Merkt, Timmer and Kaschek, [Phys. Rev. E 92, 012920, 2015](https://doi.org/10.1103/PhysRevE.92.012920)); the -[method page](https://dmodverse.github.io/symident/method.html) states the method and the -work it builds on. +[method chapters](https://dmodverse.github.io/symident/method.html) state the mathematics and +the work it builds on. @@ -28,54 +37,53 @@ work it builds on. pip install symident ``` -Wheels exist for Linux, macOS on Apple silicon and Windows and Python 3.10 to 3.15. The -[installation page](https://dmodverse.github.io/symident/install.html) covers the build -from source, the PEtab extra, [msolve](https://msolve.lip6.fr) for coupled steady states and -discrete symmetries, and the use from R through [dMod2](https://dmodverse.github.io/dMod2/). +Wheels exist for Linux, macOS on Apple silicon and Windows and Python 3.10 to 3.15; they depend +on NumPy, SciPy, SymPy and python-flint. The global analysis and steady states with coupled +balances need [msolve](https://msolve.lip6.fr), which `symident.install_msolve()` builds. The +[installation page](https://dmodverse.github.io/symident/install.html) covers the build from +source, the PEtab extra, msolve, and the use from R through +[dMod2](https://dmodverse.github.io/dMod2/). ## Example +The two-compartment model with an input into the first compartment, observed in the second, is +locally identifiable, but exchanging the elimination rate `k01` and the return rate `k12` keeps +the output: + ```python import symident as si -m = si.Model({"A": "-k1*A", "B": "k1*A - k2*B"}, {"y": "s*B"}) -res = si.detect(m, reconstruct=True) +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: rank 4 / 5 | 1 non-identifiable direction -#> -#> Generators X = Σᵢ ξ(i) ∂ᵢ +#> Result: structurally locally identifiable (rank 5 / 5) #> -#> Scalings: -#> X₁ (exact) -#> ξ(A) : + A -#> ξ(B) : + B -#> ξ(s) : - s -#> -#> exact = proven over Q. -res.symmetries[0].generator -#> {'A': 'A', 'B': 'B', 's': '-s'} -print(res.reduce()) -#> Reduced 1 of 1 direction. -#> -#> Trafo (non-identity entries) -#> A = 1 -#> -#> Sections: -#> {X₁} A = 1 -#> summary(detailed=True) explains each section. +#> 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 +the reparametrization to identifiable parameters; the +[quickstart](https://dmodverse.github.io/symident/quickstart.html) shows both. + ## 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`); with `discrete=True` also the discrete symmetries | +| `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 | | `reduce(result, ...)`, `result.reduce()` | reparametrization that removes the directions (`Reduction`) | +| `result.discrete(...)` | the global analysis on a result of `detect()` | | `read_petab(path)`, `Model.from_petab(path)` | a `Model` from a PEtab problem, format version 1 or 2 (`pip install "symident[petab]"`) | | `reconst_control(...)` | settings of the saturation and the reconstruction | | `switches(...)` | diagnostic and route switches for a `with` block | -| `install_msolve()` | builds msolve, needed for coupled steady states and discrete symmetries | +| `install_msolve()` | builds msolve, needed for the global analysis and coupled steady states | | `PEtabError` | raised for a PEtab problem the reader does not support | Both results print a report; `summary()` adds the computation details and @@ -86,7 +94,7 @@ Both results print a report; `summary()` adds the computation details and Simon Beyer, simon.beyer@fdm.uni-freiburg.de. Requests for further functions in model equations, questions and bug reports are welcome by e-mail or as an [issue](https://github.com/dModverse/symident/issues); the supported functions are listed -in the [user guide](https://dmodverse.github.io/symident/guide/models.html#expressions). +in the [guide](https://dmodverse.github.io/symident/guide/models.html#expressions). ## License diff --git a/cpp/bindings.cpp b/cpp/bindings.cpp index 5af8fab..19b8246 100644 --- a/cpp/bindings.cpp +++ b/cpp/bindings.cpp @@ -162,7 +162,10 @@ py::object run(F f) { } // namespace +void register_ioproj(py::module_& m); + PYBIND11_MODULE(_core, m) { + register_ioproj(m); m.doc() = "GF(p) observability kernel"; #if defined(__SIZEOF_INT128__) && !defined(SYMIDENT_NO_INT128) m.attr("has_int128") = true; @@ -185,6 +188,32 @@ PYBIND11_MODULE(_core, m) { }, arg("tapes"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("point"), arg("p_in"), arg("Nt"), arg("cores") = 1); + m.def("sym_obs_annihilates", [](py::object tapes, int nLeaves, int nStates, py::object zSlots, + py::object point, double p, int Nt, py::object V, int cores) { + List t = cv(tapes); IntegerVector z = cv(zSlots), pt = cv(point); + IntegerMatrix v = cv(V); + return run([&] { return Value(symObsAnnihilates(t, nLeaves, nStates, z, pt, p, Nt, v, cores)); }); + }, arg("tapes"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("point"), arg("p_in"), + arg("Nt"), arg("V"), arg("cores") = 1); + + m.def("sym_obs_annihilates_batch", [](py::object tapes, int nLeaves, int nStates, py::object zSlots, + py::object points, py::object primes, int Nt, py::object V, int cores) { + List t = cv(tapes); IntegerVector z = cv(zSlots); + IntegerMatrix pts = cv(points), v = cv(V); + NumericVector pr = cv(primes); + return run([&] { return Value(symObsAnnihilatesBatch(t, nLeaves, nStates, z, pts, pr, Nt, v, cores)); }); + }, arg("tapes"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("points"), arg("primes"), + arg("Nt"), arg("V"), arg("cores") = 1); + + m.def("sym_obs_cover", [](py::object tapes, int nLeaves, int nStates, py::object zSlots, py::object point, + double p, int Nt, int target, int cores, py::object order, py::object keep) { + List t = cv(tapes); IntegerVector z = cv(zSlots), pt = cv(point); + IntegerVector o = order.is_none() ? IntegerVector() : cv(order); + LogicalVector k = keep.is_none() ? LogicalVector() : cv(keep); + return run([&] { return Value(symObsCover(t, nLeaves, nStates, z, pt, p, Nt, target, cores, o, k)); }); + }, arg("tapes"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("point"), arg("p_in"), + arg("Nt"), arg("target"), arg("cores") = 1, arg("order") = py::none(), arg("keep") = py::none()); + m.def("sym_obs_chain_rank_profile", [](py::object chain, int nLeaves, int nStates, py::object zSlots, py::object point, double p, int Nt, int threads) { @@ -223,11 +252,13 @@ PYBIND11_MODULE(_core, m) { m.def("sym_obs_chain_rows", [](py::object chain, int nLeaves, int nStates, py::object zSlots, py::object point, double p, int Nt, int Mtot, int threads, - bool profile) { + bool profile, std::string session) { List c = cv(chain); IntegerVector z = cv(zSlots), pt = cv(point); - return run([&] { return Value(symObsChainRows(c, nLeaves, nStates, z, pt, p, Nt, Mtot, threads, profile)); }); + return run([&] { + return Value(symObsChainRows(c, nLeaves, nStates, z, pt, p, Nt, Mtot, threads, profile, session)); + }); }, arg("chain"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("point"), arg("p_in"), - arg("Nt"), arg("Mtot"), arg("threads") = 1, arg("profile") = false); + arg("Nt"), arg("Mtot"), arg("threads") = 1, arg("profile") = false, arg("session") = ""); m.def("sym_chain_reduce", [](py::object rows, py::object srows, int nz, int N, double p) { IntegerMatrix r = cv(rows), s = cv(srows); @@ -235,17 +266,20 @@ PYBIND11_MODULE(_core, m) { }, arg("rows"), arg("srows"), arg("nz"), arg("N"), arg("p_in")); m.def("sym_set_block_bytes", [](double bytes) { return symSetBlockBytes(bytes); }, arg("bytes")); + m.def("sym_clear_jets", []() { return symClearJets(); }); m.def("sym_segment_ranks", [](py::object segs, int nLeaves, int nStates, py::object zSlots, py::object point, double p, int Nt, py::object stateVals, - int threads, py::object dropStates, bool fromStates) { + int threads, py::object dropStates, bool fromStates, std::string session) { List s = cv(segs); IntegerVector z = cv(zSlots), pt = cv(point); IntegerMatrix sv = stateVals.is_none() ? IntegerMatrix(0, 0) : cv(stateVals); IntegerVector dr = dropStates.is_none() ? IntegerVector(0) : cv(dropStates); - return run([&] { return Value(symSegmentRanks(s, nLeaves, nStates, z, pt, p, Nt, sv, threads, dr, fromStates)); }); + return run([&] { + return Value(symSegmentRanks(s, nLeaves, nStates, z, pt, p, Nt, sv, threads, dr, fromStates, session)); + }); }, arg("segs"), arg("n_leaves"), arg("n_states"), arg("z_slots"), arg("point"), arg("p_in"), arg("Nt"), arg("state_vals") = py::none(), arg("threads") = 1, arg("drop_states") = py::none(), - arg("from_states") = false); + arg("from_states") = false, arg("session") = ""); m.def("sym_obs_null_chain_seed_batch", [](py::object chains, py::object evalChain, py::object seeds, py::object primes, int nLeaves, int nStates, @@ -288,6 +322,16 @@ PYBIND11_MODULE(_core, m) { return run([&] { return symSolveMod(a, bb, p); }); }, arg("A"), arg("b"), arg("p_in")); + m.def("sym_matmul_mod", [](py::object A, py::object B, double p, int cores) { + NumericMatrix a = cv(A), b = cv(B); + return run([&] { return Value(symMatMulMod(a, b, p, cores)); }); + }, arg("A"), arg("B"), arg("p_in"), arg("cores") = 1); + + m.def("sym_independent_rows", [](py::object M, double p, int cores) { + NumericMatrix mm = cv(M); + return run([&] { return Value(symIndependentRows(mm, p, cores)); }); + }, arg("M"), arg("p_in"), arg("cores") = 1); + m.def("sym_rref_mod", [](py::object M, double p) { NumericMatrix mm = cv(M); return run([&] { return Value(symRrefMod(mm, p)); }); diff --git a/cpp/ioproj.cpp b/cpp/ioproj.cpp new file mode 100644 index 0000000..0717820 --- /dev/null +++ b/cpp/ioproj.cpp @@ -0,0 +1,322 @@ +// Input-output projections over GF(p): polynomials evaluated at many points, the kernel of a dense matrix and the +// Taylor series of monomials in series (detection/ioproj.py). + +#include +#include +#include + +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +namespace py = pybind11; + +namespace { + +typedef uint64_t u64; +typedef int64_t i64; + +// Reduction of x < 2^62 modulo p < 2^31 through a floating-point quotient, off by at most one. +struct Mod { + u64 p; + double ip; + explicit Mod(u64 p_) : p(p_), ip(1.0 / (double)p_) {} + inline u64 red(u64 x) const { + u64 q = (u64)((double)x * ip); + i64 r = (i64)(x - q * p); + if (r < 0) r += (i64)p; + if (r >= (i64)p) r -= (i64)p; + return (u64)r; + } + inline u64 mul(u64 a, u64 b) const { return red(a * b); } + inline u64 sub(u64 a, u64 b) const { return a >= b ? a - b : a + p - b; } + u64 pow(u64 a, u64 e) const { + u64 r = 1; + while (e) { + if (e & 1) r = mul(r, a); + a = mul(a, a); + e >>= 1; + } + return r; + } + u64 inv(u64 a) const { return pow(a, p - 2); } +}; + +u64 residue(i64 v, u64 p) { + i64 r = v % (i64)p; + return (u64)(r < 0 ? r + (i64)p : r); +} + +void check_prime(double p) { + if (!(p > 2 && p < 2147483648.0)) throw std::runtime_error("the prime must lie below 2^31"); +} + +// Values of K polynomials at M points: polynomial k has the terms off[k]..off[k+1]-1, term t the exponents exps[t, :] +// and the coefficient coef[t] modulo p. +py::array_t poly_eval(py::array_t exps, + py::array_t coef, + py::array_t off, + py::array_t pts, double pIn, int threads) { + check_prime(pIn); + Mod md((u64)pIn); + if (exps.ndim() != 2 || pts.ndim() != 2 || exps.shape(1) != pts.shape(1)) + throw std::runtime_error("exponents and points need the same number of variables"); + const int T = (int)exps.shape(0), V = (int)exps.shape(1), M = (int)pts.shape(0), K = (int)off.shape(0) - 1; + const int32_t* E = exps.data(); + const i64* O = off.data(); + std::vector C(T); + for (int t = 0; t < T; ++t) C[t] = residue(coef.data()[t], md.p); + std::vector top(V, 0); + for (int t = 0; t < T; ++t) + for (int v = 0; v < V; ++v) { + if (E[t * V + v] < 0) throw std::runtime_error("negative exponent"); + if (E[t * V + v] > top[v]) top[v] = E[t * V + v]; + } + std::vector X((size_t)M * V); + for (size_t i = 0; i < X.size(); ++i) X[i] = residue(pts.data()[i], md.p); + py::array_t out({M, K}); + i64* R = out.mutable_data(); + { + py::gil_scoped_release rel; +#pragma omp parallel for schedule(dynamic, 4) num_threads(threads > 0 ? threads : 1) + for (int i = 0; i < M; ++i) { + std::vector > pw(V); + for (int v = 0; v < V; ++v) { + pw[v].resize(top[v] + 1); + pw[v][0] = 1; + for (int e = 1; e <= top[v]; ++e) pw[v][e] = md.mul(pw[v][e - 1], X[(size_t)i * V + v]); + } + for (int k = 0; k < K; ++k) { + u64 s = 0; + for (i64 t = O[k]; t < O[k + 1]; ++t) { + u64 x = C[t]; + const int32_t* e = E + t * V; + for (int v = 0; v < V && x; ++v) + if (e[v]) x = md.mul(x, pw[v][e[v]]); + s += x; + if (s >= md.p) s -= md.p; + } + R[(size_t)i * K + k] = (i64)s; + } + } + } + return out; +} + +// The kernel of A over GF(p): {"rank", "pivots", "free", "basis"}, each basis vector 1 on one free column and 0 on the +// other free columns. +py::dict kernel(py::array_t A, double pIn, int threads) { + check_prime(pIn); + Mod md((u64)pIn); + if (A.ndim() != 2) throw std::runtime_error("a matrix is needed"); + const int R = (int)A.shape(0), C = (int)A.shape(1); + std::vector W((size_t)R * C); + for (size_t i = 0; i < W.size(); ++i) W[i] = residue(A.data()[i], md.p); + std::vector piv; + { + py::gil_scoped_release rel; + // row echelon form in blocks of three pivots: the rows below see the pending pivots through their multipliers + // and take the three updates at once, f1 a1 + f2 a2 + f3 a3 < 2^64 for entries below 2^31 + const int Bk = 3; + std::vector > f(Bk, std::vector(R, 0)); + std::vector pc; + int r0 = 0, np = 0; + auto flush = [&]() { + if (!np) return; + const int lo = r0 + np, c0 = pc[0]; + const u64* P0 = &W[(size_t)r0 * C]; + const u64* P1 = np > 1 ? &W[(size_t)(r0 + 1) * C] : nullptr; + const u64* P2 = np > 2 ? &W[(size_t)(r0 + 2) * C] : nullptr; +#pragma omp parallel for schedule(static) num_threads(threads > 0 ? threads : 1) if (R - lo > 64) + for (int i = lo; i < R; ++i) { + const u64 f0 = f[0][i], f1 = np > 1 ? f[1][i] : 0, f2 = np > 2 ? f[2][i] : 0; + if (!f0 && !f1 && !f2) continue; + u64* row = &W[(size_t)i * C]; + for (int j = c0; j < C; ++j) { + u64 acc = f0 * P0[j]; + if (P1) acc += f1 * P1[j]; + if (P2) acc += f2 * P2[j]; + row[j] = md.sub(row[j], md.red(acc)); + } + } + for (int k = 0; k < np; ++k) std::fill(f[k].begin(), f[k].end(), 0); + r0 += np; + np = 0; + pc.clear(); + }; + auto colval = [&](int i, int c) { + u64 v = W[(size_t)i * C + c]; + for (int k = 0; k < np; ++k) + if (f[k][i]) v = md.sub(v, md.mul(f[k][i], W[(size_t)(r0 + k) * C + c])); + return v; + }; + for (int c = 0; c < C && r0 + np < R; ++c) { + int pr = -1; + for (int i = r0 + np; i < R; ++i) + if (colval(i, c)) { + pr = i; + break; + } + if (pr < 0) continue; + const int at = r0 + np; + if (pr != at) { + for (int j = 0; j < C; ++j) std::swap(W[(size_t)pr * C + j], W[(size_t)at * C + j]); + for (int k = 0; k < np; ++k) std::swap(f[k][pr], f[k][at]); + } + // the new pivot row takes the pending updates and is normalized + u64* prow = &W[(size_t)at * C]; + for (int k = 0; k < np; ++k) { + const u64 g = f[k][at]; + if (!g) continue; + const u64* P = &W[(size_t)(r0 + k) * C]; + for (int j = pc[k]; j < C; ++j) + if (P[j]) prow[j] = md.sub(prow[j], md.mul(g, P[j])); + f[k][at] = 0; + } + const u64 iv = md.inv(prow[c]); + for (int j = c; j < C; ++j) prow[j] = md.mul(prow[j], iv); + for (int i = at + 1; i < R; ++i) f[np][i] = colval(i, c); + pc.push_back(c); + piv.push_back(c); + ++np; + if (np == Bk) flush(); + } + flush(); + } + const int rank = (int)piv.size(); + std::vector isPiv(C, 0); + for (int c : piv) isPiv[c] = 1; + std::vector fr; + for (int c = 0; c < C; ++c) + if (!isPiv[c]) fr.push_back(c); + const int k = (int)fr.size(); + py::array_t basis({k, C}); + i64* B = basis.mutable_data(); + { + py::gil_scoped_release rel; +#pragma omp parallel for schedule(dynamic, 1) num_threads(threads > 0 ? threads : 1) + for (int q = 0; q < k; ++q) { + std::vector v(C, 0); + v[fr[q]] = 1; + for (int a = rank - 1; a >= 0; --a) { + const u64* row = &W[(size_t)a * C]; + u64 s = 0; + for (int j = piv[a] + 1; j < C; ++j) + if (row[j] && v[j]) { + s += md.mul(row[j], v[j]); + if (s >= md.p) s -= md.p; + } + v[piv[a]] = s ? md.p - s : 0; + } + for (int j = 0; j < C; ++j) B[(size_t)q * C + j] = (i64)v[j]; + } + } + py::dict out; + out["rank"] = rank; + out["pivots"] = py::cast(piv); + out["free"] = py::cast(fr); + out["basis"] = basis; + return out; +} + +// Truncated Taylor series of monomials: S holds nb series of K coefficients, mons the exponent vectors; row t of the +// result is the series of prod_v S_v^{mons[t, v]} modulo t^K. +py::array_t series_monomials(py::array_t S, + py::array_t mons, double pIn, + int threads) { + check_prime(pIn); + Mod md((u64)pIn); + const int nb = (int)S.shape(0), K = (int)S.shape(1), T = (int)mons.shape(0); + if (mons.shape(1) != nb) throw std::runtime_error("monomials and series differ in the number of variables"); + const int32_t* E = mons.data(); + std::vector base((size_t)nb * K); + for (size_t i = 0; i < base.size(); ++i) base[i] = residue(S.data()[i], md.p); + std::vector top(nb, 0); + for (int t = 0; t < T; ++t) + for (int v = 0; v < nb; ++v) top[v] = std::max(top[v], (int)E[t * nb + v]); + auto mul = [&](const u64* a, const u64* b, u64* c) { + for (int n = 0; n < K; ++n) { + u64 s = 0; + for (int i = 0; i <= n; ++i) s = md.red(s + a[i] * b[n - i]); + c[n] = s; + } + }; + py::array_t out({T, K}); + i64* R = out.mutable_data(); + { + py::gil_scoped_release rel; + // the powers of each series + std::vector > > pw(nb); + for (int v = 0; v < nb; ++v) { + pw[v].assign(top[v] + 1, std::vector(K, 0)); + pw[v][0][0] = 1; + for (int e = 1; e <= top[v]; ++e) mul(pw[v][e - 1].data(), &base[(size_t)v * K], pw[v][e].data()); + } +#pragma omp parallel for schedule(dynamic, 4) num_threads(threads > 0 ? threads : 1) + for (int t = 0; t < T; ++t) { + std::vector acc(K, 0), tmp(K); + acc[0] = 1; + for (int v = 0; v < nb; ++v) { + int e = E[t * nb + v]; + if (!e) continue; + mul(acc.data(), pw[v][e].data(), tmp.data()); + acc.swap(tmp); + } + for (int n = 0; n < K; ++n) R[(size_t)t * K + n] = (i64)acc[n]; + } + } + return out; +} + +// The values of the monomials mons (T x nb exponents) at the rows of B (M x nb values) modulo p, M x T. +py::array_t mono_matrix(py::array_t B, + py::array_t mons, double pIn, + int threads) { + check_prime(pIn); + Mod md((u64)pIn); + const int M = (int)B.shape(0), nb = (int)B.shape(1), T = (int)mons.shape(0); + if (mons.shape(1) != nb) throw std::runtime_error("monomials and values differ in the number of variables"); + const int32_t* E = mons.data(); + std::vector top(nb, 0); + for (int t = 0; t < T; ++t) + for (int v = 0; v < nb; ++v) top[v] = std::max(top[v], (int)E[t * nb + v]); + std::vector X((size_t)M * nb); + for (size_t i = 0; i < X.size(); ++i) X[i] = residue(B.data()[i], md.p); + py::array_t out({M, T}); + i64* R = out.mutable_data(); + { + py::gil_scoped_release rel; +#pragma omp parallel for schedule(static) num_threads(threads > 0 ? threads : 1) + for (int i = 0; i < M; ++i) { + std::vector > pw(nb); + for (int v = 0; v < nb; ++v) { + pw[v].resize(top[v] + 1); + pw[v][0] = 1; + for (int e = 1; e <= top[v]; ++e) pw[v][e] = md.mul(pw[v][e - 1], X[(size_t)i * nb + v]); + } + for (int t = 0; t < T; ++t) { + u64 x = 1; + for (int v = 0; v < nb; ++v) + if (E[t * nb + v]) x = md.mul(x, pw[v][E[t * nb + v]]); + R[(size_t)i * T + t] = (i64)x; + } + } + } + return out; +} + +} // namespace + +void register_ioproj(py::module_& m) { + m.def("io_poly_eval", &poly_eval, py::arg("exps"), py::arg("coef"), py::arg("off"), py::arg("points"), + py::arg("p"), py::arg("threads") = 1); + m.def("io_kernel", &kernel, py::arg("A"), py::arg("p"), py::arg("threads") = 1); + m.def("io_mono_matrix", &mono_matrix, py::arg("B"), py::arg("mons"), py::arg("p"), py::arg("threads") = 1); + m.def("io_series_monomials", &series_monomials, py::arg("S"), py::arg("mons"), py::arg("p"), + py::arg("threads") = 1); +} diff --git a/cpp/kernel.cpp b/cpp/kernel.cpp index 6cf59d6..fc35e58 100644 --- a/cpp/kernel.cpp +++ b/cpp/kernel.cpp @@ -10,6 +10,7 @@ #include "kernel.h" #include +#include #include #include #include @@ -19,6 +20,11 @@ #include #include #include +#include +#if defined(__GLIBC__) +#include +#endif +#include #ifdef _OPENMP #include @@ -434,6 +440,165 @@ std::vector rref_mod(std::vector >& A, u64 p) { return pivots; } +// ---- Reduced echelon basis, rows added a batch at a time ---- +// Basis rows live on the non-pivot columns `cols` (ascending), 1 at the pivot of the row, 0 at the other pivots. +// A batch is reduced by the basis in parallel, echelonized, and clears the basis at the new pivots; the reduced +// form of a row space is unique, so the result does not depend on the batching. +struct RrefBasis { + int nz; + u64 p; + std::vector cols, piv; // free columns; the pivot column of each row + std::vector > rows; // per basis row, the entries at `cols` + RrefBasis(int nz_, u64 p_) : nz(nz_), p(p_) { + cols.resize(nz); + for (int c = 0; c < nz; ++c) cols[c] = c; + } + int rank() const { return (int)piv.size(); } + + // the rows of X (nz residues each, reduced below p) added; X is consumed. With `from`, the indices of the rows + // of X that are independent of the basis and of the rows of X before them, ascending + void add(std::vector >& X, int threads, std::vector* from = nullptr) { + if (X.empty() || cols.empty()) return; + int m = (int)X.size(), nf = (int)cols.size(), r = rank(); + const Barrett br(p); + const u64 LIM = (((u64)1 << 63) / p) * p; + // reduction by the basis: y = x at the free columns minus the sum of x at the pivots times the rows + std::vector > Y(m); + OmpGuard guard_; + int nThr = std::max(1, std::min(threads, m)); + #pragma omp parallel for num_threads(nThr) schedule(dynamic, 16) if (nThr > 1) + for (int i = 0; i < m; ++i) { + try { + std::vector acc(nf, 0); + const std::vector& x = X[i]; + for (int j = 0; j < r; ++j) { + u64 f = x[piv[j]] % p; + if (!f) continue; + const u64* bj = rows[j].data(); + for (int n = 0; n < nf; ++n) { + u64 t = acc[n] + f * bj[n]; + acc[n] = t >= LIM ? t - LIM : t; + } + } + std::vector& y = Y[i]; + y.resize(nf); + bool any = false; + for (int n = 0; n < nf; ++n) { + y[n] = submod(x[cols[n]] % p, br.red(acc[n]), p); + any |= y[n] != 0; + } + if (!any) y.clear(); + std::vector().swap(X[i]); + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + // echelon of the reduced rows among themselves, a chunk at a time: the rows of a chunk are reduced by + // the new rows of the earlier chunks in parallel, then by each other in order + std::vector > E; + std::vector epiv; // position in `cols` of each new pivot + auto reduce_by = [&](std::vector& y, size_t k0, size_t k1) { + for (size_t k = k0; k < k1; ++k) { + u64 f = y[epiv[k]]; + if (!f) continue; + u64 nfac = p - f; + const u64* e = E[k].data(); + for (int n = 0; n < nf; ++n) + if (e[n]) y[n] = br.red(y[n] + nfac * e[n]); + } + }; + const int CH = 64; + for (int i0 = 0; i0 < m; i0 += CH) { + int i1 = std::min(m, i0 + CH); + size_t q0 = E.size(); + int nThr3 = std::max(1, std::min(threads, i1 - i0)); + #pragma omp parallel for num_threads(nThr3) schedule(static, 1) if (nThr3 > 1 && q0 > 0) + for (int i = i0; i < i1; ++i) + if (!Y[i].empty()) reduce_by(Y[i], 0, q0); + for (int i = i0; i < i1; ++i) { + std::vector& y = Y[i]; + if (y.empty()) continue; + reduce_by(y, q0, E.size()); + int pc = -1; + for (int n = 0; n < nf; ++n) if (y[n]) { pc = n; break; } + if (pc < 0) continue; + u64 inv = invmod(y[pc], p); + for (int n = pc; n < nf; ++n) if (y[n]) y[n] = br.red(y[n] * inv); + E.push_back(std::move(y)); + epiv.push_back(pc); + if (from) from->push_back(i); + } + } + if (E.empty()) return; + int q = (int)E.size(); + // the new rows reduced at each other's pivots + int nThr4 = std::max(1, std::min(threads, q)); + for (int k = 0; k < q; ++k) { + const u64* ek = E[k].data(); + #pragma omp parallel for num_threads(nThr4) schedule(static, 16) if (nThr4 > 1 && q > 64) + for (int l = 0; l < q; ++l) { + if (l == k) continue; + u64 f = E[l][epiv[k]]; + if (!f) continue; + u64 nfac = p - f; + u64* el = E[l].data(); + for (int n = 0; n < nf; ++n) + if (ek[n]) el[n] = br.red(el[n] + nfac * ek[n]); + } + } + // the old rows cleared at the new pivots + int nThr2 = std::max(1, std::min(threads, r)); + #pragma omp parallel for num_threads(nThr2) schedule(dynamic, 16) if (nThr2 > 1) + for (int j = 0; j < r; ++j) { + std::vector& bj = rows[j]; + for (int k = 0; k < q; ++k) { + u64 f = bj[epiv[k]]; + if (!f) continue; + u64 nfac = p - f; + const u64* e = E[k].data(); + for (int n = 0; n < nf; ++n) + if (e[n]) bj[n] = br.red(bj[n] + nfac * e[n]); + } + } + // the new pivots leave the free columns + std::vector isNew(nf, 0); + for (int k = 0; k < q; ++k) isNew[epiv[k]] = 1; + std::vector keep; + for (int n = 0; n < nf; ++n) if (!isNew[n]) keep.push_back(n); + auto compact = [&](std::vector& v) { + std::vector w(keep.size()); + for (size_t n = 0; n < keep.size(); ++n) w[n] = v[keep[n]]; + v.swap(w); + }; + for (auto& bj : rows) compact(bj); + for (int k = 0; k < q; ++k) { + piv.push_back(cols[epiv[k]]); + compact(E[k]); + rows.push_back(std::move(E[k])); + } + std::vector nc(keep.size()); + for (size_t n = 0; n < keep.size(); ++n) nc[n] = cols[keep[n]]; + cols.swap(nc); + } + + // the basis as full rows ordered by pivot column, as rref_mod returns them + void full(std::vector >& R, std::vector& pivots) const { + int r = rank(); + std::vector ord(r); + for (int j = 0; j < r; ++j) ord[j] = j; + std::sort(ord.begin(), ord.end(), [&](int x, int y) { return piv[x] < piv[y]; }); + R.assign(r, std::vector(nz, 0)); + pivots.assign(r, 0); + for (int i = 0; i < r; ++i) { + int j = ord[i]; + pivots[i] = piv[j]; + R[i][piv[j]] = 1; + for (size_t n = 0; n < cols.size(); ++n) R[i][cols[n]] = rows[j][n]; + } + } +}; + // ---- Rank over GF(p)((eps)) of rows truncated at eps^N ---- // A series row holds nz entries, each a truncated power series: coefficient d of // entry c at c*N + d. Rows are reduced with a pivot of minimal valuation over the @@ -918,8 +1083,21 @@ bool build_obs_rows(std::vector >& val, int m = (int)stateSlots.size(); std::vector > invA0(nInstr); bool fail = false; + // values constant in time: zero past order 0, so a product with one takes a single term + std::vector tconst(instrBase + nInstr, 0); + { + std::vector isState(instrBase, 0); + for (int s : stateSlots) if (s >= 0 && s < instrBase) isState[s] = 1; + for (int v = 0; v < instrBase; ++v) tconst[v] = !isState[v]; + for (int i = 0; i < nInstr; ++i) { + int o = op[i]; + tconst[instrBase + i] = o == OP_CONST || ((o == OP_ADD || o == OP_MUL) && tconst[a[i]] && tconst[b[i]]) || + (o == OP_INV && tconst[a[i]]); + } + } for (int k = 0; k <= Nt && !fail; ++k) { for (int i = 0; i < nInstr; ++i) { + if (k > 0 && tconst[instrBase + i]) continue; u64* o = val[instrBase + i].data() + (size_t)k * w; switch (op[i]) { case OP_CONST: @@ -934,7 +1112,8 @@ bool build_obs_rows(std::vector >& val, case OP_MUL: { const u64* pa = val[a[i]].data(); const u64* pb = val[b[i]].data(); - for (int ii = 0; ii <= k; ++ii) + int j0 = tconst[b[i]] ? k : 0, j1 = tconst[a[i]] ? 0 : k; + for (int ii = j0; ii <= j1; ++ii) dual_mul_acc(o, pa + (size_t)ii * w, pb + (size_t)(k - ii) * w, w, p); break; } @@ -1115,7 +1294,8 @@ inline bool lb_inv(LBlk& out, const LBlk& a, const PolyBasis& pb, u64 p) { // that is 0/0 at the start) is evaluated after the recursion as a Laurent series; where the // truncation needs more orders, the recursion is run again further. Rows of negative order // (poles of the dual lanes, e.g. along a state of the start) go to `preRows` as -// (output, -order, monomial, lanes...); without it, a pole fails. +// (output, -order, monomial, lanes...); without it, a pole fails. `deferredOut` is set where an +// instruction is taken as a Laurent series. bool build_obs_rows_poly(std::vector >& val, const std::vector& op, const std::vector& a, const std::vector& b, const std::vector& cval, @@ -1125,7 +1305,7 @@ bool build_obs_rows_poly(std::vector >& val, std::vector >& rows, const u64* dtau = nullptr, std::vector >* preRows = nullptr, int depth = 0, - int need = -1, int spowAxis0 = -1) { + int need = -1, int spowAxis0 = -1, char* deferredOut = nullptr) { if (need < 0) need = Nrun + 1; int nInstr = (int)op.size(); int m = (int)stateSlots.size(); @@ -1259,6 +1439,7 @@ bool build_obs_rows_poly(std::vector >& val, if (fcone[i]) { fail = true; break; } deferred[i] = 1; anyDeferred = true; + if (deferredOut) *deferredOut = 1; } if (deferred[i] || (k > 0 && tconst[instrBase + i])) continue; u64* o = val[instrBase + i].data() + (size_t)k * blk; @@ -1536,15 +1717,26 @@ bool build_obs_rows_poly(std::vector >& val, // constants and the IC map as decimal strings, an optional steady-state seed // icSeed as raw ints. Constants are reduced per prime in build_one_condition, so // one extraction serves every prime (the batch path relies on this). +// A condition of a shared tape sets leaves: leaf ovSlot[i] takes the value and duals of leaf +// ovSrc[i], or the constant ovNum[i]/ovDen[i] where ovSrc[i] < 0. struct CondRaw { std::vector op, a, b, stateSlots, fOut, gOut, icLeaf, icOp, icA, icB, icOut; std::vector cnum, cden, icCnum, icCden, icNum, icDen; bool hasIcTape, hasIcSeed; std::vector > icSeedRaw; + std::vector ovSlot, ovSrc; + std::vector ovNum, ovDen; }; +void extract_leaf_set(const List& tp, CondRaw& cd) { + if (!tp.containsElementNamed("leaf_slot")) return; + cd.ovSlot = to_ivec(tp["leaf_slot"]); cd.ovSrc = to_ivec(tp["leaf_src"]); + cd.ovNum = to_svec(tp["leaf_num"]); cd.ovDen = to_svec(tp["leaf_den"]); +} + CondRaw extract_cond_raw(List tp, int nStates, int w) { CondRaw cd; + extract_leaf_set(tp, cd); cd.op = to_ivec(tp["op"]); cd.a = to_ivec(tp["a"]); cd.b = to_ivec(tp["b"]); cd.stateSlots = to_ivec(tp["state_slots"]); cd.fOut = to_ivec(tp["f_out"]); cd.gOut = to_ivec(tp["g_out"]); @@ -1567,23 +1759,79 @@ CondRaw extract_cond_raw(List tp, int nStates, int w) { return cd; } -// Build one condition's observability rows at a single point/prime. leafVal holds -// each leaf's value and dual already reduced mod p; the tape and IC constants are -// reduced from their strings here, so the same CondRaw serves any prime. Returns -// false on a vanishing denominator (tape reciprocal or reciprocal IC). -bool build_one_condition(const CondRaw& cd, - const std::vector >& leafVal, - int nLeaves, int nStates, int nz, int w, int Nt, u64 p, - std::vector >& outRows, bool laurent = false) { - int nInstr = (int)cd.op.size(); - int instrBase = nLeaves + nStates; - int S = instrBase + nInstr; +// The tapes of a call. A tape with an entry `base` holds the arrays of the earlier tape `base` and +// only the leaves it sets, so that the arrays of a shared tape are read once. +struct TapeSet { + std::vector td; + std::vector base; + TapeSet(List& tapes, int nStates, int w) { + int T = tapes.size(); + td.resize(T); + base.resize(T); + for (int t = 0; t < T; ++t) { + List tp = tapes[t]; + base[t] = t; + if (tp.containsElementNamed("base")) { + base[t] = (int)tp["base"]; + if (base[t] < 0 || base[t] >= t || base[base[t]] != base[t]) + throw std::invalid_argument("a tape names a base that is no earlier full tape"); + extract_leaf_set(tp, td[t]); + } else { + td[t] = extract_cond_raw(tp, nStates, w); + } + } + } + int size() const { return (int)td.size(); } + // tape t, assembled in `tmp` where it holds the arrays of a base + const CondRaw& get(int t, CondRaw& tmp) const { + if (base[t] == t) return td[t]; + tmp = td[base[t]]; + tmp.ovSlot = td[t].ovSlot; tmp.ovSrc = td[t].ovSrc; + tmp.ovNum = td[t].ovNum; tmp.ovDen = td[t].ovDen; + return tmp; + } +}; + +// The leaves of a condition: the shared leaf values with the leaves the condition sets replaced. +struct LeafView { + const std::vector >& base; + std::vector at; + std::vector > own; + explicit LeafView(const std::vector >& b) : base(b) {} + const std::vector& operator[](int L) const { + return (!at.empty() && at[L] >= 0) ? own[at[L]] : base[L]; + } +}; + +LeafView cond_leaves(const CondRaw& cd, const std::vector >& leafVal, int w, u64 p) { + LeafView v(leafVal); + if (cd.ovSlot.empty()) return v; + v.at.assign(leafVal.size(), -1); + for (size_t i = 0; i < cd.ovSlot.size(); ++i) { + v.at[cd.ovSlot[i]] = (int)v.own.size(); + if (cd.ovSrc[i] >= 0) { + v.own.push_back(leafVal[cd.ovSrc[i]]); + } else { + std::vector c(w, 0); + c[0] = reduce_rational(cd.ovNum[i], cd.ovDen[i], p); + v.own.push_back(c); + } + } + return v; +} - std::vector cval(nInstr, 0); +// The constants of a condition's tape modulo p and the start of each state as a dual of width w. +// False on a vanishing denominator of a start value. +bool cond_start(const CondRaw& cd, const std::vector >& leafVal, + int nLeaves, int nStates, int w, u64 p, std::vector& cval, + std::vector >& st0) { + int nInstr = (int)cd.op.size(); + cval.assign(nInstr, 0); for (int i = 0; i < nInstr; ++i) if (cd.op[i] == OP_CONST) cval[i] = reduce_rational(cd.cnum[i], cd.cden[i], p); + const LeafView lv = cond_leaves(cd, leafVal, w, p); std::vector > icVal; if (cd.hasIcTape && !cd.hasIcSeed) { int nIc = (int)cd.icOp.size(); @@ -1591,9 +1839,15 @@ bool build_one_condition(const CondRaw& cd, for (int i = 0; i < nIc; ++i) if (cd.icOp[i] == OP_CONST) icCval[i] = reduce_rational(cd.icCnum[i], cd.icCden[i], p); - icVal.assign(nLeaves + nIc, std::vector(w, 0)); - for (int L = 0; L < nLeaves; ++L) - for (int c = 0; c < w; ++c) icVal[L][c] = leafVal[L][c]; + // the leaves the initial-value tape reads + icVal.assign(nLeaves + nIc, std::vector()); + auto need = [&](int s) { if (s >= 0 && s < nLeaves && icVal[s].empty()) icVal[s] = lv[s]; }; + for (int i = 0; i < nIc; ++i) { + icVal[nLeaves + i].assign(w, 0); + if (cd.icOp[i] == OP_CONST) continue; + need(cd.icA[i]); + if (cd.icOp[i] == OP_ADD || cd.icOp[i] == OP_MUL) need(cd.icB[i]); + } if (!eval_ic_order0(icVal, cd.icOp, cd.icA, cd.icB, icCval, nLeaves, w, p)) return false; } @@ -1605,23 +1859,46 @@ bool build_one_condition(const CondRaw& cd, icConst[i] = reduce_rational(cd.icNum[i], cd.icDen[i], p); } - std::vector > val(S, std::vector((size_t)(Nt + 1) * w, 0)); - for (int L = 0; L < nLeaves; ++L) - for (int c = 0; c < w; ++c) val[L][c] = leafVal[L][c]; + st0.assign(cd.stateSlots.size(), std::vector(w, 0)); for (int i = 0; i < (int)cd.stateSlots.size(); ++i) { - int slot = cd.stateSlots[i]; if (cd.hasIcSeed) { - for (int c = 0; c < w; ++c) val[slot][c] = red(cd.icSeedRaw[i][c], p); + for (int c = 0; c < w; ++c) st0[i][c] = red(cd.icSeedRaw[i][c], p); continue; } int src = cd.hasIcTape ? cd.icOut[i] : (cd.icLeaf[i] >= 0 ? cd.icLeaf[i] : -1); if (src >= 0) { - const std::vector& s = src < nLeaves ? leafVal[src] : icVal[src]; - for (int c = 0; c < w; ++c) val[slot][c] = s[c]; + const std::vector& s = src < nLeaves ? lv[src] : icVal[src]; + for (int c = 0; c < w; ++c) st0[i][c] = s[c]; } else { - val[slot][0] = icConst[i]; + st0[i][0] = icConst[i]; } } + return true; +} + +// Build one condition's observability rows at a single point/prime. leafVal holds +// each leaf's value and dual already reduced mod p; the tape and IC constants are +// reduced from their strings here, so the same CondRaw serves any prime. Returns +// false on a vanishing denominator (tape reciprocal or reciprocal IC). +bool build_one_condition(const CondRaw& cd, + const std::vector >& leafVal, + int nLeaves, int nStates, int nz, int w, int Nt, u64 p, + std::vector >& outRows, bool laurent = false) { + int nInstr = (int)cd.op.size(); + int instrBase = nLeaves + nStates; + int S = instrBase + nInstr; + std::vector cval; + std::vector > st0; + if (!cond_start(cd, leafVal, nLeaves, nStates, w, p, cval, st0)) return false; + + std::vector > val(S, std::vector((size_t)(Nt + 1) * w, 0)); + { + const LeafView lv = cond_leaves(cd, leafVal, w, p); + for (int L = 0; L < nLeaves; ++L) + for (int c = 0; c < w; ++c) val[L][c] = lv[L][c]; + } + for (int i = 0; i < (int)cd.stateSlots.size(); ++i) + for (int c = 0; c < w; ++c) val[cd.stateSlots[i]][c] = st0[i][c]; if (laurent) { // one axis per power of a state at 0, within the total degree Nt (a power counts at @@ -1649,12 +1926,302 @@ bool build_one_condition(const CondRaw& cd, return build_one_condition(cd, leafVal, nLeaves, nStates, nz, w, Nt, p, outRows, true); } +// SYMIDENT_KERNEL_MODE: `forward` or `reverse` fixes the mode of the rows, `check` builds a call in +// both and requires equal rows; otherwise the mode that sweeps fewer residues. +enum { KM_AUTO, KM_FORWARD, KM_REVERSE, KM_CHECK }; +int kernel_mode() { + const char* e = std::getenv("SYMIDENT_KERNEL_MODE"); + std::string m = e ? e : ""; + if (m == "forward") return KM_FORWARD; + if (m == "reverse") return KM_REVERSE; + if (m == "check") return KM_CHECK; + return KM_AUTO; +} + +// rows of the two modes, equal modulo p, or an error naming the call +void require_same_rows(const std::vector >& fw, + const std::vector >& rv, u64 p, const char* what) { + bool same = fw.size() == rv.size(); + for (size_t i = 0; same && i < fw.size(); ++i) { + same = fw[i].size() == rv[i].size(); + for (size_t c = 0; same && c < fw[i].size(); ++c) same = fw[i][c] % p == rv[i][c] % p; + } + if (!same) + throw std::runtime_error(std::string("kernel: the reverse mode differs from the forward mode (") + + what + ")"); +} + +// dst += c * src over n residues +inline void axpy_mod(u64* dst, const u64* src, u64 c, int n, const Barrett& br) { + for (int j = 0; j < n; ++j) dst[j] = br.red(dst[j] + src[j] * c); +} + +// ---- Reverse mode of build_one_condition ---- +// A pass of the values alone, then adjoint sweeps over blocks of rows. Row r is output r % nOut at +// order Nt - r / nOut, so the sweep down from order j covers a prefix of the rows. +struct RevPass { + int nOut = 0, Nt = 0, S = 0, nMarked = 0; + std::vector > v; // Taylor values per slot + std::vector > nsq; // per reciprocal: -(o*o) as a series + std::vector > > d0; // per slot: the duals at order 0 + std::vector tconst; // values constant in time + std::vector mark; // slot*(Nt+1)+k: adjoint index or -1 +}; + +enum { REV_OK, REV_FAIL, REV_FORWARD }; + +// The orders ii of A in sum_ii A_ii B_(k-ii) where neither factor vanishes for being constant in time +inline void conv_range(bool ca, bool cb, int k, int& j0, int& j1) { + j0 = cb ? k : 0; + j1 = ca ? 0 : k; +} + +// The values and the adjoint cells of the reverse mode. REV_FAIL on a vanishing denominator of a +// start value; REV_FORWARD for an operation other than CONST/ADD/MUL/INV or a reciprocal without +// value at order 0, which the forward mode takes as a Laurent series. +int rev_values(const CondRaw& cd, const std::vector >& leafVal, + int nLeaves, int nStates, int w, int Nt, u64 p, RevPass& rp) { + int nInstr = (int)cd.op.size(), instrBase = nLeaves + nStates; + int S = instrBase + nInstr, N1 = Nt + 1; + for (int o : cd.op) + if (o != OP_CONST && o != OP_ADD && o != OP_MUL && o != OP_INV) return REV_FORWARD; + std::vector cval; + std::vector > st0; + if (!cond_start(cd, leafVal, nLeaves, nStates, w, p, cval, st0)) return REV_FAIL; + rp.nOut = (int)cd.gOut.size(); rp.Nt = Nt; rp.S = S; + rp.v.assign(S, std::vector(N1, 0)); + rp.d0.assign(S, {}); + std::vector isState(S, 0); + for (int s : cd.stateSlots) isState[s] = 1; + rp.tconst.assign(S, 0); + for (int L = 0; L < instrBase; ++L) rp.tconst[L] = !isState[L]; + const LeafView lv = cond_leaves(cd, leafVal, w, p); + for (int L = 0; L < nLeaves; ++L) { + const std::vector& x = lv[L]; + rp.v[L][0] = x[0] % p; + for (int c = 1; c < w; ++c) + if (x[c] % p) rp.d0[L].push_back({c - 1, x[c] % p}); + } + for (size_t i = 0; i < cd.stateSlots.size(); ++i) { + int s = cd.stateSlots[i]; + rp.v[s][0] = st0[i][0] % p; + rp.d0[s].clear(); + for (int c = 1; c < w; ++c) + if (st0[i][c] % p) rp.d0[s].push_back({c - 1, st0[i][c] % p}); + } + for (int i = 0; i < nInstr; ++i) { + int o = cd.op[i], a = cd.a[i], b = cd.b[i]; + rp.tconst[instrBase + i] = o == OP_CONST || + ((o == OP_ADD || o == OP_MUL) && rp.tconst[a] && rp.tconst[b]) || + (o == OP_INV && rp.tconst[a]); + } + const Barrett br(p); + for (int k = 0; k <= Nt; ++k) { + for (int i = 0; i < nInstr; ++i) { + int s = instrBase + i; + if (k > 0 && rp.tconst[s]) continue; + int a = cd.a[i], b = cd.b[i]; + u64& o = rp.v[s][k]; + switch (cd.op[i]) { + case OP_CONST: o = cval[i]; break; + case OP_ADD: o = addmod(rp.v[a][k], rp.v[b][k], p); break; + case OP_MUL: { + int j0, j1; + conv_range(rp.tconst[a], rp.tconst[b], k, j0, j1); + u64 acc = 0; + for (int ii = j0; ii <= j1; ++ii) acc = br.red(acc + rp.v[a][ii] * rp.v[b][k - ii]); + o = acc; + break; + } + case OP_INV: + if (k == 0) { + if (rp.v[a][0] == 0) return REV_FORWARD; + o = invmod(rp.v[a][0], p); + } else { + u64 acc = 0; + for (int j = 1; j <= k; ++j) acc = br.red(acc + rp.v[a][j] * rp.v[s][k - j]); + o = mulmod(submod(0, acc, p), rp.v[s][0], p); + } + break; + } + } + if (k == Nt) break; + u64 ik = invmod((u64)(k + 1), p); + for (size_t i = 0; i < cd.stateSlots.size(); ++i) + rp.v[cd.stateSlots[i]][k + 1] = mulmod(rp.v[cd.fOut[i]][k], ik, p); + } + rp.nsq.assign(nInstr, {}); + for (int i = 0; i < nInstr; ++i) { + if (cd.op[i] != OP_INV) continue; + const std::vector& o = rp.v[instrBase + i]; + rp.nsq[i].assign(N1, 0); + int top = rp.tconst[instrBase + i] ? 1 : N1; + for (int k = 0; k < top; ++k) { + u64 s = 0; + for (int j = 0; j <= k; ++j) s = br.red(s + o[j] * o[k - j]); + rp.nsq[i][k] = submod(0, s, p); + } + } + // the cells an adjoint reaches: a leaf or a start with a dual at order 0, a state past order 0, + // an instruction that is not a constant, past order 0 only where it varies in time + auto live = [&](int s, int k) { + if (s < instrBase) return isState[s] ? (k > 0 || !rp.d0[s].empty()) : (k == 0 && !rp.d0[s].empty()); + if (cd.op[s - instrBase] == OP_CONST) return false; + return k == 0 || !rp.tconst[s]; + }; + rp.mark.assign((size_t)S * N1, -1); + rp.nMarked = 0; + auto mark = [&](int s, int k) { + int& m = rp.mark[(size_t)s * N1 + k]; + if (m < 0 && live(s, k)) m = rp.nMarked++; + }; + for (int g : cd.gOut) + for (int k = 0; k <= Nt; ++k) mark(g, k); + for (int k = Nt; k >= 0; --k) { + if (k < Nt) + for (size_t i = 0; i < cd.stateSlots.size(); ++i) + if (rp.mark[(size_t)cd.stateSlots[i] * N1 + k + 1] >= 0) mark(cd.fOut[i], k); + for (int i = nInstr - 1; i >= 0; --i) { + if (rp.mark[(size_t)(instrBase + i) * N1 + k] < 0) continue; + int a = cd.a[i], b = cd.b[i]; + switch (cd.op[i]) { + case OP_ADD: mark(a, k); mark(b, k); break; + case OP_MUL: { + int j0, j1; + conv_range(rp.tconst[a], rp.tconst[b], k, j0, j1); + for (int ii = j0; ii <= j1; ++ii) { + if (rp.v[b][k - ii]) mark(a, ii); + if (rp.v[a][ii]) mark(b, k - ii); + } + break; + } + case OP_INV: + for (int ii = 0; ii <= (rp.tconst[a] ? 0 : k); ++ii) + if (rp.nsq[i][k - ii]) mark(a, ii); + break; + } + } + } + return REV_OK; +} + +// The adjoint sweep over rows [r0, r1) of the order-descending numbering; `out` receives the +// entries of each row over the nz columns. +void rev_sweep(const CondRaw& cd, const RevPass& rp, int nLeaves, int nStates, int nz, + u64 p, int r0, int r1, std::vector >& out) { + int B = r1 - r0, Nt = rp.Nt, N1 = Nt + 1, nOut = rp.nOut; + int nInstr = (int)cd.op.size(), instrBase = nLeaves + nStates; + const Barrett br(p); + std::vector pool((size_t)rp.nMarked * B, 0); + auto at = [&](int s, int k) -> u64* { + int m = rp.mark[(size_t)s * N1 + k]; + return m < 0 ? nullptr : pool.data() + (size_t)m * B; + }; + for (int k = Nt; k >= 0; --k) { + int act = std::min(B, nOut * (Nt - k + 1) - r0); + if (act <= 0) continue; + for (int r = std::max(r0, nOut * (Nt - k)); r < std::min(r1, nOut * (Nt - k + 1)); ++r) + if (u64* g = at(cd.gOut[r % nOut], k)) g[r - r0] = addmod(g[r - r0], 1, p); + if (k < Nt) { + u64 ik = invmod((u64)(k + 1), p); + for (size_t i = 0; i < cd.stateSlots.size(); ++i) { + const u64* src = at(cd.stateSlots[i], k + 1); + u64* dst = at(cd.fOut[i], k); + if (src && dst) axpy_mod(dst, src, ik, act, br); + } + } + for (int i = nInstr - 1; i >= 0; --i) { + const u64* o = at(instrBase + i, k); + if (!o) continue; + int a = cd.a[i], b = cd.b[i]; + switch (cd.op[i]) { + case OP_ADD: + if (u64* d = at(a, k)) axpy_mod(d, o, 1, act, br); + if (u64* d = at(b, k)) axpy_mod(d, o, 1, act, br); + break; + case OP_MUL: { + int j0, j1; + conv_range(rp.tconst[a], rp.tconst[b], k, j0, j1); + for (int ii = j0; ii <= j1; ++ii) { + u64 vb = rp.v[b][k - ii], va = rp.v[a][ii]; + if (vb) if (u64* d = at(a, ii)) axpy_mod(d, o, vb, act, br); + if (va) if (u64* d = at(b, k - ii)) axpy_mod(d, o, va, act, br); + } + break; + } + case OP_INV: + for (int ii = 0; ii <= (rp.tconst[a] ? 0 : k); ++ii) { + u64 c = rp.nsq[i][k - ii]; + if (c) if (u64* d = at(a, ii)) axpy_mod(d, o, c, act, br); + } + break; + } + } + } + out.assign(B, std::vector(nz, 0)); + for (int s = 0; s < rp.S; ++s) { + if (rp.d0[s].empty()) continue; + const u64* ad = at(s, 0); + if (!ad) continue; + for (int rr = 0; rr < B; ++rr) { + if (!ad[rr]) continue; + for (const auto& e : rp.d0[s]) + out[rr][e.first] = br.red(out[rr][e.first] + ad[rr] * e.second); + } + } +} + +double chain_block_bytes(); + +// The rows of build_one_condition in reverse mode, in the order of the forward mode; REV_FAIL and +// REV_FORWARD as rev_values. +int build_one_condition_reverse(const CondRaw& cd, + const std::vector >& leafVal, + int nLeaves, int nStates, int nz, int Nt, u64 p, + std::vector >& outRows, int threads) { + RevPass rp; + int st = rev_values(cd, leafVal, nLeaves, nStates, nz + 1, Nt, p, rp); + if (st != REV_OK) return st; + int nRows = rp.nOut * (Nt + 1); + if (nRows == 0) return REV_OK; + // rows per block: split over the threads, and bounded so that one block's adjoints stay within + // the budget of chain_block_bytes() + double perRow = std::max(1.0, (double)rp.nMarked * 8.0); + int Bmem = std::max(1, (int)(chain_block_bytes() / perRow)); + int Bt = threads > 1 ? (nRows + threads - 1) / threads : nRows; + int B = std::max(1, std::min(Bt, Bmem)); + int nb = (nRows + B - 1) / B; + std::vector > > rB(nb); + int nThr = std::max(1, std::min(threads, nb)); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1) + for (int b = 0; b < nb; ++b) { + try { + rev_sweep(cd, rp, nLeaves, nStates, nz, p, b * B, std::min(nRows, (b + 1) * B), rB[b]); + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + size_t r0 = outRows.size(); + outRows.resize(r0 + nRows); + for (int b = 0; b < nb; ++b) + for (size_t i = 0; i < rB[b].size(); ++i) { + int r = b * B + (int)i, gi = r % rp.nOut, k = Nt - r / rp.nOut; + outRows[r0 + (size_t)gi * (Nt + 1) + k] = std::move(rB[b][i]); + } + return REV_OK; +} + +// The reverse mode sweeps about half the rows per order, the forward mode every column. +bool reverse_pays(size_t nOut, int nz, int Nt) { + return (double)nOut * (Nt + 2) < (double)(nz + 1); +} + // build_one_condition over column blocks on `threads` threads: each block holds the // value and a separate range of dual lanes, the rows are assembled over all columns. A steady-state // seed is laid out over all columns, so a seeded condition is built unblocked. -double chain_block_bytes(); - -bool build_one_condition_blocked(const CondRaw& cd, +bool build_one_condition_forward(const CondRaw& cd, const std::vector >& leafVal, int nLeaves, int nStates, int nz, int Nt, u64 p, std::vector >& outRows, int threads) { @@ -1705,13 +2272,37 @@ bool build_one_condition_blocked(const CondRaw& cd, return true; } +// The rows of build_one_condition in the mode of kernel_mode(), on `threads` threads. +bool build_one_condition_blocked(const CondRaw& cd, + const std::vector >& leafVal, + int nLeaves, int nStates, int nz, int Nt, u64 p, + std::vector >& outRows, int threads) { + int mode = kernel_mode(); + if (mode == KM_FORWARD || (mode == KM_AUTO && !reverse_pays(cd.gOut.size(), nz, Nt))) + return build_one_condition_forward(cd, leafVal, nLeaves, nStates, nz, Nt, p, outRows, threads); + std::vector > rv; + int st = build_one_condition_reverse(cd, leafVal, nLeaves, nStates, nz, Nt, p, rv, threads); + if (st == REV_FORWARD) + return build_one_condition_forward(cd, leafVal, nLeaves, nStates, nz, Nt, p, outRows, threads); + if (mode == KM_CHECK) { + std::vector > fw; + bool okF = build_one_condition_forward(cd, leafVal, nLeaves, nStates, nz, Nt, p, fw, threads); + if (okF != (st == REV_OK)) + throw std::runtime_error("kernel: the reverse mode fails where the forward mode does not"); + require_same_rows(fw, rv, p, "one condition"); + } + if (st == REV_FAIL) return false; + for (auto& r : rv) outRows.push_back(std::move(r)); + return true; +} + // One chain segment in thread-safe plain C++: the regime-substituted tape, the // reduced constants, and the optional first-segment steady-state seed, IC tape // and state-dose event map. Constants are reduced against the single call prime. struct SegRaw { std::vector op, a, b, stateSlots, fOut, gOut; std::vector cval; - bool hasIcSeed, hasIcTape, hasEv, evStates = false; + bool hasIcSeed, hasIcTape, hasEv, evStates = false, evReadsStates = false; std::vector > icSeed; std::vector icOp, icA, icB, icOut; std::vector icCval; @@ -1722,7 +2313,40 @@ struct SegRaw { std::vector tmCval; }; -SegRaw extract_seg_raw(List seg, int nStates, int w, u64 p) { +// A tape whose slots below `base` are leaves and states, rewritten to read leaf slot[i] from leaf +// src[i], or from the constant cv[i] where src[i] < 0: the constants become instructions ahead of the +// others. `outs` are further slot arrays of the tape, remapped alike. +void rebind_leaves(std::vector& op, std::vector& a, std::vector& b, + std::vector& cval, int base, const std::vector& slot, + const std::vector& src, const std::vector& cv, + std::initializer_list*> outs) { + std::vector to(base, -1); + std::vector consts; + for (size_t i = 0; i < slot.size(); ++i) { + if (slot[i] < 0 || slot[i] >= base) continue; + if (src[i] >= 0) { + to[slot[i]] = src[i]; + } else { + to[slot[i]] = base + (int)consts.size(); + consts.push_back(cv[i]); + } + } + int nC = (int)consts.size(); + auto m = [&](int x) { return x < 0 ? x : x >= base ? x + nC : to[x] >= 0 ? to[x] : x; }; + for (size_t i = 0; i < op.size(); ++i) { + if (op[i] == OP_CONST) continue; + a[i] = m(a[i]); + if (op[i] == OP_ADD || op[i] == OP_MUL || op[i] == OP_SPOW) b[i] = m(b[i]); + } + for (std::vector* v : outs) + for (int& x : *v) x = m(x); + op.insert(op.begin(), nC, OP_CONST); + a.insert(a.begin(), nC, 0); + b.insert(b.begin(), nC, 0); + cval.insert(cval.begin(), consts.begin(), consts.end()); +} + +SegRaw extract_seg_raw(List seg, int nLeaves, int nStates, int w, u64 p) { SegRaw s; s.op = to_ivec(seg["op"]); s.a = to_ivec(seg["a"]); s.b = to_ivec(seg["b"]); s.stateSlots = to_ivec(seg["state_slots"]); @@ -1758,6 +2382,12 @@ SegRaw extract_seg_raw(List seg, int nStates, int w, u64 p) { s.evVarIdx = to_ivec(seg["ev_var_idx"]); s.evMethod = to_ivec(seg["ev_method"]); s.evOp = to_ivec(seg["ev_op"]); s.evA = to_ivec(seg["ev_a"]); s.evB = to_ivec(seg["ev_b"]); s.evOut = to_ivec(seg["ev_out"]); + if (s.evStates) { + std::vector leafOnly; + if (seg.containsElementNamed("ev_leaf_only")) leafOnly = to_ivec(seg["ev_leaf_only"]); + s.evReadsStates = leafOnly.size() != s.evVarIdx.size() || + std::find(leafOnly.begin(), leafOnly.end(), 0) != leafOnly.end(); + } std::vector ecn = to_svec(seg["ev_cnum"]), ecd = to_svec(seg["ev_cden"]); int nEv = (int)s.evOp.size(); s.evCval.assign(nEv, 0); @@ -1776,6 +2406,20 @@ SegRaw extract_seg_raw(List seg, int nStates, int w, u64 p) { if (s.tmOp[i] == OP_CONST) s.tmCval[i] = reduce_rational(tcn[i], tcd[i], p); } + if (seg.containsElementNamed("leaf_slot")) { + // the leaves a condition of a shared tape sets + std::vector slot = to_ivec(seg["leaf_slot"]), src = to_ivec(seg["leaf_src"]); + std::vector num = to_svec(seg["leaf_num"]), den = to_svec(seg["leaf_den"]); + std::vector cv(slot.size(), 0); + for (size_t i = 0; i < slot.size(); ++i) + if (src[i] < 0) cv[i] = reduce_rational(num[i], den[i], p); + rebind_leaves(s.op, s.a, s.b, s.cval, nLeaves + nStates, slot, src, cv, {&s.fOut, &s.gOut}); + if (s.hasIcTape) rebind_leaves(s.icOp, s.icA, s.icB, s.icCval, nLeaves, slot, src, cv, {&s.icOut}); + if (s.hasEv) + rebind_leaves(s.evOp, s.evA, s.evB, s.evCval, nLeaves + (s.evStates ? nStates : 0), slot, src, cv, + {&s.evOut}); + if (s.hasTm) rebind_leaves(s.tmOp, s.tmA, s.tmB, s.tmCval, nLeaves, slot, src, cv, {&s.tmOut}); + } return s; } @@ -1806,6 +2450,17 @@ bool eval_tape_poly(std::vector >& V, const std::vector& o return true; } +// What the reverse mode reads of a value pass of a chain: per segment the Taylor values of every +// slot, the orders run and whether a boundary row follows; per boundary the start of the next +// segment before the events; whether an instruction was taken as a Laurent series. +struct ChainTrace { + std::vector > > val; + std::vector nrun; + std::vector kink; + std::vector > > preEvents; + char deferred = 0; +}; + // Build one condition's chain (all segments) at a single point/prime, propagating // the state across each gap as a formal power series and applying state-dose // events to the propagated state. leafPt holds the leaf residues; the z-leaves seed a dual @@ -1818,7 +2473,7 @@ bool build_one_chain(const std::vector& segs, int nLeaves, int nStates, const std::vector >* ser = nullptr, const std::vector* lane = nullptr, const std::vector* movesIn = nullptr, int Tser = -1, - bool keepZeroSer = false) { + bool keepZeroSer = false, ChainTrace* tr = nullptr) { int instrBase = nLeaves + nStates; int nSeg = (int)segs.size(); int K = nSeg - 1; if (K < 1) K = 1; @@ -1930,15 +2585,17 @@ bool build_one_chain(const std::vector& segs, int nLeaves, int nStates, size_t from = rows.size(); if (!build_obs_rows_poly(val, seg.op, seg.a, seg.b, seg.cval, instrBase, seg.stateSlots, seg.fOut, seg.gOut, pb, Nrun, NtS, p, rows, - moves[sj] ? tau[sj].data() + 1 : nullptr)) + moves[sj] ? tau[sj].data() + 1 : nullptr, nullptr, 0, -1, -1, + tr ? &tr->deferred : nullptr)) return false; bool keepZero = lane != nullptr || keepZeroSer; if (lineMode) rows_to_series_axis(rows, from, pb, nz, Ns, srows, keepZero); else rows_to_line(rows, from, pb, lineC, nz, Mtot + 1, p, srows, keepZero); // where the output is not analytic across a moving boundary, the boundary time is // itself read off the output: the gradient of the boundary time joins the rows + bool kink = false; if (sj > 0 && moves[sj]) { - bool kink = leftJet.size() != seg.gOut.size(); + kink = leftJet.size() != seg.gOut.size(); for (size_t gi = 0; gi < seg.gOut.size() && !kink; ++gi) { const u64* gr = val[seg.gOut[gi]].data(); for (int k = 0; k <= NtS && !kink; ++k) @@ -1955,6 +2612,7 @@ bool build_one_chain(const std::vector& segs, int nLeaves, int nStates, srows.push_back(srow); } } + if (tr) tr->kink.push_back(kink); if (sj < nSeg - 1) { int axis = sj; carry.assign(nStates, std::vector(blk, 0)); @@ -2002,6 +2660,7 @@ bool build_one_chain(const std::vector& segs, int nLeaves, int nStates, leftJet.assign(seg.gOut.size(), std::vector()); for (size_t gi = 0; gi < seg.gOut.size(); ++gi) leftJet[gi] = valL[seg.gOut[gi]]; } + if (tr) tr->preEvents.push_back(carry); const SegRaw& nxt = segs[sj + 1]; if (nxt.hasEv) { // event values over the leaves and the states just before the events @@ -2027,6 +2686,7 @@ bool build_one_chain(const std::vector& segs, int nLeaves, int nStates, } } } + if (tr) { tr->nrun.push_back(Nrun); tr->val.push_back(std::move(val)); } } return true; } @@ -2055,28 +2715,511 @@ bool chain_moves(const std::vector& segs, int nLeaves, int w, return true; } -// Columns per block so that one block's Taylor values stay within `budget` bytes. -int chain_block_size(const std::vector& segs, int nLeaves, int nStates, int nz, - int Nt, int Mtot, bool hasSer, double budget, int Tser = -1) { - size_t Sn = 0; - for (const SegRaw& sg : segs) Sn = std::max(Sn, (size_t)(nLeaves + nStates) + sg.op.size()); - bool line = hasSer && Tser >= 0; - int K = std::max(1, (int)segs.size() - 1) + (hasSer && !line ? 1 : 0); - double nMono = 1; // binomial(K + Mtot, Mtot) - for (int i = 1; i <= Mtot; ++i) nMono = nMono * (K + i) / i; - if (line) nMono *= Tser + 1; - double perLane = (double)Sn * (std::max(Nt, Mtot) + 2) * nMono * 8.0; - int B = (int)(budget / perLane) - 1; - return std::max(2, std::min(nz, B)); -} +// ---- Reverse mode of build_one_chain ---- +// One value pass, then adjoint sweeps from the last segment to the first through the events and +// the gap shifts. Rows run by descending segment, then order, so that each sweep covers a prefix. +int build_one_chain_reverse(const std::vector& segs, int nLeaves, int nStates, + int nz, const std::vector& dualCol, + const std::vector& leafPt, int Nt, int Mtot, u64 p, + std::vector >& rows, + std::vector >& srows, + const std::vector >* ser, int threads, int Tser, + bool keepZeroSer) { + int w = nz + 1, nSeg = (int)segs.size(), instrBase = nLeaves + nStates; + // the sweep takes an event value as a function of the leaves alone + for (const SegRaw& sg : segs) { + if (sg.evReadsStates) return REV_FORWARD; + for (int o : sg.op) + if (o != OP_CONST && o != OP_ADD && o != OP_MUL && o != OP_INV) return REV_FORWARD; + } + std::vector moves; + if (!chain_moves(segs, nLeaves, w, dualCol, leafPt, p, moves)) return REV_FORWARD; + ChainTrace tr; + { + std::vector none(nLeaves, -1); + std::vector > r1, s1; + if (!build_one_chain(segs, nLeaves, nStates, 0, 1, none, leafPt, Nt, Mtot, p, r1, s1, ser, + nullptr, &moves, Tser, false, &tr) || tr.deferred) + return REV_FORWARD; + } + int K = nSeg - 1; if (K < 1) K = 1; + int serAxis = -1; + if (ser) { serAxis = K; K += 1; } + bool lineMode = ser && Tser >= 0; + PolyBasis pb(K, Mtot, 1, lineMode ? serAxis : -1, Tser); + int nM = pb.nMono, blkW = nM * w; + int Ns = lineMode ? Tser + 1 : Mtot + 1; -// the default of chain_block_bytes(), set by symSetBlockBytes -std::atomic g_block_bytes(256LL * 1048576LL); + // the sources of duals, in forward mode over all columns: the leaves, the boundary times, the + // start of the first segment and the event values + std::vector > leafW(nLeaves, std::vector(blkW, 0)); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)leafPt[L] % (long long)p; if (pv < 0) pv += p; + leafW[L][0] = (u64)pv; + if (dualCol[L] >= 0) leafW[L][1 + dualCol[L]] = 1; + } + if (ser) { + std::vector mu(K, 0); + for (int L = 0; L < nLeaves; ++L) + for (int j = 1; j <= (int)(*ser)[L].size() && j <= (lineMode ? Tser : Mtot); ++j) { + mu[serAxis] = j; + leafW[L][(size_t)pb.slotOf.at(mu) * w] = (*ser)[L][j - 1] % p; + } + } + std::unique_ptr pbW; + if (ser) pbW.reset(new PolyBasis(K, Mtot, w, lineMode ? serAxis : -1, Tser)); + // a side tape on the leaves: polyseries with a series, else order 0 at monomial 0; the slots + // from nLeaves to `base` are states the values do not read + auto side = [&](const std::vector& op, const std::vector& a, const std::vector& b, + const std::vector& cval, std::vector >& V, int base) { + if (ser) { + V.assign(base + op.size(), std::vector(blkW, 0)); + for (int L = 0; L < nLeaves; ++L) V[L] = leafW[L]; + return eval_tape_poly(V, op, a, b, cval, base, *pbW, p); + } + std::vector > S(base + op.size(), std::vector(w, 0)); + for (int L = 0; L < nLeaves; ++L) std::copy(leafW[L].begin(), leafW[L].begin() + w, S[L].begin()); + if (!eval_ic_order0(S, op, a, b, cval, base, w, p)) return false; + V.assign(S.size(), std::vector(blkW, 0)); + for (size_t i = 0; i < S.size(); ++i) std::copy(S[i].begin(), S[i].end(), V[i].begin()); + for (int L = 0; L < nLeaves; ++L) V[L] = leafW[L]; + return true; + }; + std::vector > tau(nSeg, std::vector(w, 0)); + for (int sj = 0; sj < nSeg; ++sj) { + const SegRaw& sg = segs[sj]; + if (!sg.hasTm) continue; + std::vector > tmVal(nLeaves + sg.tmOp.size(), std::vector(w, 0)); + for (int L = 0; L < nLeaves; ++L) std::copy(leafW[L].begin(), leafW[L].begin() + w, tmVal[L].begin()); + if (!eval_ic_order0(tmVal, sg.tmOp, sg.tmA, sg.tmB, sg.tmCval, nLeaves, w, p)) return REV_FORWARD; + tau[sj] = tmVal[sg.tmOut[0]]; + } + std::vector lineC(K, 1); + for (int i = 0; i + 1 < nSeg; ++i) + if (segs[i].hasTm && segs[i + 1].hasTm) lineC[i] = submod(tau[i + 1][0], tau[i][0], p); + std::vector > start(nStates, std::vector(blkW, 0)); + const SegRaw& s0 = segs[0]; + if (s0.hasIcSeed) { + for (int i = 0; i < nStates; ++i) + for (int c = 0; c < w; ++c) start[i][c] = s0.icSeed[i][c]; + } else if (s0.hasIcTape) { + std::vector > icV; + if (!side(s0.icOp, s0.icA, s0.icB, s0.icCval, icV, nLeaves)) return REV_FORWARD; + for (int i = 0; i < nStates; ++i) start[i] = icV[s0.icOut[i]]; + } + std::vector > > evv(std::max(0, nSeg - 1)); + for (int b = 0; b + 1 < nSeg; ++b) { + const SegRaw& nx = segs[b + 1]; + if (!nx.hasEv) continue; + std::vector > eV; + if (!side(nx.evOp, nx.evA, nx.evB, nx.evCval, eV, nLeaves + (nx.evStates ? nStates : 0))) + return REV_FORWARD; + for (size_t e = 0; e < nx.evVarIdx.size(); ++e) { + std::vector vv = eV[nx.evOut[e]]; + for (u64& x : vv) x %= p; + evv[b].push_back(vv); + } + } -// Taylor values per column block, bytes; SYMIDENT_BLOCKMB overrides (MB) -double chain_block_bytes() { - const char* e = std::getenv("SYMIDENT_BLOCKMB"); - return (e && *e) ? std::atof(e) * 1048576.0 : (double)g_block_bytes.load(); + // per segment: -(o*o) of each reciprocal, the values constant in time and the (slot, order) + // cells an adjoint reaches + struct RevSeg { + std::vector > nsq; + std::vector tconst; + std::vector mark; + int nMarked; + }; + std::vector rsg(nSeg); + size_t maxMarked = 1; + for (int sj = 0; sj < nSeg; ++sj) { + const SegRaw& sg = segs[sj]; + const std::vector >& V = tr.val[sj]; + int N1 = tr.nrun[sj] + 1, nInstr = (int)sg.op.size(), S = (int)V.size(); + RevSeg& rs = rsg[sj]; + std::vector isState(S, 0); + for (int s : sg.stateSlots) isState[s] = 1; + rs.tconst.assign(S, 0); + for (int v = 0; v < instrBase; ++v) rs.tconst[v] = !isState[v]; + for (int i = 0; i < nInstr; ++i) { + int o = sg.op[i]; + rs.tconst[instrBase + i] = o == OP_CONST || + ((o == OP_ADD || o == OP_MUL) && rs.tconst[sg.a[i]] && rs.tconst[sg.b[i]]) || + (o == OP_INV && rs.tconst[sg.a[i]]); + } + rs.nsq.assign(nInstr, {}); + for (int i = 0; i < nInstr; ++i) { + if (sg.op[i] != OP_INV) continue; + const std::vector& o = V[instrBase + i]; + std::vector& q = rs.nsq[i]; + q.assign((size_t)N1 * nM, 0); + for (int k = 0; k < N1; ++k) + for (int ii = 0; ii <= k; ++ii) + for (int am = 0; am < nM; ++am) { + u64 x = o[(size_t)ii * nM + am]; + if (!x) continue; + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl < 0) continue; + u64& t = q[(size_t)k * nM + sl]; + t = addmod(t, mulmod(x, o[(size_t)(k - ii) * nM + bm], p), p); + } + } + for (u64& t : q) t = submod(0, t, p); + } + auto nzv = [&](const std::vector& v, int k) { + for (int m = 0; m < nM; ++m) if (v[(size_t)k * nM + m]) return true; + return false; + }; + auto live = [&](int s, int k) { + if (s < instrBase && !isState[s]) return k == 0 && s < nLeaves && dualCol[s] >= 0; + if (s < instrBase) return true; + if (sg.op[s - instrBase] == OP_CONST) return false; + return k == 0 || !rs.tconst[s]; + }; + rs.mark.assign((size_t)S * N1, -1); + rs.nMarked = 0; + auto mark = [&](int s, int k) { + int& m = rs.mark[(size_t)s * N1 + k]; + if (m < 0 && live(s, k)) m = rs.nMarked++; + }; + for (int g : sg.gOut) + for (int k = 0; k <= Nt && k < N1; ++k) mark(g, k); + if (sj + 1 < nSeg) + for (int s : sg.stateSlots) + for (int k = 0; k <= Mtot && k < N1; ++k) mark(s, k); + for (int s : sg.stateSlots) mark(s, 0); + for (int k = N1 - 1; k >= 0; --k) { + if (k + 1 < N1) + for (int i = 0; i < (int)sg.stateSlots.size(); ++i) + if (rs.mark[(size_t)sg.stateSlots[i] * N1 + k + 1] >= 0) mark(sg.fOut[i], k); + for (int i = nInstr - 1; i >= 0; --i) { + if (rs.mark[(size_t)(instrBase + i) * N1 + k] < 0) continue; + int a = sg.a[i], b = sg.b[i]; + switch (sg.op[i]) { + case OP_ADD: mark(a, k); mark(b, k); break; + case OP_MUL: { + int j0, j1; + conv_range(rs.tconst[a], rs.tconst[b], k, j0, j1); + for (int ii = j0; ii <= j1; ++ii) { + if (nzv(V[b], k - ii)) mark(a, ii); + if (nzv(V[a], ii)) mark(b, k - ii); + } + break; + } + case OP_INV: + for (int ii = 0; ii <= (rs.tconst[a] ? 0 : k); ++ii) { + bool any = false; + for (int m = 0; m < nM && !any; ++m) any = rs.nsq[i][(size_t)(k - ii) * nM + m] != 0; + if (any) mark(a, ii); + } + break; + } + } + } + maxMarked = std::max(maxMarked, (size_t)rs.nMarked); + } + // shift of time order k at monomial a into the gap axis of boundary b + std::vector > > shiftTab(std::max(0, nSeg - 1), + std::vector >(Mtot + 1, std::vector(nM, -1))); + for (int b = 0; b + 1 < nSeg; ++b) + for (int k = 0; k <= Mtot; ++k) + for (int am = 0; am < nM; ++am) shiftTab[b][k][am] = pb.shiftSlot(am, b, k); + + std::vector nOut(nSeg), offset(nSeg + 1, 0); + for (int sj = nSeg - 1; sj >= 0; --sj) { + nOut[sj] = (int)segs[sj].gOut.size(); + offset[sj] = offset[sj + 1] + nOut[sj] * (Nt + 1) * nM; + } + // the rows of segment sj start after those of the later segments + std::vector first(nSeg); + for (int sj = 0; sj < nSeg; ++sj) first[sj] = offset[sj + 1]; + int Rtot = offset[0]; + + auto sweep = [&](int r0, int r1, std::vector >& out) { + int B = r1 - r0; + size_t cell = (size_t)nM * B; + const Barrett br(p); + out.assign(B, std::vector(nz, 0)); + std::vector coef(B); + // out += coef * the duals of `dual` (w residues: value, then duals) + auto addDual = [&](const u64* cf, const u64* dual) { + for (int c = 1; c < w; ++c) { + u64 d = dual[c] % p; + if (!d) continue; + for (int rr = 0; rr < B; ++rr) + if (cf[rr]) out[rr][c - 1] = br.red(out[rr][c - 1] + cf[rr] * d); + } + }; + std::vector > adjC; + for (int sj = nSeg - 1; sj >= 0; --sj) { + const SegRaw& sg = segs[sj]; + const RevSeg& rs = rsg[sj]; + const std::vector >& V = tr.val[sj]; + int Nrun = tr.nrun[sj], N1 = Nrun + 1, nO = nOut[sj], nInstr = (int)sg.op.size(); + std::vector pool((size_t)rs.nMarked * cell, 0); + auto at = [&](int s, int k) -> u64* { + int m = rs.mark[(size_t)s * N1 + k]; + return m < 0 ? nullptr : pool.data() + (size_t)m * cell; + }; + if (sj + 1 < nSeg) { + bool mv = moves[sj] || moves[sj + 1]; + std::vector dd(w, 0); + if (mv) for (int c = 1; c < w; ++c) dd[c] = submod(tau[sj + 1][c], tau[sj][c], p); + std::fill(coef.begin(), coef.end(), (u64)0); + for (int i = 0; i < nStates; ++i) { + int s = sg.stateSlots[i]; + const std::vector& xv = V[s]; + for (int k = 0; k <= Mtot; ++k) { + u64* d = at(s, k); + for (int am = 0; am < nM; ++am) { + int dst = shiftTab[sj][k][am]; + if (dst < 0) continue; + const u64* a = adjC[i].data() + (size_t)dst * B; + if (d) axpy_mod(d + (size_t)am * B, a, 1, B, br); + if (!mv) continue; + u64 fk = mulmod((u64)(k + 1) % p, xv[(size_t)(k + 1) * nM + am], p); + if (fk) for (int rr = 0; rr < B; ++rr) coef[rr] = br.red(coef[rr] + a[rr] * fk); + } + } + } + if (mv) addDual(coef.data(), dd.data()); + } + for (int k = Nrun; k >= 0; --k) { + int act = std::min(B, first[sj] + std::max(0, Nt - k + 1) * nO * nM - r0); + if (act <= 0) continue; + if (k <= Nt) + for (int gi = 0; gi < nO; ++gi) + for (int mo = 0; mo < nM; ++mo) { + int r = first[sj] + ((Nt - k) * nO + gi) * nM + mo; + if (r < r0 || r >= r1) continue; + if (u64* g = at(sg.gOut[gi], k)) { + u64& e = g[(size_t)mo * B + (r - r0)]; + e = addmod(e, 1, p); + } + } + if (k < Nrun) { + u64 ik = invmod((u64)(k + 1), p); + for (int i = 0; i < (int)sg.stateSlots.size(); ++i) { + const u64* src = at(sg.stateSlots[i], k + 1); + u64* dst = at(sg.fOut[i], k); + if (src && dst) + for (int m = 0; m < nM; ++m) + axpy_mod(dst + (size_t)m * B, src + (size_t)m * B, ik, act, br); + } + } + for (int i = nInstr - 1; i >= 0; --i) { + const u64* o = at(instrBase + i, k); + if (!o) continue; + int a = sg.a[i], b = sg.b[i]; + switch (sg.op[i]) { + case OP_ADD: + for (int x : {a, b}) + if (u64* d = at(x, k)) + for (int m = 0; m < nM; ++m) + axpy_mod(d + (size_t)m * B, o + (size_t)m * B, 1, act, br); + break; + case OP_MUL: { + int j0, j1; + conv_range(rs.tconst[a], rs.tconst[b], k, j0, j1); + for (int ii = j0; ii <= j1; ++ii) { + const u64* A = V[a].data() + (size_t)ii * nM; + const u64* Bv = V[b].data() + (size_t)(k - ii) * nM; + u64* da = at(a, ii); + u64* db = at(b, k - ii); + if (!da && !db) continue; + for (int am = 0; am < nM; ++am) + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl < 0) continue; + const u64* os = o + (size_t)sl * B; + if (da && Bv[bm]) axpy_mod(da + (size_t)am * B, os, Bv[bm], act, br); + if (db && A[am]) axpy_mod(db + (size_t)bm * B, os, A[am], act, br); + } + } + break; + } + case OP_INV: + for (int ii = 0; ii <= (rs.tconst[a] ? 0 : k); ++ii) { + u64* da = at(a, ii); + if (!da) continue; + const u64* ns = rs.nsq[i].data() + (size_t)(k - ii) * nM; + for (int am = 0; am < nM; ++am) + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl < 0 || !ns[bm]) continue; + axpy_mod(da + (size_t)am * B, o + (size_t)sl * B, ns[bm], act, br); + } + } + break; + } + } + } + for (int L = 0; L < nLeaves; ++L) { + if (dualCol[L] < 0) continue; + const u64* d = at(L, 0); + if (!d) continue; + for (int rr = 0; rr < B; ++rr) + if (d[rr]) out[rr][dualCol[L]] = addmod(out[rr][dualCol[L]], d[rr], p); + } + std::vector > adjS(nStates, std::vector(cell, 0)); + for (int i = 0; i < nStates; ++i) + if (const u64* d = at(sg.stateSlots[i], 0)) std::copy(d, d + cell, adjS[i].begin()); + if (sj == 0) { + for (int i = 0; i < nStates; ++i) + for (int m = 0; m < nM; ++m) + addDual(adjS[i].data() + (size_t)m * B, start[i].data() + (size_t)m * w); + break; + } + // the events into this segment, reversed; a scaling reads the start before it + int bnd = sj - 1; + if (sg.hasEv) { + int E = (int)sg.evVarIdx.size(); + std::vector > cur = tr.preEvents[bnd]; + std::vector > pre(E); + for (int e = 0; e < E; ++e) { + int s = sg.evVarIdx[e], meth = sg.evMethod[e]; + const std::vector& vv = evv[bnd][e]; + if (meth == 0) { + for (int m = 0; m < nM; ++m) cur[s][m] = vv[(size_t)m * w]; + } else if (meth == 1) { + for (int m = 0; m < nM; ++m) cur[s][m] = addmod(cur[s][m], vv[(size_t)m * w], p); + } else { + pre[e] = cur[s]; + std::vector sc(nM, 0); + for (int am = 0; am < nM; ++am) + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl >= 0) sc[sl] = addmod(sc[sl], mulmod(pre[e][am], vv[(size_t)bm * w], p), p); + } + cur[s] = sc; + } + } + for (int e = E - 1; e >= 0; --e) { + int s = sg.evVarIdx[e], meth = sg.evMethod[e]; + const std::vector& vv = evv[bnd][e]; + std::vector& aS = adjS[s]; + if (meth != 2) { + for (int m = 0; m < nM; ++m) addDual(aS.data() + (size_t)m * B, vv.data() + (size_t)m * w); + if (meth == 0) std::fill(aS.begin(), aS.end(), (u64)0); + continue; + } + std::vector nA(cell, 0); + for (int am = 0; am < nM; ++am) + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl < 0) continue; + const u64* as = aS.data() + (size_t)sl * B; + u64 vb = vv[(size_t)bm * w]; + if (vb) axpy_mod(nA.data() + (size_t)am * B, as, vb, B, br); + u64 pa = pre[e][am]; + if (!pa) continue; + for (int rr = 0; rr < B; ++rr) coef[rr] = mulmod(as[rr], pa, p); + addDual(coef.data(), vv.data() + (size_t)bm * w); + } + aS.swap(nA); + } + } + adjC.swap(adjS); + } + }; + + if (Rtot == 0) return REV_OK; + // rows per block: split over the threads, and bounded so that one block's adjoints stay within + // the budget of chain_block_bytes() + double perRow = std::max(1.0, (double)maxMarked * nM * 8.0); + int Bmem = std::max(1, (int)(chain_block_bytes() / perRow)); + int Bt = threads > 1 ? (Rtot + threads - 1) / threads : Rtot; + int B = std::max(1, std::min(Bt, Bmem)); + int nb = (Rtot + B - 1) / B; + std::vector > > rB(nb); + int nThr = std::max(1, std::min(threads, nb)); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1) + for (int b = 0; b < nb; ++b) { + try { + sweep(b * B, std::min(Rtot, (b + 1) * B), rB[b]); + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + + // the rows in the order of the forward mode, with the shift of a moving segment start + std::vector > > segRows(nSeg); + for (int sj = 0; sj < nSeg; ++sj) segRows[sj].resize((size_t)nOut[sj] * (Nt + 1) * nM); + for (int b = 0; b < nb; ++b) + for (size_t i = 0; i < rB[b].size(); ++i) { + int r = b * B + (int)i, sj = 0; + while (r < first[sj]) ++sj; + int loc = r - first[sj], nO = nOut[sj]; + int k = Nt - loc / (nO * nM), gi = (loc % (nO * nM)) / nM, mo = loc % nM; + segRows[sj][((size_t)gi * (Nt + 1) + k) * nM + mo] = std::move(rB[b][i]); + } + for (int sj = 0; sj < nSeg; ++sj) { + const SegRaw& sg = segs[sj]; + if (moves[sj]) + for (int gi = 0; gi < nOut[sj]; ++gi) { + const std::vector& g = tr.val[sj][sg.gOut[gi]]; + for (int k = 0; k <= Nt; ++k) + for (int mo = 0; mo < nM; ++mo) { + u64 fk = mulmod((u64)(k + 1) % p, g[(size_t)(k + 1) * nM + mo], p); + if (!fk) continue; + std::vector& row = segRows[sj][((size_t)gi * (Nt + 1) + k) * nM + mo]; + for (int c = 0; c < nz; ++c) + row[c] = submod(row[c], mulmod(fk, tau[sj][1 + c], p), p); + } + } + size_t from = rows.size(); + for (std::vector& r : segRows[sj]) rows.push_back(std::move(r)); + if (lineMode) rows_to_series_axis(rows, from, pb, nz, Ns, srows, keepZeroSer); + else rows_to_line(rows, from, pb, lineC, nz, Mtot + 1, p, srows, keepZeroSer); + if (tr.kink[sj]) { + std::vector row(tau[sj].begin() + 1, tau[sj].end()); + std::vector srow((size_t)nz * Ns, 0); + for (int c = 0; c < nz; ++c) srow[(size_t)c * Ns] = row[c]; + rows.push_back(row); + srows.push_back(srow); + } + } + return REV_OK; +} + +// Reverse mode where the rows of a chain sweep fewer residues than the columns hold, as in +// reverse_pays +bool reverse_pays_chain(const std::vector& segs, int nz, int Nt, int Mtot, bool hasSer, + int Tser) { + bool line = hasSer && Tser >= 0; + int K = std::max(1, (int)segs.size() - 1) + (hasSer && !line ? 1 : 0); + double nMono = 1; + for (int i = 1; i <= Mtot; ++i) nMono = nMono * (K + i) / i; + if (line) nMono *= Tser + 1; + double rowsTot = 0; + for (const SegRaw& sg : segs) rowsTot += (double)sg.gOut.size() * (Nt + 2) * nMono; + return rowsTot < (double)(nz + 1); +} + +// Columns per block so that one block's Taylor values stay within `budget` bytes. +int chain_block_size(const std::vector& segs, int nLeaves, int nStates, int nz, + int Nt, int Mtot, bool hasSer, double budget, int Tser = -1) { + size_t Sn = 0; + for (const SegRaw& sg : segs) Sn = std::max(Sn, (size_t)(nLeaves + nStates) + sg.op.size()); + bool line = hasSer && Tser >= 0; + int K = std::max(1, (int)segs.size() - 1) + (hasSer && !line ? 1 : 0); + double nMono = 1; // binomial(K + Mtot, Mtot) + for (int i = 1; i <= Mtot; ++i) nMono = nMono * (K + i) / i; + if (line) nMono *= Tser + 1; + double perLane = (double)Sn * (std::max(Nt, Mtot) + 2) * nMono * 8.0; + int B = (int)(budget / perLane) - 1; + return std::max(2, std::min(nz, B)); +} + +// the default of chain_block_bytes(), set by symSetBlockBytes +std::atomic g_block_bytes(256LL * 1048576LL); + +// Taylor values per column block, bytes; SYMIDENT_BLOCKMB overrides (MB) +double chain_block_bytes() { + const char* e = std::getenv("SYMIDENT_BLOCKMB"); + return (e && *e) ? std::atof(e) * 1048576.0 : (double)g_block_bytes.load(); } // Threads inside one chain when `outer` chains share `cores`; nesting is enabled for it. @@ -2092,13 +3235,23 @@ int chain_inner_threads(int cores, int outer) { // build_one_chain over column blocks: each block holds the value and a separate range of dual // lanes, the rows are assembled over all columns. Rows and series rows keep the order // of the unblocked call, zero series rows dropped. -bool build_chain_blocked(const std::vector& segs, int nLeaves, int nStates, +int lean_chain(const std::vector& segs, int nLeaves, int nStates, int nz, + const std::vector& dualCol, const std::vector& leafPt, int Nt, int Mtot, u64 p, + std::vector >& rows, std::vector >& srows, + int threads, bool keepZeroSer, const std::string& key); + +bool build_chain_forward(const std::vector& segs, int nLeaves, int nStates, int nz, const std::vector& dualCol, const std::vector& leafPt, int Nt, int Mtot, u64 p, std::vector >& rows, std::vector >& srows, const std::vector >* ser, int B, int threads, - int Tser = -1, bool keepZeroSer = false) { + int Tser, bool keepZeroSer, const std::string& key = std::string()) { + if (ser == nullptr) { + int st = lean_chain(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, rows, srows, threads, + keepZeroSer, key); + if (st != REV_FORWARD) return st == REV_OK; + } if (B >= nz) return build_one_chain(segs, nLeaves, nStates, nz, nz + 1, dualCol, leafPt, Nt, Mtot, p, rows, srows, ser, nullptr, nullptr, Tser, keepZeroSer); @@ -2149,6 +3302,654 @@ bool build_chain_blocked(const std::vector& segs, int nLeaves, int nStat return true; } +// The rows of build_one_chain in the mode of kernel_mode(); B columns per block of the forward mode. +bool build_chain_blocked(const std::vector& segs, int nLeaves, int nStates, + int nz, const std::vector& dualCol, + const std::vector& leafPt, int Nt, int Mtot, u64 p, + std::vector >& rows, + std::vector >& srows, + const std::vector >* ser, int B, int threads, + int Tser = -1, bool keepZeroSer = false, + const std::string& key = std::string()) { + int mode = kernel_mode(); + if (mode == KM_FORWARD || + (mode == KM_AUTO && !reverse_pays_chain(segs, nz, Nt, Mtot, ser != nullptr, Tser))) + return build_chain_forward(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, rows, + srows, ser, B, threads, Tser, keepZeroSer, key); + std::vector > rv, sv; + int st = build_one_chain_reverse(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, rv, + sv, ser, threads, Tser, keepZeroSer); + if (st == REV_FORWARD) + return build_chain_forward(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, rows, + srows, ser, B, threads, Tser, keepZeroSer, key); + if (mode == KM_CHECK) { + std::vector > fr, fs; + bool okF = build_chain_forward(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, fr, + fs, ser, B, threads, Tser, keepZeroSer); + if (okF != (st == REV_OK)) + throw std::runtime_error("kernel: the reverse mode fails where the forward mode does not (chain)"); + require_same_rows(fr, rv, p, "chain rows"); + require_same_rows(fs, sv, p, "chain series rows"); + } + if (st == REV_FAIL) return false; + for (auto& r : rv) rows.push_back(std::move(r)); + for (auto& r : sv) srows.push_back(std::move(r)); + return true; +} + +// ---- Jets of one segment continued to higher orders ---- +// Taylor coefficients of a segment over a block of dual lanes, kept between calls so that a higher order +// continues from the last one. Values a convolution reads keep every order, the others the current order only. +struct LeanJets { + int s0 = 0, wb = 1, K = -1; // lanes [s0, s0 + wb - 1), last order formed + int nM = 1; // monomials in the gap lengths per value + std::shared_ptr pb; // the monomials, with wb lanes + std::vector > H; // per slot: the current order, or order 0 + std::vector > > C; // per slot that keeps every order: chunks of orders + std::vector > invA0; // per reciprocal: 1/a at order 0 + std::vector > rlo, rhi; // per kept slot, order and monomial: the nonzero lanes + std::vector > rows; // per order, output and monomial: the lanes + std::vector gVal; // per order, output and monomial: the value + std::vector fVal; // the field at order 0, monomial 0 + int keepEarly = -1; // the state orders kept for the next segment + std::vector > > early; // per state and order up to keepEarly + size_t bytes() const { + size_t b = 0; + for (const auto& h : H) b += h.capacity() * 8; + for (const auto& c : C) + for (const auto& x : c) b += x.capacity() * 8; + for (const auto& r : rows) b += r.capacity() * 8; + return b; + } +}; + +struct LeanTape { + std::vector hist, tconst; + int instrBase = 0; + bool ok = true; +}; + +// The kept orders of a segment tape; ok = false for an operation other than CONST/ADD/MUL/INV. +LeanTape lean_tape(const SegRaw& seg, int nLeaves, int nStates) { + LeanTape lt; + int ib = nLeaves + nStates, nI = (int)seg.op.size(), S = ib + nI; + lt.instrBase = ib; + lt.hist.assign(S, 0); + lt.tconst.assign(S, 0); + std::vector isState(S, 0); + for (int s : seg.stateSlots) isState[s] = 1; + for (int v = 0; v < ib; ++v) lt.tconst[v] = !isState[v]; + for (int i = 0; i < nI; ++i) { + int o = seg.op[i], a = seg.a[i], b = seg.b[i]; + if (o != OP_CONST && o != OP_ADD && o != OP_MUL && o != OP_INV) { lt.ok = false; return lt; } + lt.tconst[ib + i] = o == OP_CONST || ((o == OP_ADD || o == OP_MUL) && lt.tconst[a] && lt.tconst[b]) || + (o == OP_INV && lt.tconst[a]); + if (o == OP_MUL && !lt.tconst[a] && !lt.tconst[b]) lt.hist[a] = lt.hist[b] = 1; + if (o == OP_INV && !lt.tconst[a]) lt.hist[a] = lt.hist[ib + i] = 1; + } + return lt; +} + +// A block of lanes [s0, s1) at order 0: the leaves at their values with a unit lane per coordinate in +// the block, state i at st[i] (per monomial the value, then the lanes over all nLane columns). +LeanJets lean_block(const LeanTape& lt, const SegRaw& seg, int nLeaves, const std::vector& leaf, + const std::vector& dualCol, const std::vector >& st, int s0, int s1, + int nLane, int K = 1, int Mtot = 0) { + LeanJets J; + int S = (int)lt.hist.size(); + J.s0 = s0; J.wb = s1 - s0 + 1; + J.pb = std::make_shared(K, Mtot, J.wb); + J.nM = J.pb->nMono; + size_t blk = (size_t)J.nM * J.wb; + J.H.assign(S, std::vector()); + J.rlo.assign(S, std::vector()); + J.rhi.assign(S, std::vector()); + J.invA0.assign(seg.op.size(), std::vector()); + for (int v = 0; v < S; ++v) J.H[v].assign(blk, 0); + for (int L = 0; L < nLeaves; ++L) { + J.H[L][0] = leaf[L]; + if (dualCol[L] >= s0 && dualCol[L] < s1) J.H[L][1 + dualCol[L] - s0] = 1; + } + for (size_t i = 0; i < seg.stateSlots.size(); ++i) { + std::vector& h = J.H[seg.stateSlots[i]]; + for (int mo = 0; mo < J.nM; ++mo) { + const u64* src = st[i].data() + (size_t)mo * (1 + nLane); + u64* d = h.data() + (size_t)mo * J.wb; + d[0] = src[0]; + for (int c = s0; c < s1; ++c) d[1 + c - s0] = src[1 + c]; + } + } + return J; +} + +// The orders K + 1 .. Nrun of the jets `J`; false where a reciprocal has no unit value at order 0. +bool lean_extend(LeanJets& J, const LeanTape& lt, const SegRaw& seg, int Nrun, u64 p) { + int ib = lt.instrBase, nI = (int)seg.op.size(), wb = J.wb, m = (int)seg.stateSlots.size(); + int nOut = (int)seg.gOut.size(), nM = J.nM; + size_t blk = (size_t)nM * wb; + const PolyBasis& pb = *J.pb; + const Barrett br(p); + const u64 LIM = (((u64)1 << 63) / p) * p; + std::vector zero(blk, 0), acc(blk), tmp(blk); + // orders in chunks, so that a higher order adds chunks and copies none + const int CH = 32; + if (J.C.empty()) J.C.resize(J.H.size()); + for (size_t s = 0; s < J.H.size(); ++s) + if (lt.hist[s]) { + if (J.C[s].empty()) J.C[s].push_back(J.H[s]); + while ((int)J.C[s].size() * CH < Nrun + 2) J.C[s].push_back(std::vector()); + for (auto& c : J.C[s]) + if (c.size() != (size_t)CH * blk) c.resize((size_t)CH * blk, 0); + J.rlo[s].resize((size_t)(Nrun + 2) * nM, -1); + J.rhi[s].resize((size_t)(Nrun + 2) * nM, 0); + } + if (J.keepEarly >= 0 && J.early.empty()) { + J.early.assign(m, std::vector >()); + for (int i = 0; i < m; ++i) J.early[i].push_back(J.H[seg.stateSlots[i]]); + } + auto hp = [&](int s, int k) -> u64* { return J.C[s][k / CH].data() + (size_t)(k % CH) * blk; }; + auto rd = [&](int s, int k) -> const u64* { + if (lt.tconst[s]) return k == 0 ? J.H[s].data() : zero.data(); + return lt.hist[s] ? hp(s, k) : J.H[s].data(); + }; + auto wr = [&](int s, int k) -> u64* { + return lt.hist[s] ? hp(s, k) : J.H[s].data(); + }; + auto dense = [&](const u64* x, int& lo, int& hi) { + lo = 1; while (lo < wb && x[lo] == 0) ++lo; + hi = wb; while (hi > lo && x[hi - 1] == 0) --hi; + }; + auto range = [&](int s, int k, int mo, int& lo, int& hi) { + size_t key = (size_t)k * nM + mo; + if (J.rlo[s][key] < 0) { + int l, h; + dense(hp(s, k) + (size_t)mo * wb, l, h); + J.rlo[s][key] = l; J.rhi[s][key] = h; + } + lo = J.rlo[s][key]; hi = J.rhi[s][key]; + }; + // acc[sl] += x * y over the duals, unreduced below LIM + auto dmul1 = [&](u64* ac, const u64* x, const u64* y, int lx, int hx, int ly, int hy) { + u64 x0 = x[0], y0 = y[0]; + if (x0 && y0) { u64 t = ac[0] + x0 * y0; ac[0] = t >= LIM ? t - LIM : t; } + if (x0) for (int c = ly; c < hy; ++c) { u64 t = ac[c] + x0 * y[c]; ac[c] = t >= LIM ? t - LIM : t; } + if (y0) for (int c = lx; c < hx; ++c) { u64 t = ac[c] + y0 * x[c]; ac[c] = t >= LIM ? t - LIM : t; } + }; + // acc += X * Y over the monomials; `xr`, `yr` give the lanes of a monomial + auto pmul = [&](const u64* X, const u64* Y, auto xr, auto yr) { + for (int am = 0; am < nM; ++am) { + const u64* x = X + (size_t)am * wb; + int lx, hx; + xr(am, lx, hx); + if (x[0] == 0 && lx == hx) continue; + for (int bm = 0; bm < nM; ++bm) { + int sl = pb.sumSlot[am][bm]; + if (sl < 0) continue; + const u64* y = Y + (size_t)bm * wb; + int ly, hy; + yr(bm, ly, hy); + if (y[0] == 0 && ly == hy) continue; + dmul1(acc.data() + (size_t)sl * wb, x, y, lx, hx, ly, hy); + } + } + }; + auto dr = [&](const u64* X) { return [X, &dense, wb](int mo, int& lo, int& hi) { dense(X + (size_t)mo * wb, lo, hi); }; }; + for (int k = J.K + 1; k <= Nrun; ++k) { + if (k > 0) { + // the states at order k, from the field at order k - 1 + u64 ik = invmod((u64)k, p); + std::vector > nx(m, std::vector(blk)); + for (int i = 0; i < m; ++i) { + const u64* f = rd(seg.fOut[i], k - 1); + for (size_t c = 0; c < blk; ++c) nx[i][c] = mulmod(f[c], ik, p); + } + for (int i = 0; i < m; ++i) { + std::copy(nx[i].begin(), nx[i].end(), wr(seg.stateSlots[i], k)); + if (k <= J.keepEarly) J.early[i].push_back(nx[i]); + } + } + for (int i = 0; i < nI; ++i) { + int s = ib + i, a = seg.a[i], b = seg.b[i]; + if (k > 0 && lt.tconst[s]) continue; + u64* o = wr(s, k); + std::fill(acc.begin(), acc.end(), (u64)0); + switch (seg.op[i]) { + case OP_CONST: + std::fill(o, o + blk, (u64)0); + o[0] = seg.cval[i]; + continue; + case OP_ADD: { + const u64* x = rd(a, k); const u64* y = rd(b, k); + for (size_t c = 0; c < blk; ++c) o[c] = addmod(x[c], y[c], p); + continue; + } + case OP_MUL: + if (lt.tconst[a] || lt.tconst[b]) { + const u64* x = rd(a, lt.tconst[a] ? 0 : k); const u64* y = rd(b, lt.tconst[b] ? 0 : k); + pmul(x, y, dr(x), dr(y)); + } else { + for (int ii = 0; ii <= k; ++ii) + pmul(hp(a, ii), hp(b, k - ii), + [&](int mo, int& lo, int& hi) { range(a, ii, mo, lo, hi); }, + [&](int mo, int& lo, int& hi) { range(b, k - ii, mo, lo, hi); }); + } + break; + case OP_INV: { + if (k == 0) { + J.invA0[i].assign(blk, 0); + if (!poly_inv(J.invA0[i].data(), rd(a, 0), pb, p)) return false; + std::copy(J.invA0[i].begin(), J.invA0[i].end(), o); + continue; + } + for (int j = 1; j <= k; ++j) + pmul(hp(a, j), hp(s, k - j), + [&](int mo, int& lo, int& hi) { range(a, j, mo, lo, hi); }, + [&](int mo, int& lo, int& hi) { range(s, k - j, mo, lo, hi); }); + for (size_t c = 0; c < blk; ++c) tmp[c] = submod(0, br.red(acc[c]), p); + std::fill(acc.begin(), acc.end(), (u64)0); + pmul(J.invA0[i].data(), tmp.data(), dr(J.invA0[i].data()), dr(tmp.data())); + break; + } + } + for (size_t c = 0; c < blk; ++c) o[c] = br.red(acc[c]); + } + if (k == 0) { + J.fVal.assign(m, 0); + for (int i = 0; i < m; ++i) J.fVal[i] = rd(seg.fOut[i], 0)[0] % p; + } + for (int gi = 0; gi < nOut; ++gi) { + const u64* g = rd(seg.gOut[gi], k); + for (int mo = 0; mo < nM; ++mo) { + const u64* gm = g + (size_t)mo * wb; + J.rows.push_back(std::vector(gm + 1, gm + wb)); + J.gVal.push_back(gm[0] % p); + } + } + J.K = k; + } + return true; +} + +// Returns the freed heap of every thread to the system: the jets of many threads leave the arenas +// fragmented, which counts against a limit on the address space. Called after the calls at high +// orders only, since the walk over the arenas holds every thread. +void release_heap() { +#if defined(__GLIBC__) + malloc_trim(0); +#endif +} + +// Taylor values of a slot over many orders are mapped and unmapped on their own rather than taken from +// the arenas of the threads, where the freed ones stay. +struct MapLargeValues { + MapLargeValues() { +#if defined(__GLIBC__) + mallopt(M_MMAP_THRESHOLD, 256 * 1024); +#endif + } +} g_map_large_values; + +// Sessions of continued jets: one per key, the oldest dropped past a memory budget. +struct SegSession { + std::mutex mu; + int nz = 0, nLane = 0, B = 0, nb = 0, nOut = 0; + std::vector blocks; + std::vector > segBlocks; // a chain: the blocks of each segment + std::vector > basis; + std::vector pivCol, ranks; + size_t bytes = 0; + long long used = 0; +}; +std::mutex g_sess_mu; +std::map > g_sess; +long long g_sess_clock = 0; + +double session_budget() { + const char* e = std::getenv("SYMIDENT_JETMB"); + return (e && *e) ? std::atof(e) * 1048576.0 : 8.0 * chain_block_bytes(); +} + +std::shared_ptr session_get(const std::string& key, bool& fresh) { + std::lock_guard lk(g_sess_mu); + auto it = g_sess.find(key); + fresh = it == g_sess.end(); + if (fresh) it = g_sess.emplace(key, std::make_shared()).first; + it->second->used = ++g_sess_clock; + return it->second; +} + +// The bytes of the jets of `lt` over nLane lanes in nb blocks to order Nrun, with the rows. +double lean_bytes(const LeanTape& lt, int nLane, int nb, int Nrun, int nOut, int nM = 1, int early = 0, + int nStates = 0) { + double h = 0, S = (double)lt.hist.size(); + for (char x : lt.hist) h += x; + double orders = 32.0 * ((Nrun + 2 + 31) / 32); + return 8.0 * nM * (nLane + nb) * (h * orders + S + (double)nOut * (Nrun + 1) + (double)nStates * early); +} + +// jets being formed, in bytes, which the budget holds besides the sessions kept +double g_sess_inflight = 0; + +// Reserves `need` bytes of the budget, dropping the oldest sessions not in use; false where the +// bytes do not fit. +bool session_reserve(double need, const SegSession* self) { + std::lock_guard lk(g_sess_mu); + double budget = session_budget(); + for (;;) { + double tot = g_sess_inflight; + for (auto& kv : g_sess) if (kv.second.get() != self) tot += (double)kv.second->bytes; + if (tot + need <= budget) { + g_sess_inflight += need; + return true; + } + auto old = g_sess.end(); + for (auto it = g_sess.begin(); it != g_sess.end(); ++it) { + if (it->second.get() == self || !it->second->mu.try_lock()) continue; + it->second->mu.unlock(); + if (old == g_sess.end() || it->second->used < old->second->used) old = it; + } + if (old == g_sess.end()) return false; + g_sess.erase(old); + } +} + +void session_release(double need) { + std::lock_guard lk(g_sess_mu); + g_sess_inflight -= need; +} + +void session_trim() { + std::lock_guard lk(g_sess_mu); + double budget = session_budget(); + for (;;) { + double tot = 0; + for (auto& kv : g_sess) tot += (double)kv.second->bytes; + if (tot <= budget || g_sess.empty()) return; + auto old = g_sess.begin(); + for (auto it = g_sess.begin(); it != g_sess.end(); ++it) + if (it->second->used < old->second->used) old = it; + g_sess.erase(old); + } +} + +// The ranks of one segment from the states `q` at orders 0..Nt (symSegmentRanks with fromStates), +// continued from the jets kept under `key`; false where the session does not apply. +bool session_ranks(const std::string& key, const SegRaw& seg, int nLeaves, int nStates, int nz, + const std::vector& dualCol, const std::vector& leaf, + const std::vector& qs, bool moves, int Nt, int threads, + const std::vector& dropStates, u64 p, std::vector& ranksOut, + std::vector& fValOut) { + LeanTape lt = lean_tape(seg, nLeaves, nStates); + if (!lt.ok) return false; + bool fresh; + std::shared_ptr ss = session_get(key, fresh); + std::lock_guard lk(ss->mu); + int nzA = nz + nStates + 1, nOut = (int)seg.gOut.size(); + int Nrun = Nt + 1; + if (ss->blocks.empty()) { + ss->nz = nz; ss->nOut = nOut; + ss->nLane = nz + nStates; + ss->nb = std::max(1, std::min(threads, ss->nLane / 16)); + ss->B = (ss->nLane + ss->nb - 1) / ss->nb; + ss->nb = (ss->nLane + ss->B - 1) / ss->B; + } + if (ss->nz != nz || ss->nOut != nOut) return false; + // jets past the budget are formed by the blocked kernel instead + double need = ss->blocks.empty() || ss->blocks[0].K < Nrun ? + std::max(0.0, lean_bytes(lt, ss->nLane, ss->nb, Nrun, nOut) - (double)ss->bytes) : 0.0; + if (!session_reserve(need, ss.get())) { + std::lock_guard lk2(g_sess_mu); + g_sess.erase(key); + return false; + } + struct Release { double n; ~Release() { session_release(n); } } rel{need}; + if (ss->blocks.empty()) { + // each state a separate unit lane after the coordinates + std::vector > st(nStates, std::vector(1 + ss->nLane, 0)); + for (int i = 0; i < nStates; ++i) { + st[i][0] = qs[i]; + st[i][1 + nz + i] = 1; + } + for (int b = 0; b < ss->nb; ++b) + ss->blocks.push_back(lean_block(lt, seg, nLeaves, leaf, dualCol, st, b * ss->B, + std::min(ss->nLane, (b + 1) * ss->B), ss->nLane)); + } + if (ss->blocks[0].K < Nrun) { + std::vector okB(ss->nb, 1); + int nThr = std::max(1, std::min(threads, ss->nb)); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1) + for (int b = 0; b < ss->nb; ++b) { + try { + okB[b] = lean_extend(ss->blocks[b], lt, seg, Nrun, p); + } catch (const std::bad_alloc&) { + okB[b] = 0; // the blocked kernel forms them instead + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + for (char o : okB) + if (!o) { + std::lock_guard lk2(g_sess_mu); + g_sess.erase(key); + return false; + } + } + // rows of the new orders, ranked after those kept + const LeanJets& J0 = ss->blocks[0]; + for (int k = (int)ss->ranks.size(); k <= Nt; ++k) { + for (int gi = 0; gi < nOut; ++gi) { + std::vector r(nzA, 0); + for (int b = 0; b < ss->nb; ++b) { + const std::vector& lane = ss->blocks[b].rows[(size_t)k * nOut + gi]; + std::copy(lane.begin(), lane.end(), r.begin() + ss->blocks[b].s0); + } + if (moves) r[nzA - 1] = submod(0, mulmod((u64)(k + 1) % p, J0.gVal[(size_t)(k + 1) * nOut + gi], p), p); + for (int d : dropStates) r[nz + d] = 0; + for (size_t b = 0; b < ss->basis.size(); ++b) { + u64 f = r[ss->pivCol[b]] % p; + if (!f) continue; + u64 nf = p - f; + for (int c = 0; c < nzA; ++c) + if (ss->basis[b][c]) r[c] = addmod(r[c] % p, mulmod(nf, ss->basis[b][c], p), p); + } + int pc = -1; + for (int c = 0; c < nzA; ++c) if (r[c] % p) { pc = c; break; } + if (pc < 0) continue; + u64 inv = invmod(r[pc] % p, p); + for (int c = 0; c < nzA; ++c) r[c] = mulmod(r[c] % p, inv, p); + ss->basis.push_back(std::move(r)); + ss->pivCol.push_back(pc); + } + ss->ranks.push_back((int)ss->basis.size()); + } + ranksOut.assign(ss->ranks.begin(), ss->ranks.begin() + Nt + 1); + fValOut = J0.fVal; + size_t by = 0; + for (const auto& J : ss->blocks) by += J.bytes(); + for (const auto& r : ss->basis) by += r.capacity() * 8; + ss->bytes = by; + session_trim(); + return true; +} + + +// build_one_chain in the lean jets without a series, a moving boundary or an event after the start, else +// REV_FORWARD: a segment starts at the orders up to Mtot of the segment before, shifted into the boundary gap. +// The jets are kept under `key`, where one is given, and continued by a call at a higher order. +int lean_chain(const std::vector& segs, int nLeaves, int nStates, int nz, + const std::vector& dualCol, const std::vector& leafPt, int Nt, int Mtot, u64 p, + std::vector >& rows, std::vector >& srows, + int threads, bool keepZeroSer, const std::string& key) { + int nSeg = (int)segs.size(), w = nz + 1; + if (nSeg == 0) return REV_FORWARD; + std::vector lts; + for (int sj = 0; sj < nSeg; ++sj) { + lts.push_back(lean_tape(segs[sj], nLeaves, nStates)); + if (!lts.back().ok || (sj > 0 && segs[sj].hasEv)) return REV_FORWARD; + } + const SegRaw& s0 = segs[0]; + if (!s0.hasIcSeed && !s0.hasIcTape) return REV_FORWARD; + std::vector moves; + if (!chain_moves(segs, nLeaves, w, dualCol, leafPt, p, moves)) return REV_FAIL; + for (char m : moves) if (m) return REV_FORWARD; + std::vector leaf(nLeaves); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)leafPt[L] % (long long)p; if (pv < 0) pv += p; + leaf[L] = (u64)pv; + } + // the gaps between the start times, which must not vanish + std::vector tau(nSeg, 0); + for (int sj = 0; sj < nSeg; ++sj) { + const SegRaw& sg = segs[sj]; + if (!sg.hasTm) continue; + std::vector > tmVal(nLeaves + sg.tmOp.size(), std::vector(1, 0)); + for (int L = 0; L < nLeaves; ++L) tmVal[L][0] = leaf[L]; + if (!eval_ic_order0(tmVal, sg.tmOp, sg.tmA, sg.tmB, sg.tmCval, nLeaves, 1, p)) return REV_FAIL; + tau[sj] = tmVal[sg.tmOut[0]][0] % p; + } + int K = std::max(1, nSeg - 1); + std::vector lineC(K, 1); + for (int i = 0; i + 1 < nSeg; ++i) { + if (!segs[i].hasTm || !segs[i + 1].hasTm) continue; + lineC[i] = submod(tau[i + 1], tau[i], p); + if (!lineC[i]) return REV_FAIL; + } + // the start of the chain, a dual over the coordinates + std::vector > st(nStates, std::vector(w, 0)); + if (s0.hasIcSeed) { + for (int i = 0; i < nStates; ++i) + for (int c = 0; c < w; ++c) st[i][c] = s0.icSeed[i][c]; + } else { + std::vector > icVal(nLeaves + s0.icOp.size(), std::vector(w, 0)); + for (int L = 0; L < nLeaves; ++L) { + icVal[L][0] = leaf[L]; + if (dualCol[L] >= 0) icVal[L][1 + dualCol[L]] = 1; + } + if (!eval_ic_order0(icVal, s0.icOp, s0.icA, s0.icB, s0.icCval, nLeaves, w, p)) return REV_FAIL; + for (int i = 0; i < nStates; ++i) st[i] = icVal[s0.icOut[i]]; + } + std::shared_ptr ss; + if (!key.empty()) { + bool fresh; + ss = session_get(key, fresh); + } else { + ss = std::make_shared(); + } + std::lock_guard lk(ss->mu); + int Nrun = std::max(Nt, Mtot); + PolyBasis pbS(K, Mtot, 1); + int nM = pbS.nMono; + if (ss->segBlocks.empty()) { + ss->nz = nz; + ss->nb = std::max(1, std::min(threads, nz / 16)); + ss->B = std::max(1, (nz + ss->nb - 1) / ss->nb); + ss->nb = std::max(1, (nz + ss->B - 1) / ss->B); + } + if (ss->nz != nz) return REV_FORWARD; + // jets past the budget are formed by the blocked kernel instead + double need = -(double)ss->bytes; + for (int sj = 0; sj < nSeg; ++sj) + need += lean_bytes(lts[sj], nz, ss->nb, Nrun, (int)segs[sj].gOut.size(), nM, Mtot + 1, nStates); + need = std::max(0.0, need); + if (!session_reserve(need, ss.get())) { + if (!key.empty()) { + std::lock_guard lk2(g_sess_mu); + g_sess.erase(key); + } + return REV_FORWARD; + } + struct Release { double n; ~Release() { session_release(n); } } rel{need}; + if (ss->segBlocks.empty()) { + ss->segBlocks.resize(nSeg); + // each segment from the start the segment before gives it, the orders up to Mtot first + std::vector > cur(nStates, std::vector((size_t)nM * w, 0)); + for (int i = 0; i < nStates; ++i) std::copy(st[i].begin(), st[i].end(), cur[i].begin()); + for (int sj = 0; sj < nSeg; ++sj) { + for (int b = 0; b < ss->nb; ++b) { + ss->segBlocks[sj].push_back(lean_block(lts[sj], segs[sj], nLeaves, leaf, dualCol, cur, b * ss->B, + std::min(nz, (b + 1) * ss->B), nz, K, Mtot)); + ss->segBlocks[sj].back().keepEarly = sj + 1 < nSeg ? Mtot : -1; + } + if (sj + 1 == nSeg) break; + std::vector okE(ss->nb, 1); + for (int b = 0; b < ss->nb; ++b) okE[b] = lean_extend(ss->segBlocks[sj][b], lts[sj], segs[sj], Mtot, p); + for (char o : okE) + if (!o) { + ss->segBlocks.clear(); + if (!key.empty()) { + std::lock_guard lk2(g_sess_mu); + g_sess.erase(key); + } + return REV_FORWARD; + } + for (auto& c : cur) std::fill(c.begin(), c.end(), (u64)0); + for (int i = 0; i < nStates; ++i) + for (int k = 0; k <= Mtot; ++k) + for (int am = 0; am < nM; ++am) { + int dst = pbS.shiftSlot(am, sj, k); + if (dst < 0) continue; + u64* d = cur[i].data() + (size_t)dst * w; + for (const LeanJets& J : ss->segBlocks[sj]) { + const u64* x = J.early[i][k].data() + (size_t)am * J.wb; + if (J.s0 == 0) d[0] = addmod(d[0], x[0], p); + for (int c = 1; c < J.wb; ++c) d[J.s0 + c] = addmod(d[J.s0 + c], x[c], p); + } + } + } + } + if ((int)ss->segBlocks.size() != nSeg) return REV_FORWARD; + int nb = ss->nb, nJobs = nSeg * nb; + std::vector okB(nJobs, 1); + int nThr = std::max(1, std::min(threads, nJobs)); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1) + for (int jb = 0; jb < nJobs; ++jb) { + try { + int sj = jb / nb, b = jb % nb; + LeanJets& J = ss->segBlocks[sj][b]; + if (J.K < Nrun) okB[jb] = lean_extend(J, lts[sj], segs[sj], Nrun, p); + } catch (const std::bad_alloc&) { + okB[jb] = 0; // the blocked kernel forms them instead + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + for (char o : okB) + if (!o) { + if (!key.empty()) { + std::lock_guard lk2(g_sess_mu); + g_sess.erase(key); + } + return REV_FORWARD; + } + for (int sj = 0; sj < nSeg; ++sj) { + int nOut = (int)segs[sj].gOut.size(); + size_t from = rows.size(); + for (int gi = 0; gi < nOut; ++gi) + for (int k = 0; k <= Nt; ++k) + for (int mo = 0; mo < nM; ++mo) { + std::vector r(nz, 0); + for (const LeanJets& J : ss->segBlocks[sj]) { + const std::vector& lane = J.rows[((size_t)k * nOut + gi) * nM + mo]; + std::copy(lane.begin(), lane.end(), r.begin() + J.s0); + } + rows.push_back(std::move(r)); + } + rows_to_line(rows, from, pbS, lineC, nz, Mtot + 1, p, srows, keepZeroSer); + } + if (!key.empty()) { + size_t by = 0; + for (const auto& sb : ss->segBlocks) + for (const auto& J : sb) by += J.bytes(); + ss->bytes = by; + session_trim(); + } + return REV_OK; +} + } // namespace // Multi-condition observability over a shared coordinate space. Each element of @@ -2177,50 +3978,299 @@ List symObsNullMulti(List tapes, int nLeaves, int nStates, // serial pre-pass into flat vectors: the parallel region reads no Value or List, whose named // access can insert and whose conversion copies - std::vector td(T); - for (int t = 0; t < T; ++t) td[t] = extract_cond_raw(tapes[t], nStates, w); + TapeSet ts(tapes, nStates, w); + + // the conditions a chunk at a time, built in parallel; the rows of a chunk join the basis and are + // dropped. A vanishing denominator in any condition marks failure (no early return inside OpenMP). + int nThr = cores > 0 ? cores : 1; + int chunk = std::max(64, 4 * nThr); + RrefBasis basis(nz, p); + for (int t0 = 0; t0 < T; t0 += chunk) { + int t1 = std::min(T, t0 + chunk), nc = t1 - t0; + std::vector > > perRows(nc); + std::vector okFlag(nc, 1); + int inner = chain_inner_threads(cores, nc); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1 && nc > 1) + for (int t = t0; t < t1; ++t) { + try { + CondRaw tmp; + if (!build_one_condition_blocked(ts.get(t, tmp), leafVal, nLeaves, nStates, nz, Nt, p, + perRows[t - t0], inner)) + okFlag[t - t0] = 0; + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + for (int t = 0; t < nc; ++t) + if (!okFlag[t]) return List::create(_["ok"] = false); + std::vector > rows; + for (int t = 0; t < nc; ++t) + for (auto& r : perRows[t]) rows.push_back(std::move(r)); + basis.add(rows, nThr); + } - // parallel per-condition build: each thread owns one row block; a vanishing - // denominator in any condition marks failure (no early return inside OpenMP). - std::vector > > perRows(T); + std::vector > R0; + std::vector pivots; + basis.full(R0, pivots); + int rank = (int)pivots.size(); + IntegerMatrix R(rank, nz); + for (int i = 0; i < rank; ++i) + for (int c = 0; c < nz; ++c) R(i, c) = (int)R0[i][c]; + IntegerVector piv(rank); + for (int i = 0; i < rank; ++i) piv[i] = pivots[i]; + + return List::create(_["ok"] = true, _["R"] = R, _["pivots"] = piv, + _["rank"] = rank, _["dim"] = nz); +} + +// Per column of V (nz x D residues) whether every row of every condition annihilates it: the +// directions in the kernel of the stacked rows, checked condition by condition without stacking. +List symObsAnnihilates(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, IntegerMatrix V, int cores = 1) { + if (V.ncol() < zSlots.size()) { + IntegerMatrix pts(1, nLeaves); + for (int L = 0; L < nLeaves; ++L) pts(0, L) = point[L]; + NumericVector pr(1); + pr[0] = pIn; + SEXP lanes = symObsAnnihilatesBatch(tapes, nLeaves, nStates, zSlots, pts, pr, Nt, V, cores); + if (!Rf_isNull(lanes)) return List(List(lanes)[0]); + } + u64 p = (u64)pIn; + int nz = zSlots.size(), w = nz + 1, T = tapes.size(), D = V.ncol(); + std::vector dualCol(nLeaves, -1); + for (int c = 0; c < nz; ++c) dualCol[zSlots[c]] = c; + std::vector > leafVal(nLeaves, std::vector(w, 0)); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)point[L] % (long long)p; + if (pv < 0) pv += p; + leafVal[L][0] = (u64)pv; + if (dualCol[L] >= 0) leafVal[L][1 + dualCol[L]] = 1; + } + std::vector > Vc(D, std::vector(nz, 0)); + for (int d = 0; d < D; ++d) + for (int c = 0; c < nz; ++c) Vc[d][c] = red(V(c, d), p); + TapeSet ts(tapes, nStates, w); + int nThr = cores > 0 ? cores : 1; std::vector okFlag(T, 1); - int inner = chain_inner_threads(cores, T); + std::vector > bad(T, std::vector(D, 0)); OmpGuard guard_; - #pragma omp parallel for num_threads(cores > 0 ? cores : 1) schedule(dynamic) \ - if (cores > 1 && T > 1) + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1 && T > 1) for (int t = 0; t < T; ++t) { try { - if (!build_one_condition_blocked(td[t], leafVal, nLeaves, nStates, nz, Nt, p, - perRows[t], inner)) + CondRaw tmp; + std::vector > rows; + if (!build_one_condition_blocked(ts.get(t, tmp), leafVal, nLeaves, nStates, nz, Nt, p, rows, 1)) { okFlag[t] = 0; + continue; + } + const Barrett br(p); + for (const auto& r : rows) + for (int d = 0; d < D; ++d) { + if (bad[t][d]) continue; + u64 acc = 0; + for (int c = 0; c < nz; ++c) + if (r[c] && Vc[d][c]) acc = br.red(acc + (r[c] % p) * Vc[d][c]); + if (acc) bad[t][d] = 1; + } } catch (...) { guard_.capture(); } } guard_.rethrow(); - for (int t = 0; t < T; ++t) if (!okFlag[t]) return List::create(_["ok"] = false); + LogicalVector zero(D); + for (int d = 0; d < D; ++d) { + zero[d] = 1; + for (int t = 0; t < T; ++t) if (bad[t][d]) { zero[d] = 0; break; } + } + return List::create(_["ok"] = true, _["zero"] = zero); +} - std::vector > rows; +// Per point (row of `points`) and column of V (nz x D residues) whether every row of every condition annihilates +// the column, from jets seeded along V where cheaper than reverse-mode rows, else from the rows. ok is FALSE at a +// vanishing denominator; NULL where a tape holds a steady-state seed (duals laid out over the coordinates). +SEXP symObsAnnihilatesBatch(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerMatrix points, + NumericVector primes, int Nt, IntegerMatrix V, int cores) { + int nz = zSlots.size(), T = tapes.size(), D = V.ncol(), nB = points.nrow(); + TapeSet ts(tapes, nStates, nz + 1); for (int t = 0; t < T; ++t) - for (size_t i = 0; i < perRows[t].size(); ++i) - rows.push_back(std::move(perRows[t][i])); - - std::vector pivots = rref_mod(rows, p); - int rank = (int)pivots.size(); - IntegerMatrix R(rank, nz); - for (int i = 0; i < rank; ++i) - for (int c = 0; c < nz; ++c) R(i, c) = (int)rows[i][c]; - IntegerVector piv(rank); - for (int i = 0; i < rank; ++i) piv[i] = pivots[i]; + if (ts.td[ts.base[t]].hasIcSeed) return R_NilValue; + std::vector colOf(nLeaves, -1); + for (int c = 0; c < nz; ++c) colOf[zSlots[c]] = c; + // lanes per pass, bounded so that the Taylor values of one condition stay within chain_block_bytes() + size_t slots = 0; + for (int t = 0; t < T; ++t) slots = std::max(slots, ts.td[ts.base[t]].op.size()); + double perLane = (double)(nLeaves + nStates + slots) * (Nt + 1) * 8.0; + int B = std::max(1, std::min(D, (int)(chain_block_bytes() / perLane) - 1)); + int nBlk = D > 0 ? (D + B - 1) / B : 0; + std::vector lanes(T); + bool anyRows = false; + for (int t = 0; t < T; ++t) { + const CondRaw& cd = ts.td[ts.base[t]]; + lanes[t] = !(reverse_pays(cd.gOut.size(), nz, Nt) && (double)D + 1 >= (double)cd.gOut.size() * (Nt + 2)); + anyRows = anyRows || !lanes[t]; + } + // the leaves with one dual per coordinate, per point, for the conditions read from their rows + std::vector > > oneHot(anyRows ? nB : 0); + for (int bi = 0; bi < (int)oneHot.size(); ++bi) { + u64 p = (u64)primes[bi]; + oneHot[bi].assign(nLeaves, std::vector(nz + 1, 0)); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)points(bi, L) % (long long)p; + if (pv < 0) pv += p; + oneHot[bi][L][0] = (u64)pv; + if (colOf[L] >= 0) oneHot[bi][L][1 + colOf[L]] = 1; + } + } + std::vector > bad((size_t)nB * D); + for (auto& x : bad) x.store(0); + std::vector > okPt(nB); + for (auto& x : okPt) x.store(1); + long long nTask = (long long)nB * T * nBlk; + int nThr = cores > 0 ? cores : 1; + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1 && nTask > 1) + for (long long k = 0; k < nTask; ++k) { + try { + int bi = (int)(k / ((long long)T * nBlk)), rem = (int)(k % ((long long)T * nBlk)); + int t = rem / nBlk, b = rem % nBlk; + int d0 = b * B, d1 = std::min(D, d0 + B), nd = d1 - d0; + if (!okPt[bi].load() || (!lanes[t] && b > 0)) continue; + bool open = false; + for (int d = d0; d < d1 && !open; ++d) open = !bad[(size_t)bi * D + d].load(); + if (!open) continue; + u64 p = (u64)primes[bi]; + if (!lanes[t]) { + CondRaw tmp; + std::vector > rows; + if (!build_one_condition_blocked(ts.get(t, tmp), oneHot[bi], nLeaves, nStates, nz, Nt, p, rows, 1)) { + okPt[bi].store(0); + continue; + } + const Barrett br(p); + for (int d = 0; d < D; ++d) { + if (bad[(size_t)bi * D + d].load()) continue; + for (const auto& r : rows) { + u64 acc = 0; + for (int c = 0; c < nz; ++c) + if (r[c] && V(c, d)) acc = br.red(acc + (r[c] % p) * red(V(c, d), p)); + if (acc) { bad[(size_t)bi * D + d].store(1); break; } + } + } + continue; + } + std::vector > lv(nLeaves, std::vector(nd + 1, 0)); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)points(bi, L) % (long long)p; + if (pv < 0) pv += p; + lv[L][0] = (u64)pv; + if (colOf[L] >= 0) + for (int d = d0; d < d1; ++d) lv[L][1 + d - d0] = red(V(colOf[L], d), p); + } + CondRaw tmp; + std::vector > rows; + if (!build_one_condition(ts.get(t, tmp), lv, nLeaves, nStates, nd, nd + 1, Nt, p, rows)) { + okPt[bi].store(0); + continue; + } + for (const auto& r : rows) + for (int j = 0; j < nd; ++j) + if (r[j] % p) bad[(size_t)bi * D + d0 + j].store(1); + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + List out(nB); + for (int bi = 0; bi < nB; ++bi) { + if (!okPt[bi].load()) { out[bi] = List::create(_["ok"] = false); continue; } + LogicalVector zero(D); + for (int d = 0; d < D; ++d) zero[d] = !bad[(size_t)bi * D + d].load(); + out[bi] = List::create(_["ok"] = true, _["zero"] = zero); + } + return out; +} - return List::create(_["ok"] = true, _["R"] = R, _["pivots"] = piv, - _["rank"] = rank, _["dim"] = nz); +// Conditions in `order` (all tapes if empty) join a reduced basis with the rows to Lie order Nt at the point; one is +// chosen where the rows raise the rank or `keep` marks it, until the rank reaches `target`. Chunks give the choice of +// one at a time; `gain` is the rank each chosen condition adds, `taken` the conditions read. +List symObsCover(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, int target, int cores, IntegerVector order, LogicalVector keep) { + u64 p = (u64)pIn; + int nz = zSlots.size(), w = nz + 1, T = tapes.size(); + std::vector ord; + if (order.size() == 0) { + for (int t = 0; t < T; ++t) ord.push_back(t); + } else { + for (int i = 0; i < order.size(); ++i) { + if (order[i] < 0 || order[i] >= T) throw std::invalid_argument("order names no tape"); + ord.push_back(order[i]); + } + } + int n = (int)ord.size(); + std::vector forced(T, 0); + for (int t = 0; t < keep.size() && t < T; ++t) forced[t] = keep[t] ? 1 : 0; + std::vector dualCol(nLeaves, -1); + for (int c = 0; c < nz; ++c) dualCol[zSlots[c]] = c; + std::vector > leafVal(nLeaves, std::vector(w, 0)); + for (int L = 0; L < nLeaves; ++L) { + long long pv = (long long)point[L] % (long long)p; + if (pv < 0) pv += p; + leafVal[L][0] = (u64)pv; + if (dualCol[L] >= 0) leafVal[L][1 + dualCol[L]] = 1; + } + TapeSet ts(tapes, nStates, w); + int nThr = cores > 0 ? cores : 1, chunk = std::max(8, 2 * nThr); + RrefBasis basis(nz, p); + std::vector chosen, gain; + int taken = 0; + for (int i0 = 0; i0 < n && basis.rank() < target; i0 += chunk) { + int i1 = std::min(n, i0 + chunk), nc = i1 - i0; + std::vector > > perRows(nc); + std::vector okFlag(nc, 1); + OmpGuard guard_; + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1 && nc > 1) + for (int i = i0; i < i1; ++i) { + try { + CondRaw tmp; + if (!build_one_condition_blocked(ts.get(ord[i], tmp), leafVal, nLeaves, nStates, nz, Nt, p, + perRows[i - i0], 1)) + okFlag[i - i0] = 0; + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + for (int i = 0; i < nc; ++i) + if (!okFlag[i]) return List::create(_["ok"] = false); + std::vector owner; + std::vector > rows; + for (int i = 0; i < nc; ++i) + for (auto& r : perRows[i]) { + rows.push_back(std::move(r)); + owner.push_back(i); + } + std::vector from; + basis.add(rows, nThr, &from); + std::vector g(nc, 0); + for (int k : from) ++g[owner[k]]; + for (int i = 0; i < nc; ++i) + if (g[i] > 0 || forced[ord[i0 + i]]) { + chosen.push_back(ord[i0 + i]); + gain.push_back(g[i]); + } + taken = i1; + } + IntegerVector out(chosen.begin(), chosen.end()), gv(gain.begin(), gain.end()); + return List::create(_["ok"] = true, _["conditions"] = out, _["gain"] = gv, _["rank"] = basis.rank(), + _["taken"] = taken); } -// Rank of the stacked single-segment rows of `tapes` up to each Lie order 0..Nt, by an -// incremental echelon in order-major row order. The rows up to order k do not depend +// Rank of the stacked single-segment rows of `tapes` up to each Lie order 0..Nt: the rows of an +// order join the reduced basis together, the orders ascending. The rows up to order k do not depend // on Nt, so ranks[k] equals the rank of symObsNullMulti at order k. List symObsRankProfile(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, int cores = 1) { @@ -2236,17 +4286,17 @@ List symObsRankProfile(List tapes, int nLeaves, int nStates, IntegerVector zSlot leafVal[L][0] = (u64)pv; if (dualCol[L] >= 0) leafVal[L][1 + dualCol[L]] = 1; } - std::vector td(T); - for (int t = 0; t < T; ++t) td[t] = extract_cond_raw(tapes[t], nStates, w); + TapeSet ts(tapes, nStates, w); std::vector > > perRows(T); std::vector okFlag(T, 1); int inner = chain_inner_threads(cores, T); + int nThr = cores > 0 ? cores : 1; OmpGuard guard_; - #pragma omp parallel for num_threads(cores > 0 ? cores : 1) schedule(dynamic) \ - if (cores > 1 && T > 1) + #pragma omp parallel for num_threads(nThr) schedule(dynamic) if (nThr > 1 && T > 1) for (int t = 0; t < T; ++t) { try { - if (!build_one_condition_blocked(td[t], leafVal, nLeaves, nStates, nz, Nt, p, + CondRaw tmp; + if (!build_one_condition_blocked(ts.get(t, tmp), leafVal, nLeaves, nStates, nz, Nt, p, perRows[t], inner)) okFlag[t] = 0; } catch (...) { @@ -2258,32 +4308,16 @@ List symObsRankProfile(List tapes, int nLeaves, int nStates, IntegerVector zSlot if (!okFlag[t]) return List::create(_["ok"] = false); // rows of a condition are ordered by output, then order - std::vector > basis; - std::vector pivCol; + RrefBasis basis(nz, p); IntegerVector ranks(Nt + 1); for (int k = 0; k <= Nt; ++k) { + std::vector > batch; for (int t = 0; t < T; ++t) { int nOut = (int)(perRows[t].size() / (size_t)(Nt + 1)); - for (int gi = 0; gi < nOut; ++gi) { - std::vector& r = perRows[t][(size_t)gi * (Nt + 1) + k]; - for (size_t b = 0; b < basis.size(); ++b) { - u64 f = r[pivCol[b]] % p; - if (!f) continue; - u64 nf = p - f; - const std::vector& bb = basis[b]; - for (int c = pivCol[b]; c < nz; ++c) - if (bb[c]) r[c] = addmod(r[c] % p, mulmod(nf, bb[c], p), p); - } - int pc = -1; - for (int c = 0; c < nz; ++c) if (r[c] % p) { pc = c; break; } - if (pc < 0) continue; - u64 inv = invmod(r[pc] % p, p); - for (int c = pc; c < nz; ++c) r[c] = mulmod(r[c] % p, inv, p); - basis.push_back(std::move(r)); - pivCol.push_back(pc); - } + for (int gi = 0; gi < nOut; ++gi) batch.push_back(std::move(perRows[t][(size_t)gi * (Nt + 1) + k])); } - ranks[k] = (int)basis.size(); + basis.add(batch, nThr); + ranks[k] = basis.rank(); } return List::create(_["ok"] = true, _["ranks"] = ranks); } @@ -2302,7 +4336,7 @@ List symObsChainRankProfile(List chain, int nLeaves, int nStates, IntegerVector int nSeg = chain.size(); std::vector segs; segs.reserve(nSeg); - for (int sj = 0; sj < nSeg; ++sj) segs.push_back(extract_seg_raw(chain[sj], nStates, w, p)); + for (int sj = 0; sj < nSeg; ++sj) segs.push_back(extract_seg_raw(chain[sj], nLeaves, nStates, w, p)); std::vector moves; if (!chain_moves(segs, nLeaves, w, dualCol, leafPt, p, moves)) return List::create(_["ok"] = false); @@ -2369,8 +4403,7 @@ List symObsDirectional(List tapes, int nLeaves, int nStates, IntegerVector zSlot if (dv < 0) dv += p; leafVal[zSlots[c]][1] = (u64)dv; } - std::vector td(T); - for (int t = 0; t < T; ++t) td[t] = extract_cond_raw(tapes[t], nStates, 2); + TapeSet ts(tapes, nStates, 2); std::vector > > perRows(T); std::vector okFlag(T, 1); OmpGuard guard_; @@ -2378,7 +4411,8 @@ List symObsDirectional(List tapes, int nLeaves, int nStates, IntegerVector zSlot if (cores > 1 && T > 1) for (int t = 0; t < T; ++t) { try { - if (!build_one_condition(td[t], leafVal, nLeaves, nStates, 1, 2, Nt, p, perRows[t])) + CondRaw tmp; + if (!build_one_condition(ts.get(t, tmp), leafVal, nLeaves, nStates, 1, 2, Nt, p, perRows[t])) okFlag[t] = 0; } catch (...) { guard_.capture(); @@ -2416,10 +4450,11 @@ List symObsNullBatch(List tapes, int nLeaves, int nStates, IntegerVector zSlots, std::vector pr(nB); for (int bi = 0; bi < nB; ++bi) pr[bi] = (u64)primes[bi]; - std::vector td(T); - for (int t = 0; t < T; ++t) td[t] = extract_cond_raw(tapes[t], nStates, w); + TapeSet ts(tapes, nStates, w); std::vector okFlag(nB, 1); + // fewer pairs than cores: the rest of the cores build the column blocks of each condition + int inner = chain_inner_threads(cores, nB); std::vector > > redRows(nB); std::vector > redPiv(nB); OmpGuard guard_; @@ -2436,8 +4471,9 @@ List symObsNullBatch(List tapes, int nLeaves, int nStates, IntegerVector zSlots, } std::vector > rows; bool ok = true; + CondRaw tmp; for (int t = 0; t < T && ok; ++t) - if (!build_one_condition_blocked(td[t], leafVal, nLeaves, nStates, nz, Nt, p, rows, 1)) + if (!build_one_condition_blocked(ts.get(t, tmp), leafVal, nLeaves, nStates, nz, Nt, p, rows, inner)) ok = false; if (!ok) { okFlag[bi] = 0; continue; } std::vector pivots = rref_mod(rows, p); @@ -2536,7 +4572,7 @@ List symObsNullChain(List chains, int nLeaves, int nStates, IntegerVector zSlots int nSeg = segs.size(); chainsRaw[t].reserve(nSeg); for (int sj = 0; sj < nSeg; ++sj) - chainsRaw[t].push_back(extract_seg_raw(segs[sj], nStates, w, p)); + chainsRaw[t].push_back(extract_seg_raw(segs[sj], nLeaves, nStates, w, p)); } // an optional continuation series of the leaves (nLeaves x T) std::vector > leafSer; @@ -2605,9 +4641,19 @@ List symObsNullChain(List chains, int nLeaves, int nStates, IntegerVector zSlots // moves (`plain`) the rows of a lower order are those with a lower tag, in the same // sequence; symChainReduce then gives the kernel of that order. With `profile` (gap order // 0) the rank per Lie order, as symObsChainRankProfile, is returned as well. +List chain_rows(List chain, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, int Mtot, int threads, bool profile, std::string session); + List symObsChainRows(List chain, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, int Mtot, int threads = 1, - bool profile = false) { + bool profile = false, std::string session = "") { + List out = chain_rows(chain, nLeaves, nStates, zSlots, point, pIn, Nt, Mtot, threads, profile, session); + if (Nt >= 200) release_heap(); + return out; +} + +List chain_rows(List chain, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, int Mtot, int threads, bool profile, std::string session) { u64 p = (u64)pIn; int nz = zSlots.size(); std::vector dualCol(nLeaves, -1); @@ -2617,7 +4663,7 @@ List symObsChainRows(List chain, int nLeaves, int nStates, IntegerVector zSlots, int nSeg = chain.size(); std::vector segs; segs.reserve(nSeg); - for (int sj = 0; sj < nSeg; ++sj) segs.push_back(extract_seg_raw(chain[sj], nStates, nz + 1, p)); + for (int sj = 0; sj < nSeg; ++sj) segs.push_back(extract_seg_raw(chain[sj], nLeaves, nStates, nz + 1, p)); std::vector moves; if (!chain_moves(segs, nLeaves, nz + 1, dualCol, leafPt, p, moves)) return List::create(_["ok"] = false); @@ -2629,7 +4675,7 @@ List symObsChainRows(List chain, int nLeaves, int nStates, IntegerVector zSlots, int B = chain_block_size(segs, nLeaves, nStates, nz, Nt, Mtot, false, chain_block_bytes()); std::vector > rows, srows; if (!build_chain_blocked(segs, nLeaves, nStates, nz, dualCol, leafPt, Nt, Mtot, p, rows, - srows, nullptr, B, threads, -1, true)) + srows, nullptr, B, threads, -1, true, session)) return List::create(_["ok"] = false); int N = Mtot + 1; // rows run by segment, output, order and gap monomial; series rows by segment, output, order @@ -2690,6 +4736,15 @@ List symObsChainRows(List chain, int nLeaves, int nStates, IntegerVector zSlots, return out; } +// Drops the jets kept for continued calls; returns how many were kept. +int symClearJets() { + std::lock_guard lk(g_sess_mu); + int n = (int)g_sess.size(); + g_sess.clear(); + release_heap(); + return n; +} + // Sets the bytes of Taylor values per column block when SYMIDENT_BLOCKMB is not set; returns the // bytes in effect. double symSetBlockBytes(double bytes) { @@ -2728,10 +4783,24 @@ List symChainReduce(IntegerMatrix rowsIn, IntegerMatrix srowsIn, int nz, int N, // states. Also returns the start states and the field at them. The columns of // `dropStates` (the jets of known inputs) are left out of the ranks. With `fromStates`, // the initial and event values are not evaluated: the starts are the rows of `stateVals`. +List segment_ranks(List segs, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, IntegerMatrix stateVals, int threads, IntegerVector dropStates, + bool fromStates, std::string session); + List symSegmentRanks(List segs, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, IntegerMatrix stateVals = IntegerMatrix(0, 0), int threads = 1, - IntegerVector dropStates = IntegerVector(0), bool fromStates = false) { + IntegerVector dropStates = IntegerVector(0), bool fromStates = false, + std::string session = "") { + List out = segment_ranks(segs, nLeaves, nStates, zSlots, point, pIn, Nt, stateVals, threads, dropStates, + fromStates, session); + if (Nt >= 200) release_heap(); + return out; +} + +List segment_ranks(List segs, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, IntegerMatrix stateVals, int threads, IntegerVector dropStates, + bool fromStates, std::string session) { u64 p = (u64)pIn; int nz = zSlots.size(), nSeg = segs.size(); int wA = nz + nStates + 2, nzA = wA - 1, w0 = nz + 1; @@ -2745,9 +4814,38 @@ List symSegmentRanks(List segs, int nLeaves, int nStates, IntegerVector zSlots, bool givenStates = stateVals.nrow() == nSeg && stateVals.ncol() == nStates; IntegerMatrix ranks(nSeg, Nt + 1), start(nSeg, nStates), field(nSeg, nStates); LogicalVector moves(nSeg); + if (!session.empty() && nSeg == 1 && fromStates && givenStates) { + // one segment from given states: the jets kept under `session` are continued + SegRaw seg = extract_seg_raw(segs[0], nLeaves, nStates, 1, p); + bool mv = false; + if (seg.hasTm) { + std::vector > tmVal(nLeaves + seg.tmOp.size(), std::vector(w0, 0)); + for (int L = 0; L < nLeaves; ++L) { + tmVal[L][0] = leaf[L]; + if (dualCol[L] >= 0) tmVal[L][1 + dualCol[L]] = 1; + } + if (eval_ic_order0(tmVal, seg.tmOp, seg.tmA, seg.tmB, seg.tmCval, nLeaves, w0, p)) + for (int c = 1; c < w0; ++c) if (tmVal[seg.tmOut[0]][c]) mv = true; + } + std::vector qs(nStates); + for (int i = 0; i < nStates; ++i) qs[i] = red(stateVals(0, i), p); + std::vector dr(dropStates.begin(), dropStates.end()), rk; + std::vector fv; + if (session_ranks(session, seg, nLeaves, nStates, nz, dualCol, leaf, qs, mv, Nt, threads, dr, p, + rk, fv)) { + for (int k = 0; k <= Nt; ++k) ranks(0, k) = rk[k]; + for (int i = 0; i < nStates; ++i) { + start(0, i) = (int)qs[i]; + field(0, i) = i < (int)fv.size() ? (int)fv[i] : 0; + } + moves[0] = mv; + return List::create(_["ok"] = true, _["ranks"] = ranks, _["start"] = start, + _["field"] = field, _["moves"] = moves); + } + } std::vector q(nStates, 0); for (int sj = 0; sj < nSeg; ++sj) { - SegRaw seg = extract_seg_raw(segs[sj], nStates, 1, p); + SegRaw seg = extract_seg_raw(segs[sj], nLeaves, nStates, 1, p); // start state at gap order 0 if (fromStates && givenStates) { // the starts are those of stateVals alone, so each segment of a chain is ranked alone @@ -2944,7 +5042,7 @@ List symObsNullChainSeedBatch(List chains, IntegerVector evalChain, for (int pi = 0; pi < nPr; ++pi) { segsRaw[pi][t].reserve(nSeg); for (int sj = 0; sj < nSeg; ++sj) - segsRaw[pi][t].push_back(extract_seg_raw(segs[sj], nStates, w, distinct[pi])); + segsRaw[pi][t].push_back(extract_seg_raw(segs[sj], nLeaves, nStates, w, distinct[pi])); } } @@ -3054,7 +5152,7 @@ List symObsNullChainPointBatch(List chains, int nLeaves, int nStates, IntegerVec for (int pi = 0; pi < nPr; ++pi) { segsRaw[pi][t].reserve(nSeg); for (int sj = 0; sj < nSeg; ++sj) - segsRaw[pi][t].push_back(extract_seg_raw(segs[sj], nStates, w, distinct[pi])); + segsRaw[pi][t].push_back(extract_seg_raw(segs[sj], nLeaves, nStates, w, distinct[pi])); } } std::vector pts((size_t)nB * nLeaves); @@ -3236,6 +5334,65 @@ SEXP symSolveMod(IntegerMatrix A, IntegerVector b, double pIn) { return x; } +// A B over GF(p) for residues below p (int64 entries), rows of A in parallel. +NumericMatrix symMatMulMod(NumericMatrix A, NumericMatrix B, double pIn, int cores = 1) { + u64 p = (u64)pIn; + int n = A.nrow(), m = A.ncol(), k = B.ncol(); + if (B.nrow() != m) throw std::invalid_argument("matmul: inner dimensions differ"); + const Barrett br(p); + const u64 LIM = (((u64)1 << 63) / p) * p; + std::vector Bt((size_t)k * m); + for (int j = 0; j < k; ++j) + for (int i = 0; i < m; ++i) { + long long v = (long long)B(i, j) % (long long)p; + Bt[(size_t)j * m + i] = (u64)(v < 0 ? v + (long long)p : v); + } + NumericMatrix C(n, k); + OmpGuard guard_; + #pragma omp parallel for num_threads(cores > 0 ? cores : 1) schedule(dynamic, 8) + for (int r = 0; r < n; ++r) { + try { + std::vector a(m); + std::vector nzc; + for (int i = 0; i < m; ++i) { + long long v = (long long)A(r, i) % (long long)p; + a[i] = (u64)(v < 0 ? v + (long long)p : v); + if (a[i]) nzc.push_back(i); + } + for (int j = 0; j < k; ++j) { + const u64* b = &Bt[(size_t)j * m]; + u64 acc = 0; + for (int i : nzc) { + u64 t = acc + a[i] * b[i]; + acc = t >= LIM ? t - LIM : t; + } + C(r, j) = (double)br.red(acc); + } + } catch (...) { + guard_.capture(); + } + } + guard_.rethrow(); + return C; +} + +// The rows of M (residues below p), in order, that are independent of the rows before them, and the rank. +List symIndependentRows(NumericMatrix M, double pIn, int cores = 1) { + u64 p = (u64)pIn; + int nr = M.nrow(), nc = M.ncol(); + std::vector > X(nr, std::vector(nc)); + for (int i = 0; i < nr; ++i) + for (int c = 0; c < nc; ++c) { + long long v = (long long)M(i, c) % (long long)p; + X[i][c] = (u64)(v < 0 ? v + (long long)p : v); + } + RrefBasis basis(nc, p); + std::vector from; + basis.add(X, cores > 0 ? cores : 1, &from); + IntegerVector out(from.begin(), from.end()); + return List::create(_["rows"] = out, _["rank"] = basis.rank()); +} + // Compiled twin of gfp.rref_modp (joint/equilibrate path, per sample point). // Entries are doubles in [0, p); returns the pivot rows, 0-based pivot columns and // rank. diff --git a/cpp/kernel.h b/cpp/kernel.h index ce19712..7d37e57 100644 --- a/cpp/kernel.h +++ b/cpp/kernel.h @@ -8,6 +8,12 @@ using namespace Rcpp; List symObsNullMulti(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, int cores); +List symObsAnnihilates(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, IntegerMatrix V, int cores); +SEXP symObsAnnihilatesBatch(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerMatrix points, + NumericVector primes, int Nt, IntegerMatrix V, int cores); +List symObsCover(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, + double pIn, int Nt, int target, int cores, IntegerVector order, LogicalVector keep); List symObsRankProfile(List tapes, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, int cores); List symObsChainRankProfile(List chain, int nLeaves, int nStates, IntegerVector zSlots, @@ -21,12 +27,13 @@ List symObsNullChain(List chains, int nLeaves, int nStates, IntegerVector zSlots IntegerVector NtChain, SEXP pointSer, int serOrder); List symObsChainRows(List chain, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, int Mtot, int threads, - bool profile); + bool profile, std::string session); List symChainReduce(IntegerMatrix rowsIn, IntegerMatrix srowsIn, int nz, int N, double pIn); double symSetBlockBytes(double bytes); +int symClearJets(); List symSegmentRanks(List segs, int nLeaves, int nStates, IntegerVector zSlots, IntegerVector point, double pIn, int Nt, IntegerMatrix stateVals, - int threads, IntegerVector dropStates, bool fromStates); + int threads, IntegerVector dropStates, bool fromStates, std::string session); List symObsNullChainSeedBatch(List chains, IntegerVector evalChain, IntegerMatrix seeds, NumericVector primes, int nLeaves, int nStates, IntegerVector zSlots, int Nt, int Mtot, int cores, @@ -40,6 +47,8 @@ List symSeriesProject(IntegerMatrix S, int nz, int N, double pIn, IntegerVector int cores); SEXP symSolveMod(IntegerMatrix A, IntegerVector b, double pIn); List symRrefMod(NumericMatrix M, double pIn); +List symIndependentRows(NumericMatrix M, double pIn, int cores); +NumericMatrix symMatMulMod(NumericMatrix A, NumericMatrix B, double pIn, int cores); NumericVector symGaugeScores(NumericMatrix F, IntegerVector piv, double pIn, IntegerVector cand); List symGaugeFix(NumericMatrix F, IntegerVector piv, double pIn, int k); diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..c307cfe --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,44 @@ +/* The font stack of Bootstrap 5, as on the dMod2 and cppDE sites. */ +html { + --pst-font-family-base: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", + "Liberation Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", + "Noto Color Emoji"; + --pst-font-family-heading: var(--pst-font-family-base); + --pst-font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", + monospace; +} + +/* From 1400 px on, the page takes 92 % of the window, at most 1600 px. */ +@media (min-width: 1400px) { + .bd-page-width { + max-width: min(92vw, 1600px); + } +} + +/* The text column fills the page next to the sidebar. */ +.bd-main .bd-content .bd-article-container { + max-width: none; +} + +/* Prose, tables, code and figures share one width, so that no table sticks out of the text. */ +.bd-article p, .bd-article li, .bd-article dd, .bd-article table, .bd-article div.highlight, +.bd-article img, .bd-article figure, .bd-article div.math, .bd-article dl { + max-width: 100ch; +} + +/* Justified and hyphenated prose only where the column is wide enough for it. */ +@media (min-width: 768px) { + .bd-article p, .bd-article li, .bd-article dd { + text-align: justify; + hyphens: auto; + } +} + +/* Display math wider than the text column scrolls inside it instead of running over the margin. */ +mjx-container[display="true"] { + display: block; + max-width: 100%; + overflow-x: auto; + overflow-y: hidden; + padding: 0.2em 0; +} diff --git a/docs/_templates/navbar-nav.html b/docs/_templates/navbar-nav.html new file mode 100644 index 0000000..e40110b --- /dev/null +++ b/docs/_templates/navbar-nav.html @@ -0,0 +1,25 @@ +{# The top-level pages in the header; a page with chapters opens a menu of them. #} + diff --git a/docs/api.rst b/docs/api.rst index de2fb8b..dd3681e 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -21,7 +21,7 @@ Results ------- .. autoclass:: Symmetries - :members: summary, unproven, solution_count, reduce, to_dict + :members: summary, unproven, discrete, solution_count, reduce, to_dict .. autoclass:: Symmetry :members: sympy @@ -56,6 +56,9 @@ Debugging: exceptions a route would record in ``info["errors"]`` are raised, except failures of SymPy. ``DIAG`` every diagnostic switch on. +``KERNEL_MODE`` + ``forward`` or ``reverse`` fixes the mode of the kernel rows, ``check`` builds every call in both and raises + where the rows differ; environment only. Diagnostic output: @@ -92,6 +95,10 @@ Routes: no forward seed of the resting states. ``NODIAG`` no diagonal start: resting conditions continued from the forward one only. +``NOSHARED`` + a tape per condition also where the conditions differ only in the values of symbols. +``NOSELECT`` + every condition analyzed, also where many conditions add nothing to the rank. Numbers: @@ -99,15 +106,23 @@ Numbers: orders the rank stays flat before the saturation ends (3). ``LIEPLATEAU_BLOCK`` the plateau per condition block; 0 for one plateau. +``STACKEDPLATEAU`` + in the first pass over the stacked rows of many conditions, the plateau as a fraction of the order the + rank last rose at, consecutive orders without change (0.5); it decides no claim: that pass settles a rank + only by proven directions or invariant fields. ``VERIFY_MARGIN`` orders the saturation guard checks past the reported one (6). ``JETWORK`` characters of jets the jet route may form (1000000). -``DIRECTSECS`` - seconds msolve may take for the direct kernel (120). ``BLOCKMB`` 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`` + megabytes of the jets the kernel keeps for calls at higher orders (eight column blocks); environment only. +``MSOLVE_GB`` + gigabytes of address space of one call of msolve in discrete() where ``memory`` is not given (8). +``FIBER_TERMS`` + terms of the equations of the fiber that one count of discrete() takes (400000). Installation of msolve: diff --git a/docs/conf.py b/docs/conf.py index d18810c..4ae8762 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -5,6 +5,10 @@ import sys import tomllib +from pybtex.plugin import register_plugin +from pybtex.style.formatting.unsrt import Style as _Unsrt +from pybtex.style.formatting.unsrt import dashify +from pybtex.style.template import field, href, join, node, optional, tag ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.path.join(ROOT, "src")) @@ -24,6 +28,7 @@ "sphinx.ext.viewcode", "numpydoc", "myst_parser", + "sphinxcontrib.bibtex", ] autosummary_generate = True numpydoc_show_class_members = False @@ -35,6 +40,92 @@ html_theme = "pydata_sphinx_theme" html_title = f"symident {release}" html_theme_options = {"navigation_with_keys": False, "show_toc_level": 2} -html_static_path = [] +html_static_path = ["_static"] +html_css_files = ["custom.css"] # every page is top level, so the section navigation of the left sidebar stays empty html_sidebars = {"**": []} +templates_path = ["_templates"] + + +def _title(doc): + """The title of the page `doc`, the line above the first underline.""" + with open(os.path.join(ROOT, "docs", doc + ".rst"), encoding="utf-8") as fh: + lines = [line.rstrip() for line in fh] + return next(a for a, b in zip(lines, lines[1:]) if a and b and set(b) <= set("=-~#*")) + + +def _chapters(doc): + """The pages in the toctree of `doc`, with their titles.""" + with open(os.path.join(ROOT, "docs", doc + ".rst"), encoding="utf-8") as fh: + text = fh.read().split(".. toctree::", 1) + if len(text) < 2: + return [] + entries = [line.strip() for line in text[1].split("\n\n", 2)[1].splitlines()] + return [(e, _title(e)) for e in entries if e] + + +# 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", [])]} + +# citations: numbered in the order cited, in the reference format of IEEE, as on the dMod2 and cppDE sites + + +def _pages(): + return field("pages", apply_func=dashify) + + +@node +def _authors(children, context, role="author"): + """The authors, the first one with et al. past six names or with a trailing others.""" + persons = context["entry"].persons[role] + style = context["style"] + names = [style.format_name(p, style.abbreviate_names) for p in persons if str(p) != "others"] + if len(persons) > 6 or str(persons[-1]) == "others": + return join[names[0], " et al."].format_data(context) + return join(sep=", ", sep2=" and ", last_sep=", and ")[names].format_data(context) + + +class _IEEE(_Unsrt): + default_sorting_style = "none" + default_label_style = "number" + + def __init__(self, **kwargs): + kwargs.setdefault("abbreviate_names", True) + super().__init__(**kwargs) + + def _title(self): + return join["\u201c", field("title"), ",\u201d "] + + def _series(self): + return optional[", ser. ", field("series"), optional[", vol. ", field("volume")]] + + def _doi(self): + doi = field("doi", raw=True) + return optional[", doi: ", href[join["https://doi.org/", doi], doi]] + + 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(), "."] + + 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(), "."] + + 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(), "."] + + +register_plugin("pybtex.style.formatting", "ieee", _IEEE) +bibtex_bibfiles = ["refs.bib"] +bibtex_default_style = "ieee" +bibtex_reference_style = "label" diff --git a/docs/guide.rst b/docs/guide.rst index 875e66b..bbb3561 100644 --- a/docs/guide.rst +++ b/docs/guide.rst @@ -1,8 +1,8 @@ -User guide -========== +Guide +===== -The user guide shows how a model is formulated, analyzed and reduced with symident. Each -chapter introduces its examples where they are used; the first chapters follow one running +The guide shows how a model is formulated, analyzed locally and globally, and reduced with +symident. Each chapter introduces the examples where they are used; the first chapters follow one running example, a precursor that is made on a stimulus and becomes an observed product. :doc:`method` gives the mathematics behind each step, and :doc:`api` the full signatures. @@ -12,6 +12,7 @@ example, a precursor that is made on a stimulus and becomes an observed product. guide/models guide/detection guide/reduction + guide/global guide/petab guide/inputs guide/switches diff --git a/docs/guide/detection.rst b/docs/guide/detection.rst index 8c092fb..da05368 100644 --- a/docs/guide/detection.rst +++ b/docs/guide/detection.rst @@ -2,7 +2,7 @@ Detection ========= :func:`symident.detect` computes the rank of the observability-identifiability matrix (OIM, -:doc:`../method`), whose kernel holds the non-identifiable directions, and returns them as +:doc:`../method/local`), whose kernel holds the non-identifiable directions, and returns them as :class:`~symident.Symmetries`. For the running example of :doc:`models`, ``equilibrate=True`` starts every condition at a steady state with the inputs at zero, and ``reconstruct=True`` asks for the directions in closed form: @@ -80,12 +80,12 @@ A direction is proven, checked with an error bound, or checked without one. Its ``res.unproven()`` returns the verified and checked directions. The rank is ``proven``, ``verified`` (with a probability) or a ``lower bound``, in which case the model may have fewer non-identifiable directions. ``info["rank_status"]`` gives the status and the reason, the -printout flags an unproven rank, and :doc:`../method` states when each applies. +printout flags an unproven rank, and :ref:`levels` states when each applies. ``res.symmetries`` lists :class:`~symident.Symmetry` objects, with the generator, its ``level``, ``kind`` (scaling, translation or curved), ``type`` (scaling or general), ``support``, the coordinates it moves, and ``route``, -the way the closed form was obtained (:doc:`../method`). ``res.summary()`` adds the Lie order, +the way the closed form was obtained (:ref:`general-directions`). ``res.summary()`` adds the Lie order, i.e., the highest order of time derivatives of the observables used, the proof of the rank, a suggested gauge (the option below) and what stopped part of the detection, and ``to_dict()`` returns the raw result. @@ -106,7 +106,7 @@ all of them. starts every condition at a steady state, with the inputs at zero. Each conserved total adds a free resting value, held by one species of the total, the pivot. A state at rest may enter exponentials, logarithms, trigonometric and hyperbolic functions and their inverses, - as without ``equilibrate``; :doc:`../method` states the conditions, and an ``InputError`` + as without ``equilibrate``; :ref:`non-rational` states the conditions, and an ``InputError`` names a state whose resting value no coordinate outside these terms moves. Before the analysis, the resting balances are solved at random parameter values: balances without a solution over the complex numbers raise an ``InputError``, and resting states outside the @@ -158,55 +158,9 @@ all of them. ``cores`` threads and worker processes. -Discrete symmetries -------------------- +Global analysis +--------------- -A discrete symmetry, such as two rate constants entering only through their sum and product, -survives local identifiability: another point of the domain gives the same output. -``detect(model, mode="global")`` analyzes local identifiability first and then counts these -points in the domain and reconstructs the maps between them where they are rational; -``res.discrete()`` does the second step on a result, and ``global_options`` passes its -arguments. The two-compartment -model of [Godfrey1983]_ with an input :math:`u` into the first compartment, observed in the -second, is the classical case: - -.. code-block:: 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"]) - r = si.detect(m, mode="global") - s, = r.discrete_symmetries - s["map"], s["level"], s["fixed_set"] - r.info["discrete"]["fundamental_domain"] - -.. code-block:: text - - ({'k01': 'k12', 'x1': '(k01*x2 - k12*x2 + k21*x1)/k21', 'k12': 'k01'}, 'exact', ['k01 - k12']) - ['k01 < k12'] - -The map exchanges the elimination rate :math:`k_{01}` and the return rate :math:`k_{12}` and -moves the initial value of :math:`x_1`, so the model is locally but not globally identifiable. -It is ``exact``: proven by a map of the states. Its image lies in the domain where -``domain_conditions`` hold, here where the image of :math:`x_1(0)` is positive, so -``info["discrete"]["counts"]`` gives at each sample point the solutions over the complex -numbers, over the reals and in the domain, which can differ between regions of the domain. A -map that never meets the domain, such as :math:`\theta \mapsto -\theta` where only -:math:`\theta^2` enters, has ``preserves_domain`` False and is not a symmetry of the model on the -domain. The fundamental domain keeps one point of each orbit; ``reduce()`` lists it in -``Reduction.discrete``. - -A model with directions is reduced first and analyzed in the coordinates of the reduced model -(``info["discrete"]["reduced"]``). The conditions share the coordinates, and the events at given -or estimated times enter as in the local analysis (:doc:`../method`). Under ``equilibrate`` a -condition starts at its resting state, which needs one rational closed form in the coordinates; -states that no observable reads are left out. A model with switches enters, as in the local -analysis, with each condition from its start and each allowed regime as a copy that starts on a -switching surface to an allowed neighbor. The analysis needs msolve (:doc:`../install`); unknown -inputs, results detected with ``reduce_cq``, switches together with events, under -``equilibrate`` or on the parameters alone, and root events are not handled, which -``mode="global"`` reports in ``info["discrete"]["unsupported"]`` with a warning. The counts hold at the sample points, and the -order of the Taylor coefficients, after an event also in the gap, is raised until the count is -stable; ``count_final`` is True when exact maps account for every solution. Where the maps are not found within ``budget`` seconds, the counts are reported -alone. ``res.solution_count()`` gives the count over the algebraic closure at one random point. +``detect(model, mode="global")`` adds the count of the parameter values with the output of a +generic one and the discrete symmetries between them; :doc:`global` describes the call and the +result. diff --git a/docs/guide/global.rst b/docs/guide/global.rst new file mode 100644 index 0000000..6e0a5e8 --- /dev/null +++ b/docs/guide/global.rst @@ -0,0 +1,154 @@ +Global analysis +=============== + +A locally identifiable model can still have several parameter values with the same output, such +as two rate constants that enter only through their sum and product. The global analysis counts +these values at a generic point, the *fiber*, and returns the maps between them, the *discrete +symmetries*. :doc:`../method/global` states the mathematics. + +Calling the global analysis +--------------------------- + +``detect(model, mode="global")`` runs the local analysis, reduces the directions it finds +(:doc:`reduction`) and then analyzes the reduced model globally; ``res.discrete()`` does the +second step on a result of a local detection. ``global_options`` passes the arguments of +:meth:`~symident.Symmetries.discrete`: ``order``, the highest Taylor coefficient of the +observables, ``points``, the number of random points of the count in the domain, ``memory``, the +address space of one call of msolve, ``experiments``, the count of several experiments, and the +work limits ``msolve_entries`` (nonzero entries of the F4 matrices of one msolve call, 4e8), +``msolve_terms`` (terms of one system given to msolve, 1e5), ``search_entries`` (entries of the +matrices over :math:`\mathbb{F}_p` the exact search reduces, 5e8) and ``elimination_terms`` (terms +of a polynomial of the elimination, 3e6). There are no time limits: a stage that reaches a work +limit ends with a result that names it. The analysis needs msolve (:doc:`../install`). + +Linear compartment models are the classical case of structural identifiability +:cite:p:`Bellman1970`. A two-compartment model with an input :math:`u` into the first compartment, +observed in the second: + +.. code-block:: 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"]) + res = si.detect(m, mode="global") + print(res) + +.. code-block:: text + + 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 + +The map exchanges the elimination rate :math:`k_{01}` and the return rate :math:`k_{12}` and +moves the initial value of :math:`x_1`, so the model is locally but not globally identifiable. +The count of two is proven: the fiber at a generic point is the orbit of the exact map. The image +lies in the domain where the image of :math:`x_1(0)` is positive, so a random point of the +domain has one or two values in it. The fundamental domain keeps one point of each orbit; +``reduce()`` lists it in ``Reduction.discrete``. + +.. code-block:: python + + s, = res.discrete_symmetries + s["map"], s["level"], s["fixed_set"] + res.info["discrete"]["certificate"]["complete"] + +.. code-block:: text + + ({'k01': 'k12', 'x1': '(k01*x2 - k12*x2 + k21*x1)/k21', 'k12': 'k01'}, 'exact', ['k01 - k12']) + 'exact' + +The result +---------- + +``res.discrete_symmetries`` lists the maps :math:`\sigma`, each a dict with + +``map``, ``changes`` + the images of the coordinates that :math:`\sigma` moves; +``level`` + ``exact``, proven by a map of the states (``state_maps``) over :math:`\mathbb{Q}`, or + ``checked``, the output coefficients agree at random points; +``found_by`` + ``candidates`` (permutations of coordinates with the same dependence of the output) or + ``fiber`` (reconstructed from the points of the fiber); +``preserves_domain``, ``domain_conditions`` + True, False, or None with the conditions under which :math:`\sigma(\theta)` lies in the + domain; a map that never meets the domain, such as :math:`\theta \mapsto -\theta` where only + :math:`\theta^2` enters, is no symmetry of the model on the domain; +``fixed_set`` + the factors on which :math:`\sigma` fixes :math:`\theta`. + +``res.info["discrete"]`` holds the count: + +``count``, ``count_bound`` + the points of the fiber over the algebraic closure at a random point modulo a prime, and the + probability that a generic point has more (None where the count is exact or has no bound); +``counts``, ``count_domain`` + per random point of the domain the points over the complex numbers, over the reals and in the + domain; the number in the domain can differ between regions. ``count_domain`` is the number at + a generic point of the domain where the count is final and each map keeps the domain or leaves + it entirely; +``count_final`` + every point of the count is the image of a proven map; +``fundamental_domain`` + inequalities that keep one point of each orbit; +``certificate`` + what the count rests on, summed up in ``complete``; +``reduced``, ``rewrites``, ``relaxed``, ``start_powers``, ``experiments`` + the reduction the analysis ran on, and the rewrites into rational form; +``eliminated`` + for a result detected with ``reduce_cq``, the species solved through the conserved totals: the + count is on the level sets of the totals, which are coordinates or set by the ``trafo``; +``limits`` + the work limits and premises that stopped or qualify part of the analysis. + +The certificate +--------------- + +``complete`` takes one of five values: + +``"exact"`` + the fiber at a generic point is the orbit of the exact maps, proven over :math:`\mathbb{Q}` + without random points; ``certificate["exact"]`` lists the functions of the coordinates shown to + be rational in the output coefficients. +``"verified"`` + a count over :math:`\mathbb{Q}` at a random integer point equals the orbit; ``count_bound`` + is the probability that a generic point has more points, ``count_bits`` and ``bezout`` the + numbers it rests on. +``"axiom"`` + the count holds under the named axiom that the count modulo a prime at a random point is the + count at a generic point, or under a premise in ``certificate["premise"]``; + ``count_bound_why`` says why no bound applies. +``"no"`` + the count exceeds the orbit of the exact maps: there are further values whose maps are not + proven. +``"open"`` + no count or no orbit was reached. + +Unsupported models and open results +----------------------------------- + +A model that the global analysis does not handle gets the reason in +``info["discrete"]["unsupported"]`` and a warning; the local result stays valid. Typical reasons: + +- a direction that the reduction does not remove, so the reduced model keeps a continuous + symmetry; +- unknown inputs together with events, switches or more than one condition; +- switches together with events, under ``equilibrate`` or on the parameters alone, and root + events; +- under ``equilibrate``, a resting state without one rational closed form in the coordinates, or + resting balances of a Bezout number past 4 or with more than 8 states coupled; +- a term the rewrites do not bring into rational form, such as a root of a state. + +A result is ``open`` or ``axiom`` where the count over the algebraic closure or over +:math:`\mathbb{Q}` exceeds the work limits of msolve, where the maps are not rational functions +of the coordinates, or where the search of the exact count does not reach every coordinate. +``limits`` names the step. The counts in the domain hold at the sample points only, since the +number of points in the domain changes across the hypersurfaces where two points meet or a point +leaves the domain. ``res.solution_count()`` gives the count over the algebraic closure at one +random point, without the maps. diff --git a/docs/guide/inputs.rst b/docs/guide/inputs.rst index 0b5404d..955dd82 100644 --- a/docs/guide/inputs.rst +++ b/docs/guide/inputs.rst @@ -52,7 +52,14 @@ As an example we consider a readout ``x`` that follows an unmeasured stimulus `` Only the initial value of ``x`` is identifiable: ``k`` trades against the scale of ``u``, and every ``tau`` fits with ``u = (tau*x' + x)/k``. ``Symmetry.input_change`` holds the component :math:`\xi(u)` of each exact direction; the type of a direction and the reduction concern -parameters and initial values only, so ``res.reduce()`` fixes ``k = 1`` and ``tau = 1``. +parameters and initial values only, so ``res.reduce()`` fixes ``k = 1`` and ``tau = 1`` and keeps +``u`` free. The reduction proves per direction that the input absorbs it: here ``u`` is solved +from the derivative of the observable, elsewhere a lift of the parameter field to the states and +the input changes the input along the flow (:ref:`red-inputs`). The +section then gives the output of a point where the changed input stays in the domain of the +input, positive by default; near every point it does. The report lists this condition under "Unknown inputs:", and a +direction without either proof stays in the model. ``discrete()`` counts the values of the +coordinates with the jets of the inputs as further unknowns. A cubic in place of ``u``, i.e., the states ``u' = u1, u1' = u2, u2' = u3, u3' = 0`` with free initial values, makes ``tau`` identifiable: four numbers, which the output determines, replace @@ -65,15 +72,15 @@ The following rules apply to unknown inputs: - The input is analytic across an event, so a state jump can separate parameters that the input absorbs otherwise. - Under ``equilibrate`` the input is zero at rest and arbitrary from the start on. -- With switches each condition needs a separate input (:doc:`../method`). +- With switches each condition needs a separate input (:ref:`switching`). - An event or ``trafo`` entry for the input and ``engine="symbolic"`` are refused. -``info["unknown_inputs"]`` lists per input the jets (:doc:`../method`), the Lie order up to +``info["unknown_inputs"]`` lists per input the jets (:ref:`inputs`), the Lie order up to which they are exact, and whether the analysis went past it. ``reconst_control(input_jet_order=)`` sets the number of jets, which grows with the model; too short a chain makes the rank a lower bound (``info["limits"]``). A direction without a *lift*, i.e., without components on states and input as functions of states, parameters and input that -prove it (:doc:`../method`), stays ``checked``, without input change. +prove it (:ref:`proofs-over-q`), stays ``checked``, without input change. Known inputs ------------ diff --git a/docs/guide/petab.rst b/docs/guide/petab.rst index 3297929..122a256 100644 --- a/docs/guide/petab.rst +++ b/docs/guide/petab.rst @@ -2,12 +2,12 @@ PEtab problems ============== Many published models are available as `PEtab `_ problems -[Schmiester2021]_, which bundle an SBML model with conditions, observables and the estimated +:cite:p:`Schmiester2021`, which bundle an SBML model with conditions, observables and the estimated parameters. :func:`symident.read_petab`, or :meth:`symident.Model.from_petab`, reads such a problem, format 1 or 2, into a :class:`~symident.Model`; it needs ``symident[petab]``. As an -example we take the model of [Raia2011]_ from the +example we take the model of :cite:p:`Raia2011` from the `benchmark collection `_ -[Hass2019]_: +:cite:p:`Hass2019`: .. code-block:: python @@ -45,6 +45,11 @@ The mapping is documented in :func:`~symident.read_petab` and recorded in ``m.pe - each experiment with measurements is one condition. A preequilibration sets ``equilibrate``; it has to be part of every experiment or of none, since symident starts all conditions alike. With conserved totals in a preequilibrated network, ``reduce_cq`` is set; +- an experiment without preequilibration whose measurements are all at time ``inf`` is a + readout at rest: the system starts from the values of the condition, rests under it, and + only the resting values of the observables enter. This assumes that a resting state exists + and is the one the experiment reaches. ``m.petab["at_rest"]`` lists these experiments; an + experiment with a finite time keeps the trajectory; - estimated parameters on a log scale or with a positive lower bound form ``Model.positive``, the default of ``detect(positive=)``; - the noise model does not enter; @@ -52,17 +57,3 @@ The mapping is documented in :func:`~symident.read_petab` and recorded in ``m.pe renamed; - an SBML or PEtab feature without counterpart, such as an algebraic rule, a delay or a fast reaction, raises :class:`~symident.PEtabError`. - -.. [Hass2019] H. Hass, C. Loos, E. Raimúndez-Álvarez, J. Timmer, J. Hasenauer and C. Kreutz. - Benchmark problems for dynamic modeling of intracellular processes. *Bioinformatics* - 35(17), 3073-3082, 2019. - -.. [Raia2011] V. Raia, M. Schilling, M. Böhm, B. Hahn, A. Kowarsch, A. Raue, C. Sticht, - S. Bohl, M. Saile, P. Möller, N. Gretz, J. Timmer, F. Theis, W.-D. Lehmann, P. Lichter and - U. Klingmüller. Dynamic mathematical modeling of IL13-induced signaling in Hodgkin and - primary mediastinal B-cell lymphoma allows prediction of therapeutic targets. *Cancer - Research* 71(3), 693-704, 2011. - -.. [Schmiester2021] L. Schmiester, Y. Schälte, F. T. Bergmann et al. PEtab: interoperable - specification of parameter estimation problems in systems biology. *PLOS Computational - Biology* 17(1), e1008646, 2021. diff --git a/docs/guide/reduction.rst b/docs/guide/reduction.rst index 90119fa..e1fa0c3 100644 --- a/docs/guide/reduction.rst +++ b/docs/guide/reduction.rst @@ -48,7 +48,7 @@ gives the output of the orbit. A direction that shifts some coordinates and rescales positive ones at rates that depend only on coordinates it does not move, such as an unknown offset of a measurement that also shifts other -coordinates, is a *linear flow* (:doc:`../method`, "Linear flows"). It is removed by fixing as +coordinates, is a *linear flow* (:ref:`red-linear`). It is removed by fixing as many moved coordinates as the block has directions, a coordinate that enters only the observables first: a linear one to 0, a positive one to 1. The other moved coordinates keep their names and stand for the invariants listed under ``Invariants``. @@ -97,13 +97,12 @@ Options ``zero_limits`` checks for each block whether coordinates can be set to zero in a limit, printed under ``Zero limits`` and returned in ``to_dict()["zero_compatibility"]``. -``timeout``, ``work_cap`` - the wall time in seconds (600 by default, ``math.inf`` for none) and the work per block of the - search for a section; reaching either is named in ``red.limits``. +``work_cap`` + the work per block of the search for a section; reaching it is named in ``red.limits``. ``check`` runs the detection again on the reduced model (``red.checks["loop"]``). ``branch`` - with a discrete symmetry of a detection with ``mode="global"`` (:doc:`detection`), the side of + with a discrete symmetry of a detection with ``mode="global"`` (:doc:`global`), the side of its fixed set, such as ``"k01 > k12"``, whose chart becomes the trafo: free values in the positive orthant map one to one onto that side, e.g. ``k01 = delta + k12`` with ``delta > 0``, chained with the section of the continuous symmetries. Without it every branch is listed in diff --git a/docs/guide/settings.rst b/docs/guide/settings.rst index 296c886..a1ce2cd 100644 --- a/docs/guide/settings.rst +++ b/docs/guide/settings.rst @@ -15,8 +15,6 @@ settings, with their defaults in parentheses, are: ``gap_order_cap`` the highest gap order, the number of power-series coefficients kept for the time between events after the start (8). -``timeout`` - the time limit of the reconstruction in seconds, once per detection (no limit). ``seed`` the seed of every random choice (0). diff --git a/docs/guide/switches.rst b/docs/guide/switches.rst index 571197c..8f7455b 100644 --- a/docs/guide/switches.rst +++ b/docs/guide/switches.rst @@ -56,7 +56,7 @@ A reported direction leaves the observables of every regime unchanged and keeps switching surfaces, the events and the given initial values. Every sign pattern of the switching functions is a regime, reached or not. A parameter of a regime that is never entered is therefore reported identifiable unless ``regimes`` excludes that regime. The state at a -switch is any point of the surface; :doc:`../method` states the rule and the exception of +switch is any point of the surface; :ref:`switching` states the rule and the exception of states that stay at zero (``info["zero_states"]``). Visibility @@ -121,5 +121,5 @@ A switch on time alone, such as ``time > tau``, is a surface like the others. An ``root`` resets ``var`` each time the root expression changes sign. Where the rule is not proven for every direction, the rank is a lower bound, ``info["switching"]["uncertified"]`` says why, and the printout lists the open directions as candidates -(``info["switching"]["candidates"]``), not as symmetries. :doc:`../method` lists the options +(``info["switching"]["candidates"]``), not as symmetries. :ref:`switching` lists the options and models that switches refuse. diff --git a/docs/index.rst b/docs/index.rst index bd38a78..7aaafc2 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -11,9 +11,10 @@ symident :doc:`quickstart` one model from detection to reduction. :doc:`guide` - models and expressions, detection, reduction, PEtab, inputs, switches, settings. + models and expressions, detection, reduction, global analysis, PEtab, inputs, switches, + settings. :doc:`method` - the mathematics, the levels of a result, references. + the mathematics: local analysis, proofs, reduction, global analysis, conditions and inputs. :doc:`api` every exported function, class and switch. :doc:`changelog` diff --git a/docs/install.rst b/docs/install.rst index f04b54c..a650649 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -6,7 +6,8 @@ Installation pip install symident Wheels exist for Linux (x86_64, aarch64, glibc 2.28 or newer; tested on Debian and -Fedora), macOS (arm64) and Windows (x86_64), Python 3.10 to 3.15. Elsewhere, such as on +Fedora), macOS (arm64) and Windows (x86_64), Python 3.10 to 3.15. They depend on NumPy, SciPy, +SymPy and python-flint, which pip installs with them. Elsewhere, such as on Intel Macs, pip builds from source with a C++17 compiler and CMake; with OpenMP the kernel runs on several threads. Development version: ``pip install git+https://github.com/dModverse/symident``. @@ -23,8 +24,8 @@ PEtab support The msolve solver ----------------- -`msolve `_ serves :meth:`~symident.Symmetries.discrete`, -:meth:`~symident.Symmetries.solution_count` and +`msolve `_ serves the global analysis (``detect(mode="global")``, +:meth:`~symident.Symmetries.discrete`), :meth:`~symident.Symmetries.solution_count` and steady-state analyses (``equilibrate=True``) whose resting states need a coupled nonlinear polynomial solve. Without it these stop with :class:`~symident.sym.msolve.MsolveMissingError`; all other analyses run without it. On Linux and macOS diff --git a/docs/method.rst b/docs/method.rst index 9fffd99..71cfa1f 100644 --- a/docs/method.rst +++ b/docs/method.rst @@ -1,11 +1,22 @@ Method ====== -This page states the mathematics behind symident: the notion of identifiability it decides, -how the rank of the observability-identifiability matrix is computed and when its order is -sufficient, how non-identifiable directions are obtained in closed form and proven, which -statements rest on random points and with which error probability, and how a model is reduced -to identifiable parameters. A small model serves as example throughout the first part. +The method chapters state the mathematics behind symident: the notion of identifiability it +decides, how the rank of the observability-identifiability matrix is computed and when the order +is sufficient, how non-identifiable directions are obtained in closed form and proven, how a model +is reduced to identifiable parameters, and how the parameter values with the same output are +counted. Every statement that rests on random points comes with an error probability or is named +in the result. + +.. toctree:: + :maxdepth: 1 + + method/local + method/proofs + method/reduction + method/global + method/conditions + method/references Notation and terms ------------------ @@ -15,7 +26,7 @@ Notation and terms .. math:: :label: eq-model - \dot x = f(x, u, \eta), \qquad x(t_0) = x_0(\eta), \qquad y = h(x, \eta), + \dot x = f(x, u, \eta), \qquad x(t_0) = x_0(\eta), with states :math:`x \in \mathbb{R}^{n_x}`, parameters :math:`\eta`, start time :math:`t_0`, inputs :math:`u = u(t, \eta)`, i.e., given functions of time such as a dose set by an event, @@ -28,19 +39,19 @@ solution, .. math:: - y(t; \theta) = h\big(x(t), \eta(\theta)\big), + g(t; \theta) = h\big(x(t), \eta(\theta)\big), -form the *prediction*. Right-hand sides, initial values and observables are rational -functions, or they are made rational by auxiliary states (see `Non-rational terms`_). A +form the *output*. Right-hand sides, initial values and observables are rational +functions, or they are made rational by auxiliary states (see :ref:`non-rational`). A *direction* at :math:`\theta` is a vector :math:`\xi \in \mathbb{R}^d` of rates of change of the coordinates. **Extended state.** Adding parameters and time to the states, :math:`z = (x, \eta, t)` with :math:`\dot\eta = 0` and :math:`\dot t = 1`, makes the model the autonomous vector field -:math:`F = f\, \partial_x + \partial_t` [Tunali1987]_. :math:`F(\varphi)` is the rate of +:math:`F = f\, \partial_x + \partial_t` :cite:p:`Tunali1987`. :math:`F(\varphi)` is the rate of change of a function :math:`\varphi(z)` along a solution, and the *start* is :math:`z_0(\theta) = (x_0(\theta), \eta(\theta), t_0)`. A set :math:`S` of points :math:`z` is -*invariant* under :math:`F` when :math:`F` is tangent to it at each of its points, so that a +*invariant* under :math:`F` when :math:`F` is tangent to :math:`S` at each point of :math:`S`, so that a solution that starts in :math:`S` stays in :math:`S`. **Conditions and events.** A *condition* is one experiment; conditions share :math:`\theta` @@ -51,58 +62,55 @@ instantaneously at a given time and splits a condition into *segments*. *irreducible* when it is not the union of two smaller varieties. A statement holds for *generic* points of an irreducible variety :math:`V` when it holds outside a proper subvariety of :math:`V`; on :math:`\Theta` the exceptions have measure zero. The *generic rank* of a -matrix of rational functions on :math:`V` is its rank at generic points of :math:`V`, which is -its largest rank on :math:`V`. The *degree* of a polynomial is its total degree, that of a +matrix of rational functions on :math:`V` is the rank at generic points of :math:`V`, which is +the largest rank on :math:`V`. The *degree* of a polynomial is the total degree, that of a vector of rational functions the largest degree of the numerators and of the common -denominator; to *clear* an expression is to multiply it by its denominator. The degree -:math:`\deg V` of a variety of dimension :math:`m` is the number of its points on a generic +denominator; to *clear* an expression is to multiply it by the denominator. The degree +:math:`\deg V` of a variety of dimension :math:`m` is the number of points of :math:`V` on a generic affine subspace of complementary dimension. **Primes.** Ranks are computed over finite fields :math:`\mathbb{F}_p`. The four *engine primes* :math:`p_1, \dots, p_4`, close to :math:`1.5 \cdot 10^9`, are fixed. The *verification prime* :math:`p`, a prime below :math:`1.4 \cdot 10^9` distinct from them, is drawn from the seed of each detection. A point *uniform modulo* :math:`p` has independent coordinates, each -uniform in :math:`\{0, \dots, p - 1\}`, drawn from a seed of its own. The *base point* +uniform in :math:`\{0, \dots, p - 1\}`, drawn from a separate seed. The *base point* :math:`\theta_b` has the coordinates 2, 3, 5, ..., the first primes. **Closed forms.** A *closed form* of a direction gives each component :math:`\xi_i` as a -rational expression of the coordinates. Its *level* (``exact``, ``verified``, ``checked``, -``open``) says how far it is established (`Levels and rank status`_), and its *route* how it -was obtained (`General directions`_). +rational expression of the coordinates. The *level* (``exact``, ``verified``, ``checked``, +``open``) says how far it is established (:ref:`levels`), and the *route* how it +was obtained (:ref:`general-directions`). -As example we consider two compartments, a substance :math:`A` that is converted into +The example is two compartments, a substance :math:`A` that is converted into :math:`B` with rate :math:`k_1`, a loss of :math:`B` with rate :math:`k_2`, and an observation of :math:`B` up to an unknown scale :math:`s`, .. math:: :label: eq-example - \dot A = -k_1 A, \qquad \dot B = k_1 A - k_2 B, \qquad y = s\, B, + \dot A = -k_1 A, \qquad \dot B = k_1 A - k_2 B, \qquad h = s\, B, with free initial values :math:`A_0` and :math:`B_0`, so that :math:`\theta = (k_1, k_2, s, A_0, B_0)` and :math:`d = 5`. -Theoretical background ----------------------- - Structural identifiability and Lie symmetries -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +--------------------------------------------- The model is *locally structurally identifiable* at :math:`\theta` if no nearby -:math:`\tilde\theta \ne \theta` has the same prediction. *Structural* means that the question +:math:`\tilde\theta \ne \theta` has the same output. *Structural* means that the question is decided by the equations alone, as if the observables were known exactly and continuously, and for generic :math:`\theta`. -A continuous family of coordinate values with the same prediction is the orbit of a *Lie +A continuous family of coordinate values with the same output is the orbit of a *Lie symmetry*, a local one-parameter group :math:`\Phi_\lambda` of transformations of :math:`\Theta` with .. math:: :label: eq-symmetry - y\big(t; \Phi_\lambda(\theta)\big) = y(t; \theta) + g\big(t; \Phi_\lambda(\theta)\big) = g(t; \theta) -[Yates2009]_ [Merkt2015]_ [Massonis2020]_. The group is described by its *generator*, the +:cite:p:`Yates2009,Merkt2015,Massonis2020`. The group is described by the *generator*, the vector field .. math:: @@ -115,1584 +123,14 @@ whose value :math:`\xi(\theta)` at :math:`\theta` is a direction. The integral c :math:`X` through :math:`\theta` is the *orbit* :math:`\mathcal{O}(\theta)`. The coordinates with :math:`\xi_i \not\equiv 0` form the *support* of the generator. A function :math:`I(\theta)` with :math:`X(I) = 0` is an *invariant* of :math:`X`; it is constant on orbits, and the -prediction depends on :math:`\theta` only through invariants. With :math:`r` generators whose +output depends on :math:`\theta` only through invariants. With :math:`r` generators whose values are linearly independent at generic :math:`\theta`, :math:`d - r` functionally independent combinations of the coordinates are *identifiable*. In Equation :eq:`eq-example`, -multiplying both initial values by a factor and dividing :math:`s` by it leaves :math:`y` +multiplying both initial values by a factor and dividing :math:`s` by it leaves :math:`g` unchanged; the generator is .. math:: X = A_0\, \partial_{A_0} + B_0\, \partial_{B_0} - s\, \partial_s, -and :math:`k_1`, :math:`k_2`, :math:`s A_0` and :math:`s B_0` are its invariants. - -Lie derivatives and the observability-identifiability matrix -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The *Lie derivatives* of the output are - -.. math:: - :label: eq-lie - - L_F^0 h = h, \qquad L_F^{k+1} h = F\big(L_F^k h\big). - -For analytic models they determine the prediction: near :math:`t_0` it is the Lie series - -.. math:: - :label: eq-lie-series - - y(t; \theta) = \sum_{k \ge 0} \frac{(t - t_0)^k}{k!}\, L_F^k h\big(z_0(\theta)\big), - -and elsewhere its analytic continuation, so equal Lie derivatives at :math:`t_0` give equal -predictions [Pohjanpalo1978]_. We collect the Lie derivatives up to the *Lie order* :math:`N` -and differentiate them with respect to :math:`\theta`, - -.. math:: - :label: eq-oim - - \Psi_N(\theta) = \big(h, L_F^1 h, \dots, L_F^N h\big)\big(z_0(\theta)\big), \qquad - \mathrm{OIM}_N(\theta) = \frac{\partial \Psi_N}{\partial \theta}, - -which gives the *observability-identifiability matrix* (OIM) [Villaverde2016]_. Its *rows of -order* :math:`k` are the gradients :math:`\partial_\theta\, L_F^k h_i(z_0(\theta))`, -:math:`i = 1, \dots, n_y`. A generator leaves :math:`\Psi_N` unchanged, so its value lies in -:math:`\ker \mathrm{OIM}_N(\theta)` for every :math:`N`. Conversely, where the rank of -:math:`\mathrm{OIM}_N` is its largest over all orders and all :math:`\theta`, which holds for -generic :math:`\theta`, every vector of the kernel is the value of a generator: the kernels -have constant dimension there, so a smooth vector field with values in them extends any -kernel vector, and along its flow every Lie derivative, and by Equation :eq:`eq-lie-series` -the prediction, stays constant. The model is therefore locally structurally identifiable when -:math:`\mathrm{OIM}_N` has rank :math:`d` for some :math:`N`, and the *non-identifiable -directions* are the vectors of the kernel. - -For the example of Equation :eq:`eq-example` the first Lie derivatives are - -.. math:: - - L_F^0 h = s B, \qquad L_F^1 h = s\,(k_1 A - k_2 B), \qquad - L_F^2 h = s\,\big(k_2^2 B - k_1 (k_1 + k_2) A\big), - -evaluated at :math:`(A, B) = (A_0, B_0)`. The rows of :math:`\mathrm{OIM}_N` reach rank four, -and the kernel is spanned by the value of the generator above. - -Sufficient Lie order -~~~~~~~~~~~~~~~~~~~~ - -The Lie order :math:`N` has to stop, and a rank that stays constant for a few orders is not -final at a special start, such as an initial value fixed to a number, a resting state or the -state after a dose. For :math:`\dot x = \theta`, :math:`y = x^m` and :math:`x_0 = 0`, every -row below order :math:`m` vanishes, and only the row of order :math:`m` shows that -:math:`\theta` is identifiable. symident therefore stops at a proven upper bound of the rank, -the *ceiling* below [HermannKrener1977]_. - -Let :math:`D_k` be the matrix of the gradients :math:`\partial_z L_F^j h_i`, :math:`j \le k`, -:math:`i \le n_y`, and :math:`S` an irreducible variety of points :math:`z` that is invariant -under :math:`F`. By the chain rule, -:math:`\mathrm{OIM}_k(\theta) = D_k\big(z_0(\theta)\big)\, \partial_\theta z_0(\theta)`. - -**Lemma.** At a generic point of :math:`S`, once :math:`\operatorname{rank} D_{k+1} = -\operatorname{rank} D_k` for one :math:`k`, the rank stays the same for every later order. - -*Proof.* Let :math:`\Omega_k` be the span of the rows of :math:`D_k` over the rational -functions on :math:`S`. A row is a one-form :math:`\omega = \sum_i \omega_i\, \mathrm{d}z_i`, -and its Lie derivative along :math:`F` is -:math:`(\mathcal{L}_F \omega)_i = \sum_j F_j\, \partial_{z_j} \omega_i + \sum_j \omega_j\, -\partial_{z_i} F_j`. It is additive, satisfies :math:`\mathcal{L}_F(a\, \omega) = F(a)\, \omega -+ a\, \mathcal{L}_F \omega` for functions :math:`a`, and by the chain rule -:math:`\mathcal{L}_F\, \partial_z \varphi = \partial_z F(\varphi)`, so it maps the row of -:math:`L_F^j h_i` to that of :math:`L_F^{j+1} h_i`. Hence - -.. math:: - :label: eq-filtration - - \mathcal{L}_F \sum_{j \le k} a_j\, \partial_z L_F^j h_i - = \sum_{j \le k} F(a_j)\, \partial_z L_F^j h_i + \sum_{j \le k} a_j\, \partial_z L_F^{j+1} h_i . - -If :math:`\Omega_{k+1} = \Omega_k`, the right-hand side lies in :math:`\Omega_k` for every -element of :math:`\Omega_k`, so :math:`\Omega_k` is invariant under :math:`\mathcal{L}_F` and -contains every later row. :math:`\square` - -Let :math:`\rho_S`, the *ceiling*, be this final rank at a generic point of :math:`S`. - -**Proposition.** Let :math:`S` contain the start :math:`z_0(\theta)` of every -:math:`\theta \in \Theta`. If at one start :math:`z_0(\theta^\ast)` the rank of :math:`D_N` -equals :math:`\rho_S`, then :math:`\ker \mathrm{OIM}_k(\theta) = \ker \mathrm{OIM}_N(\theta)` -for all :math:`k \ge N`, both at :math:`\theta^\ast` and at generic :math:`\theta`. - -*Proof.* By the lemma no :math:`D_k` exceeds rank :math:`\rho_S` on :math:`S`, so every minor -of size :math:`\rho_S + 1` vanishes on :math:`S`, and :math:`\operatorname{rank} D_k \le -\rho_S` at every point of :math:`S`. The rank of :math:`D_N(z_0(\theta))` is the rank of a -matrix rational in :math:`\theta`, so at generic :math:`\theta` it is at least its value at -:math:`\theta^\ast`, hence equal to :math:`\rho_S`. Wherever it equals :math:`\rho_S`, the row -spaces of :math:`D_k(z_0(\theta))`, :math:`k \ge N`, contain that of :math:`D_N` and have -dimension at most :math:`\rho_S`, so they coincide, and so do the kernels after multiplication -by :math:`\partial_\theta z_0`. :math:`\square` - -The proposition is what the checks of closed forms need: they run at random coordinate values, -at the order certified at one start. A *resting point* :math:`z_*` is one with -:math:`f(z_*) = 0`; for an autonomous model, where :math:`t` is dropped from :math:`z`, -:math:`F(z_*) = 0` there, and the rows form a *Krylov sequence*, each the previous one times -the same matrix, - -.. math:: - :label: eq-krylov - - \partial_z L_F^{k+1} h(z_*) = \partial_z L_F^k h(z_*)\; \partial_z F(z_*), - -so there one order without change of rank is final at the point itself. - -**The set** :math:`S`. Without ``equilibrate``, :math:`S` consists of the starts shifted by a -subspace :math:`U` of the states, -:math:`S = \{z_0(\theta) + (b, 0, 0) : \theta \in \Theta,\ b \in U\}`, with :math:`U` the -smallest subspace for which :math:`F` stays in :math:`U \times \{0\} \times \mathbb{R}` on -:math:`S`. It is built from :math:`U = \{0\}` by adding the state part of :math:`F` at a random -point of the current :math:`S` until that part lies in :math:`U`. This covers a start at rest, -a subsystem at rest, states that stay at zero, fixed initial values, and linear relations the -dynamics keeps. Under ``equilibrate`` every start is a resting point, and :math:`S` is the -resting variety of the condition (`Steady states`_), on which :math:`f = 0`; its generic point -is a random coordinate value with the resting state solved there (the first of 24 draws with a -root). In both cases the rank at the start is taken at the base point. Where the start does -not reach :math:`\rho_S`, e.g., on the level set of a nonlinear conserved quantity, no order -is proven sufficient. The order then stops after a *plateau*, three orders without change of -rank (``SYMIDENT_LIEPLATEAU``), and the result says that the Lie order is not proven -sufficient. - -**Conditions and events.** The rows of several conditions are stacked, and their row space -stops changing once that of every condition has stopped, so every condition is expanded to -its own order. An event moves the start of the next segment: a state replaced by a value of -the coordinates is removed from :math:`U`, a value added keeps :math:`U`, and an event that -multiplies a state or reads the states adds that state's direction to :math:`U`. The -proposition extends to the power series of `Conditions and events`_ and is checked at a -vanishing gap. - -**Random points.** :math:`U` and :math:`\rho_S` are taken at points uniform modulo the -verification prime :math:`p`. They are wrong only where a polynomial vanishes: the state part -of :math:`F` at the step that ends :math:`U`, or a minor of size :math:`\rho_S` of the rows of -an order, both composed with the start, whose degree :math:`\deg z_0` multiplies theirs, and -on a resting variety times the Bezout number of its balances (`Error bounds`_). Since the -generic ranks rise strictly up to their final value, orders up to the number of columns plus -one reveal a wrong plateau. The degrees are those of the rational system the modular engine -evaluates, with exponentials, free powers and trigonometric functions as separate states. A -point is the first of its draws without a pole of the starts, up to 8, or on a resting variety -the first with a root, up to 24. It is wrong only if one of the points drawn is, so each term is -multiplied by the number of points drawn for its point, and the terms add up to the order bound -of `Error bounds`_. - -**Without a stopping rule.** A direction that is an exact symmetry, i.e., a scaling under -which every expression is homogeneous (`Scalings`_) or a field with the identities of -`Proofs over Q`_, lies in the kernel at every order, so a rank that together with such -independent directions gives :math:`d` is proven for all orders. ``engine="symbolic"`` computes -the Lie derivatives over the rational functions and confirms the order by an exact rank: -where the rows at the initial values reach the generic rank, a nonvanishing minor makes every -later row a combination of earlier ones. Where no order is proven sufficient, a *saturation -guard* (``verify=True``) takes the rank at the base point again six orders further -(``SYMIDENT_VERIFY_MARGIN``) and the gap order of `Conditions and events`_ two orders further. -If the rank grows, the detection is repeated from that order, up to three times; if it still -grows, the rank is a lower bound, ``info["verification"]`` says where, and a reduction is -refused. - -Computation ------------ - -Ranks over finite fields -~~~~~~~~~~~~~~~~~~~~~~~~ - -symident evaluates :math:`\mathrm{OIM}_N` exactly over :math:`\mathbb{F}_p` in a compiled -*modular engine*: the Lie derivatives as power series in time truncated at order :math:`N`, -the derivatives with respect to :math:`\theta` as dual numbers, all rows at a point in one pass -[Sedoglavic2002]_. A point can only underestimate the generic rank, and a random point does so -with small probability [Schwartz1980]_ [Zippel1979]_. The rank of the result is taken at the -base point, as the largest over the four engine primes. Randomness enters through the points -uniform modulo the verification prime: one point that checks the rank of the *saturation*, -i.e., of the order chosen, and the points that check closed forms. - -Conditions and events -~~~~~~~~~~~~~~~~~~~~~ - -The rows of the conditions :math:`c = 1, \dots, C` are stacked over the shared coordinates, so -that :math:`\ker \mathrm{OIM} = \bigcap_c \ker \mathrm{OIM}^{(c)}`. - -A segment starts from the end of the previous one, propagated over the *gap* -:math:`\Delta t_i` between the events. To separate directions that exist only for particular -event timings from generic ones, the gaps are placed on the line -:math:`\Delta t_i = \varepsilon\, \Delta t_i^{0}` through the actual gaps :math:`\Delta -t_i^{0}`, and the rank is taken over the Laurent series :math:`\mathbb{F}_p((\varepsilon))` in -the formal variable :math:`\varepsilon`. The kernel at :math:`\varepsilon = 1` is read from -Padé forms, i.e., rational functions of :math:`\varepsilon` matching the series of each kernel -entry, that further coefficients confirm; this acceptance is heuristic and gives a basis of the -kernel only. - -The rows after a gap are power series in :math:`\varepsilon` whose coefficients belong to a -family of functions fixed by the model. Their rank, at points uniform modulo :math:`p`, -therefore gives an upper bound of the rank over the series, with error terms that enter the -order bound. The *gap order* :math:`M`, the number of coefficients kept, rises until the -truncated rank reaches this bound, which proves :math:`M` sufficient; a truncated rank above -the bound refutes it, and nothing is certified. A symbolic event time gives no bound, since it -moves the boundary and shifts the series and the event state outside the family. Without bound -(``equilibrate``, recast terms, such an event time) or at ``reconst_control(gap_order_cap=)``, -the rank is a lower bound, and ``info["limits"]`` says where :math:`M` stopped. - -Steady states -~~~~~~~~~~~~~ - -With ``equilibrate=True`` every condition starts at rest: its initial value is a *resting -state* :math:`x^\ast(\theta)` with :math:`f(x^\ast, 0, \eta) = 0`, inputs at zero. The -*balances* of a condition are the components of :math:`f` cleared to polynomials, and its -*resting variety* :math:`W` is the closure of :math:`\{(\theta, x) : f(x, 0, \eta(\theta)) = -0\}`. No closed form of the resting state is needed: at each point the balances are solved over -:math:`\mathbb{F}_p`, by linear elimination, by resultants for coupled subsystems of one or two -states, or by msolve [Berthomieu2021]_. Only msolve excludes states at zero, by a Rabinowitsch -variable :math:`\tau` with :math:`\tau \prod_i x_i = 1`, and a resting state solved modulo one -prime is not resampled at another. The kernel is taken in coordinates and resting states -jointly, with the tangency of a direction :math:`(\xi_\theta, \xi_x)` to :math:`W` as extra -rows rather than through the implicit function theorem. Let :math:`N` be the states that are -neither the pivot of a conserved total (below), nor an input, nor at zero at rest, and -:math:`f_N` their balances. The tangency rows are - -.. math:: - - J_x\, \xi_{x_N} + J_\theta\, \xi_\theta = 0, \qquad J_x = \partial_{x_N} f_N, \quad - J_\theta = \partial_\theta f_N, - -where the columns of :math:`\partial_x f` at the pivots are columns of :math:`J_\theta`, since -the resting value of a pivot is a coordinate; inputs and states at zero enter as rows that hold -them at zero. One balance per total is dropped, that of the pivot. This is exact: each total -:math:`\sum_i a_i x_i` gives :math:`\sum_i a_i f_i = 0`, and the coefficient matrix -:math:`C_P` of the totals at the pivots is invertible, so :math:`f_P = -C_P^{-1} C_N f_N` -vanishes wherever :math:`f_N` does. The full :math:`\partial_x f` is singular with a total, the -reduced :math:`J_x` is square; it is the *resting Jacobian*. A proven rank also needs the -resting Jacobian of every condition solved at the point itself invertible at the base point; -otherwise the rank is a lower bound. - -**Branches.** A *branch* is an irreducible component of :math:`W` over :math:`\mathbb{Q}`. By -default the first condition draws the resting states and solves the balances for the -*turnover rates*, one rate per state that enters its balance linearly (the *forward seed*); -this names the component that the drawn values parametrize. Where a balance has several roots -over :math:`\mathbb{F}_p`, the first nonzero one found is taken and named in -``info["branches"]``: by the factor over :math:`\mathbb{Q}(\theta)` it solves where a balance -splits into factors, else as *conjugate*. Conjugate means that the lexicographic Gröbner basis -of the balances, states at zero removed, has at a point the *shape* -:math:`x_1 - g_1(x_n), \dots, x_{n-1} - g_{n-1}(x_n), P(x_n)` with an irreducible *eliminant* -:math:`P`. Other points take their root on that branch or, without one, are left out. -Conjugate roots have equal rank, and an eliminant irreducible at a point is irreducible over -:math:`\mathbb{Q}(\theta)`. - -**Zero at rest.** A state rests at zero when its right-hand side, with the inputs at zero, is -linear in it with a coefficient that is nonzero while the other such states are zero. In a -reaction network, a species that is consumed but not produced rests at zero as the single -reactant of a consuming reaction, as does the single reactant of positive weight in a reaction -that lowers a weight no reaction raises (a *sink*; a weight assigns each species a number in -:math:`[0, 1]`). Of several such reactants, as in :math:`A + B \to 0`, the first is set to zero -(``info["branches"]``). A state with right-hand side zero at rest, and the pivot of a conserved -total (below), has a free resting value, its initial value. Rates are read at generic values, -so a catalyst at rest is nonzero. Where the coefficient of a state of a total at zero holds -other states, as for :math:`\dot B = B\,(k_1 A - k_2)`, the resting set has a second branch -with the state away from zero, where the coefficient vanishes; ``info["branches"]`` names it, -and ``free_initial`` naming the state takes it. ``free_initial`` naming a state at zero on every -resting state is an error. - -**Conserved totals.** A linear combination :math:`T = \sum_i a_i x_i` of states that the -right-hand sides conserve is a *total*; the coefficients may hold parameters, such as volumes. -Totals are read from the stoichiometry of a reaction network or from the linear laws of the -ODEs, unless given. The basis read off consists of nonnegative laws where these span the laws, -the extreme rays of the cone of nonnegative laws with the fewest species first, so that it does -not depend on the order of the species and each total is positive on the parameter space; a -total with coefficients of both signs is named in ``info["limits"]`` under ``reduce_cq``, which -takes it positive. - -Under ``equilibrate`` each total leaves one resting value free, which one species of the total, -the *pivot*, holds as initial value. The pivots form a set :math:`P` of species, one per -independent total, with an invertible coefficient matrix :math:`C_P`. ``free_initial`` names -them; otherwise they are chosen by the structure of the model, in this order: not at zero at -rest, not an input and not the base of a free power, a coefficient without parameters, in the -fewest totals, observed. Where several sets tie by these criteria, up to six are analyzed and the -result with the best rank status, rank, levels and kinds is kept, so that the result does not -depend on the names or the order of the states and totals. With another pivot the resting -value of another state is the coordinate, so the generators differ, but their spans agree after -the map to the parameters and all resting states at a common resting point. Where directions -stay open, other valid sets are tried as well. ``info["settings"]["free_initial"]`` holds the -pivots of the result. - -With ``reduce_cq`` the pivots are eliminated instead, :math:`x_P = C_P^{-1} (T - C_N x_N)`, and -the values :math:`T` of the totals become coordinates (``info["settings"]["eliminated"]``); the -pivots are chosen as above, except that unobserved species are eliminated first. An event that changes -a species :math:`x_i` of a total changes the total by :math:`a_i\,(E(x_i) - x_i)`, with -:math:`E(x_i)` the value after the event; like every event value it reads the states before the -events. The total is then a state without dynamics, so the segments after the event see the new -total, and an event on an eliminated species changes only the totals. Both parametrizations -describe the same resting variety, so ``reduce_cq`` gives the same rank and the same span of the -directions, mapped to the same space, as the pivots. - -**Rank at the resting start.** Under ``equilibrate`` the rank is that at the declared resting -start, whose coordinates fix the level set of each total. The ceiling of the order certificate -(`Sufficient Lie order`_) is the generic rank on the whole resting variety, so the computed rank -cannot exceed the rank along the trajectories from the declared start; it can only fall short of -it, and is then reported as a lower bound (a singular resting Jacobian, an order not proven -sufficient) or covered by the error bound (a random point). The exact scalings bound the rank -from above, so a rank at that bound proves the order sufficient without random points, with -``info["order_bound"]`` zero. - -**Diagonal start.** Conditions sharing :math:`\theta` have coupled resting states. Rank and -kernel are generic on the joint variety of the conditions, -:math:`\{(\theta, x_1, \dots, x_C) : (\theta, x_c) \in W_c\}`, so any point of it over -:math:`\mathbb{F}_p((\varepsilon))` off an exceptional subvariety gives them. symident seeks a -set :math:`P_Z` of free parameters whose value zero makes all conditions equal to the first, -and the largest set :math:`X_Z` of states whose value zero is then invariant; at -:math:`\theta_{P_Z} = 0`, :math:`x_{X_Z} = 0` the forward seed is a resting point -:math:`\hat z` of all conditions. Along :math:`\theta(\varepsilon) = \hat\theta + \varepsilon\, -\zeta`, with :math:`\zeta` the values of :math:`P_Z` at the sample point, Newton steps lift each -condition to a power series, - -.. math:: - - x_{c,k} = -J_c(\hat z)^{-1}\, [\varepsilon^k]\, f_c\big(x_{c, 0`, -:math:`j = 1, \dots, n_\gamma`. The *declared signs* are the domain declared by ``positive`` -and the start sides declared by ``regimes``. Conditions that the declared signs decide are -resolved; a factor of odd multiplicity of an undecided one is a *switching function* -:math:`\gamma_j`, with *switching surface* :math:`\Gamma_j = \{\gamma_j = 0\}`. A sign vector -:math:`\sigma \in \{+1, -1\}^{n_\gamma}` gives a smooth *regime* :math:`(F_\sigma, h_\sigma)`, -the field and the observables where every :math:`\gamma_j` has the sign :math:`\sigma_j`. A -*root event* (``root`` in place of ``time``) adds its root expression as a switching function -and resets its target state, the *event state*, on :math:`\Gamma_j`. - -**Regimes.** A direction counts only if it is a symmetry of every regime the declared signs -allow. Without ``regimes``, every sign vector counts unless the declared positivity decides -the sign of :math:`\gamma_a - \gamma_b` or :math:`\gamma_a + \gamma_b` against it; none is -dropped for parameter values or for not being reached, so the result holds for every initial -state. A parameter that acts only in a regime excluded by a decided condition stays a -coordinate, with the unit direction :math:`\partial_{\theta_i}` as exact direction. Each -allowed regime enters as a *copy* of the model, i.e., the rows of that regime with initial -states of their own and the parameters shared, from the start of the condition and, with -other regimes allowed, as a copy switched into it (``info["switching"]["conditions"]``). - -**Entry points.** The state at a switch is unknown, so a direction counts only if it is a -symmetry from every point of the surface. A state that starts at zero in every condition, that -every allowed regime keeps at zero with finite derivatives in such states, and that no later -event moves, is zero along every trajectory. It is dropped (``info["zero_states"]``), and a -coordinate that only such states read is a separate direction :math:`\partial_{\theta_i}`; -``info["limits"]`` names a condition with further such states. For a copy switched into a -regime, other invariant sets of the start, such as the level set of a conserved total, are not -used, so the rank of a model with switches can exceed the rank along the trajectories from the -declared start. This concerns switches only; under ``equilibrate`` without switches the rank -cannot exceed it (`Steady states`_). - -**Visibility.** Two regimes :math:`\sigma, \sigma'` are *neighbors* at :math:`\Gamma_j` when -they differ only in the sign of :math:`\gamma_j`. The switch is *visible* when for some -neighbors, observable :math:`h_i` and order :math:`k` - -.. math:: - - \big(L_{F_\sigma}^k h_{\sigma,i} - L_{F_{\sigma'}}^k h_{\sigma',i}\big)\big|_{\Gamma_j} - \ne 0 . - -A nonzero Taylor coefficient at a point of :math:`\Gamma_j`, modulo a prime, proves this. The -switch is *invisible*, or *hidden*, when for every pair the observables agree and every state -reaching them has the same right-hand side, so that every Lie derivative agrees, and -*undecided* otherwise. A root event surface counts as visible. - -**The rule.** Let :math:`\tau_e` be the time and :math:`E_e` the map of the states of event -:math:`e`. A direction :math:`v` is reported non-identifiable when, in every condition, it lies -at the start in a distribution :math:`\mathcal{D} = \operatorname{span}\{Y_1, \dots, Y_m\}` of -fields on parameters and states with - -.. math:: - - [Y_i, F_\sigma] \in \mathcal{D}, \qquad Y_i(h_\sigma) = 0 \qquad - \text{for every regime } \sigma, - -.. math:: - - Y_i(\gamma_j) = 0 \ \text{on } \Gamma_j \ \text{for every visible surface}, \qquad - Y_i(\tau_e) = 0, \qquad \mathrm{D}E_e\, Y_i(z) \in \mathcal{D}\big(E_e(z)\big) \ - \text{for every event and reset}, - -and, at a surface that is not visible and that some :math:`Y_i` moves, for every pair of -neighbors - -.. math:: - - \big(F_\sigma - F_{\sigma'}\big)\big|_{\Gamma_j} \in \mathcal{D}, \qquad - \big(h_\sigma - h_{\sigma'}\big)\big|_{\Gamma_j} = 0 . - -No :math:`Y_i` moves a fixed symbol, an input or time. The direction is -:math:`v = \big(\xi, X(x_0)\big)`, with the derivative of the initial values along :math:`X` as -state part (under ``equilibrate``, of the resting state of each regime). Along every regime -flow, :math:`v` stays in :math:`\mathcal{D}` and keeps the observables to first order; at a -visible surface :math:`v` is tangent, so the crossing time stays; at a hidden one the crossing -may move, but the jump lies in :math:`\mathcal{D}` and the observables agree. The rule therefore -never reports a direction that changes the observables, for any sequence of the listed regimes. - -**Lower bound.** The directions of the rule satisfy the rows of copies of the model, whose rank -bounds the rank from below: - -- each regime from the start of each condition, with the events of the condition; -- each regime from a generic point of each visible surface linear in a state, where a direction - of the rule is tangent to the surface; -- each regime from a generic point, when a switch of the condition is not visible; -- each copy switched at a fixed time into every other regime of the condition, with outputs - along *words* of two regimes, :math:`L_{F_\sigma}^a L_{F_{\sigma'}}^b h_{\sigma'}`; -- the switching time :math:`t_j(\theta)` of every visible switch in time alone. - -The *fresh coordinates* are the entry states of the copies that start at surface points. The -kernel of all these rows, projected onto :math:`\theta`, contains every direction of the rule; -a kernel dimension :math:`k_\Delta` gives the lower bound :math:`d - k_\Delta`. A minor that is -nonzero at the sample point is nonzero as a rational function. The projection off the fresh -coordinates, a difference of two ranks, can rise at a special point. It is proven where every -kernel direction within the fresh coordinates alone is the unit direction of a fresh coordinate -entering no row (the entry value of a state reaching no observable of the copy), which is -checked at the sample point and then with the kernel at a point uniform modulo the verification -prime, whose projection then counts. With equal dimension there and no such proof it is -``verified``, with the chance by [Schwartz1980]_ that a maximal minor of the stacked rows or of -their fresh columns vanishes there, else a lower bound (``info["projection"]``, -``info["rank_status"]``). - -**Upper bound.** The candidates are the scalings of `Scalings`_, the closed forms of the kernel -of the rows above and the unit direction :math:`\partial_{\theta_i}` of every coordinate; those -failing a condition of the rule are dropped until the family passes. Each identity is tested at -a point with rational coordinates and then proven by symbolic simplification to zero; -:math:`\ell` candidates left, independent at such a point, bound the rank by :math:`d - \ell`. -If :math:`\ell = k_\Delta`, the rank is :math:`d - k_\Delta` and the candidates span the -non-identifiable directions; otherwise :math:`d - k_\Delta` is a lower bound, -``info["switching"]["uncertified"]`` names the rejected candidates, and the unproven kernel -directions, which satisfy only necessary conditions, appear under -``info["switching"]["candidates"]``, not as symmetries. For an undecided switch the rule accepts -tangency or a hidden jump and the rows omit the surface, so both bounds stay valid. - -**Unknown inputs.** The input is continuous where a trajectory crosses a surface and analytic -between crossings; its derivatives may jump at a crossing. The input direction -:math:`G_\sigma = \partial_w F_\sigma`, over the inputs that no observable of :math:`\sigma` -reads, joins the bracket condition, - -.. math:: - - [Y_i, F_\sigma] = \sum_k c_{ik}\, Y_k + a_{i\sigma}\, G_\sigma , - -with rational functions :math:`c_{ik}` and :math:`a_{i\sigma}`, and -:math:`v = \sum_i \beta_i Y_i` changes the input in :math:`\sigma` by :math:`-\sum_i \beta_i -a_{i\sigma}`; an input that an observable reads stays unchanged. Where :math:`G_\sigma \in -\mathcal{D}` the change is free. Otherwise it must not jump where a trajectory crosses -:math:`\Gamma_j` from :math:`\sigma` into a neighbor :math:`\sigma'`: on :math:`\Gamma_j`, - -.. math:: - - a_{i\sigma'} - a_{i\sigma} - - \frac{Y_i(\gamma_j)}{F_\sigma(\gamma_j)} \sum_k e_k\, a_{k\sigma'} = 0 , - \qquad F_\sigma - F_{\sigma'} = \sum_k e_k Y_k , - -the last term counting only at a hidden surface that :math:`Y_i` moves, whose crossing then -shifts. A switch is visible only through orders :math:`k \le r_i`, with :math:`r_i` the lowest -order at which an input can enter :math:`L^k h_i`, read from the symbols of each order; higher -orders hold input derivatives. The jets of each copy are nuisance coordinates (see -`Unknown and known inputs`_), with a start of their own per copy and, at a surface point, the -input value shared by the two neighbors. A copy from a generic point of each regime replaces the -copy switched at a fixed time, which would restart the input off the surfaces, where the changes -of two regimes differ. The rank status is the weaker of the projections off the jets and off the -fresh coordinates. The rule holds per condition, so each condition needs a separate input, -renamed in ``conditions``. - -**Listed regimes.** With ``regimes``, the rule, the rows and the candidates use the listed -regimes of each condition, and a surface counts only with listed regimes on both sides. -Parameters of other regimes stay coordinates and are reported non-identifiable. A sign of -:math:`\gamma_j(x_0)` decided by the declared signs must agree with the first entry, else an -error is raised; an undecided one is declared by ``regimes`` and listed under ``declared`` in -``info["switching"]["conditions"]`` and in ``info["assumptions"]["starts"]``. - -**Limits.** Each of the following is an error, never a result: - -- a surface in the parameters alone whose side ``regimes`` does not give; -- a condition on a switched expression; -- more than 4096 sign vectors; -- ``gauge``, ``reduce_cq``, ``free_initial``, ``engine="symbolic"``; -- a state named ``time``; -- under ``equilibrate``, a resting state without closed form; -- an infeasible listed regime, or a start that contradicts the initial values; -- with unknown inputs: an input read by several conditions, a switch on an input, an event after - the start, an initial or event value that reads an input. - -Non-rational terms -~~~~~~~~~~~~~~~~~~ - -The modular engine needs rational functions. Elementary functions are therefore recast into -rational form [Savageau1987]_, type by type in a fixed order and innermost first within a type; -a nesting across that order, such as :math:`\sin(\exp x)` or :math:`\exp(\arctan x)`, is -refused. A term :math:`\nu = \varphi(\psi)` with :math:`\psi` rational in the states becomes a -new state with right-hand side :math:`\varphi'(\psi)\, \sum_j \partial_{x_j} \psi \, f_j`, -which is rational in :math:`\nu` and :math:`\psi` for - -.. math:: - - \varphi(\psi) = \psi^\alpha:\ \ \frac{\alpha\, \nu}{\psi}, \qquad - \exp(\psi):\ \ \nu, \qquad \log(\psi):\ \ \frac{1}{\psi}, \qquad - \arctan(\psi):\ \ \frac{1}{1 + \psi^2}, \qquad \operatorname{artanh}(\psi):\ \ \frac{1}{1 - - \psi^2}, - -and for :math:`\arcsin`, :math:`\arccos`, :math:`\operatorname{arsinh}` and -:math:`\operatorname{arcosh}` contains a square root, which is recast in turn. Trigonometric -functions go through :math:`\tan(\psi/2)`. A *free power* :math:`b^\mu`, with a parameter -:math:`\mu` as exponent, becomes a state :math:`B = b^\mu` with companion :math:`L_b = \log b`, -so that the field is rational and :math:`\mu` enters through :math:`\partial B / \partial \mu -= B L_b`. - -Under ``equilibrate`` a power :math:`b^\mu` of a positive rational number :math:`b` is -rewritten first: next to a power :math:`c^\mu` of a symbol -:math:`c` with the same exponent, :math:`c` stands for :math:`b c` throughout, -:math:`(b c)^\mu` being a power of one symbol, and the result is mapped back. Otherwise -:math:`b` is a constant with :math:`\log b` taken independent of the other constants, as for -logarithms of numbers in log coordinates (named in ``info["limits"]``). - -A new state starts at :math:`\varphi(\psi)` of the initial state. Where this depends on the -coordinates, a transcendental :math:`\varphi` becomes an input of the modular engine of its own, -a *leaf*, drawn independently of its argument and tied to it by relation rows -:math:`\mathrm{d}\nu = \varphi'(\psi)\, \mathrm{d}\psi`: a transcendental graph lies in no proper -variety, so a random point on it is generic. With several transcendental constants, such as -:math:`e` and :math:`\pi`, this needs their algebraic independence, which follows from -Schanuel's conjecture and is not proven. An algebraic :math:`\varphi`, a root or rational power, -is exact: through :math:`L = \log \psi` when :math:`\psi` is affine in one coordinate, else by -the root modulo the prime at each sample point, over primes in which every root of the model -exists. Logarithms, fractional powers and bases of free powers are real for a positive argument. -The rank and the kernel are taken at generic points, where every argument is nonzero, so the -detection needs no sign. An argument that the declared signs do not make positive on -:math:`\Theta`, also in initial and event values, is named in ``info["limits"]``. An observable -:math:`\kappa \sum_i a_i \log \rho_i + \beta`, with rational :math:`\rho_i` and constants -:math:`\kappa, a_i, \beta`, is strictly monotone in :math:`\prod_i \rho_i^{a_i} e^{\beta/\kappa}` -and is analyzed as that product. - -An event after the start reads the states just before it. There the state propagated across the -gaps is a power series in the gap lengths whose constant term :math:`\bar x` is the state at zero -gaps, the initial state with the earlier events of the condition applied. A transcendental -:math:`\varphi(\psi(x))` in an event value is the leaf :math:`\varphi(\bar\psi)`, -:math:`\bar\psi = \psi(\bar x)`, times or plus a series in :math:`\psi(x) - \bar\psi`, - -.. math:: - - e^{\psi} = e^{\bar\psi}\, e^{\psi - \bar\psi}, \qquad - \log \psi = \log \bar\psi + \log\Bigl(1 + \frac{\psi - \bar\psi}{\bar\psi}\Bigr), \qquad - \psi^\alpha = e^{\alpha \log \psi}, \qquad - \sin \psi = \sin \bar\psi \cos(\psi - \bar\psi) + \cos \bar\psi \sin(\psi - \bar\psi), - -and since :math:`\psi(x) - \bar\psi` has no constant term, each series ends at the truncation -order; :math:`\cos` and :math:`\tan` follow from the addition theorems. An event on a state -moves the new states of the recast with it, :math:`\nu` to -:math:`\varphi` of :math:`\psi` after the event, so a dose added to a state under a free power -moves :math:`B` and :math:`L_b`, and in log coordinates :math:`L = \log x` becomes -:math:`\log(e^{L} + d)`. Under ``equilibrate`` :math:`\bar x` is the resting state, a -coordinate, and an event at the start takes the leaves at it alone. - -**Terms of resting states.** Under ``equilibrate`` a transcendental term -:math:`\varphi(\psi(x, \theta))` of the states is a leaf :math:`W` in the balances as well, the -same leaf as the initial value of the new state :math:`\nu`. The balances are then rational in -the resting states, the coordinates and the leaves, and the relation rows -:math:`\mathrm{d}W = \varphi'(\psi)\, \mathrm{d}\psi` tie each leaf to the state columns and the -coordinates of the joint kernel (`Steady states`_). The leaves are drawn independently of the -resting states, and the resting states are solved from the balances at the drawn values. Let -:math:`M = \{(\theta, x, W) : f(x, \theta, W) = 0,\ W = \varphi(\psi(x, \theta))\}` be the -resting set and :math:`A` the component of the algebraic set :math:`\{f(x, \theta, W) = 0\}` on -which the drawn points lie. Rank and kernel are rational in :math:`(\theta, x, W)`, so their -generic values on :math:`A` are those on :math:`M` when :math:`M` is Zariski dense in -:math:`A`. This holds under two conditions. First, let :math:`H` be the states and -:math:`\theta_A` the coordinates inside the arguments :math:`\psi`. The resting values -:math:`x_H` vary independently of :math:`\theta_A`, i.e., the tangent space of the resting set -projects onto the coordinates :math:`(\theta_A, x_H)`. Then :math:`(\theta_A, x_H)` and further -coordinates form a chart of :math:`M` in which every argument is rational. Second, no nontrivial -integer combination of the arguments is constant, which the recast ensures by one leaf per -basis term, as for leaves of coordinates. The density then follows from a classical lemma, the -exponential case of the theorem of Kolchin and Ostrowski (Ostrowski 1946, Kolchin 1968; -attribution to be verified): exponentials :math:`e^{\psi_1}, \dots, e^{\psi_n}` of rational -functions :math:`\psi_i \in \mathbb{C}(z)` are algebraically independent over -:math:`\mathbb{C}(z)` if and only if no nontrivial integer combination :math:`\sum_i n_i \psi_i` -is constant. Proof of the direction used: an algebraic relation reads :math:`\sum_a c_a(z)\, -e^{\langle a, \psi \rangle} = 0` with rational :math:`c_a \neq 0` and distinct integer vectors -:math:`a`, whose exponents differ pairwise by nonconstant functions. On a generic line through -the domain this stays so, with one variable :math:`t`. Take a relation with the fewest terms, -divide by the last term and differentiate in :math:`t`. The constant term drops, and the -other terms :math:`r_j e^{h_j}` become :math:`(r_j' + r_j h_j') e^{h_j}`, a shorter relation, -so every :math:`r_j' + r_j h_j' = 0`. Then :math:`e^{h_j}` is a constant over :math:`r_j`, a -rational function, which a nonconstant rational :math:`h_j` excludes. Logarithms of -rational functions no product of integer powers of which is constant, such as distinct -irreducible factors, are algebraically independent in the same way, and a half-angle tangent -:math:`\tan(\psi/2)` is rational in :math:`e^{i\psi}`. Ax's theorem [Ax1971]_, a functional form -of Schanuel's conjecture, generalizes the lemma. The image of :math:`M` is therefore dense in -the space of the chart and the leaves, which has the dimension of :math:`A` where the resting -Jacobian is invertible, and :math:`M` is dense in :math:`A`. The first condition is checked at -the base point; where it fails, an ``InputError`` names the states. An example is -:math:`\dot x = k - x e^{x/k}`, whose resting value no coordinate outside the exponent moves. - -A state that enters the balances only through leaves, such as :math:`x` in :math:`\dot x = p - k -\sin x`, leaves the resting Jacobian singular with the leaves drawn. The resting value of such a -state is drawn, and one leaf of the state that enters the balance becomes a resting unknown, -solved from the balance; the points remain points of :math:`A`. -``info["settings"]["rest_leaves"]`` lists the resting states inside transcendental terms with -their leaves, and under ``drawn`` the states whose resting value is drawn. A leaf of a resting -state is one coordinate for all conditions, so conditions with different resting models are -refused for such a state. A root or rational power of an expression in the states in the resting -model has no leaf and is refused. - -Singular starts -~~~~~~~~~~~~~~~ - -The Lie series of Equation :eq:`eq-lie-series` needs an output that is analytic at the start. -Two kinds of terms are not, although the prediction is analytic for :math:`t > t_0`: a quotient -whose numerator and denominator both vanish at the start, such as the fraction of a species in -one compartment when every compartment starts empty, and a free power :math:`x^\alpha` of a state -that starts at 0. In both cases the prediction has an expansion at :math:`t_0` whose -coefficients are rational in :math:`\theta`, and these coefficients take the place of the Lie -derivatives. In the following, :math:`t_0 = 0`. - -**Quotients at 0/0.** Let the right-hand side be analytic at the start and let the observable -read the states through a quotient :math:`N/D` whose denominator vanishes at :math:`z_0`. The -states are power series in :math:`t`, and so are :math:`N` and :math:`D`. Let :math:`v` be the -smallest order with :math:`D_v(\theta) \not\equiv 0`. Then - -.. math:: - :label: eq-laurent - - \frac{N}{D} = t^{-v}\, \frac{N}{D_v + D_{v+1} t + \dots}, - -a Laurent series whose coefficients are rational in :math:`\theta` where :math:`D_v(\theta) \ne -0`, and a power series when :math:`N` vanishes to order :math:`v` as well. The engine evaluates -every reciprocal outside the right-hand sides whose operand starts at 0 in this form, after the -states, with the dual numbers inside the coefficients: an operand :math:`a = t^{v}(U + M)`, -with :math:`U` a power series of nonzero constant value and :math:`M` the terms below -:math:`t^v`, which lie in the dual part and the monomials of the gap lengths, has the inverse -:math:`t^{-v} U^{-1} \sum_e (-M U^{-1})^e`, a finite sum since :math:`M` is nilpotent. Each -division costs :math:`v` orders, so the states are expanded further until every output is known -to the Lie order. Rows are the gradients of the coefficients of the prediction, and the -argument of `Lie derivatives and the observability-identifiability matrix`_ holds for them -unchanged, since it uses only that the coefficients determine the prediction near the start. -The valuation :math:`v` is taken at the base point, where :math:`D_k(\theta) = 0` for -:math:`k < v` holds together with the gradient; a point where a coefficient that is not -identically zero vanishes gives the expansion of that point, whose rank is a lower bound. A pole -of the prediction itself is refused, and so is a reciprocal of an operand that starts at 0 inside -the right-hand sides. - -The stopping rule of `Sufficient Lie order`_ extends to these outputs. Let :math:`u(t) = -\partial_{z_0} y(t)` be the gradient of the prediction with respect to the start, a Laurent -series, possibly with a pole: away from the start the quotient is defined, and a start moved -off :math:`D = 0` gives a denominator of order 0. - -**Lemma.** Let :math:`U_\infty` be the span of the coefficients of :math:`u`. Then -:math:`\dim U_\infty \le \rho_S`. - -*Proof.* :math:`\dim U_\infty` is the number of functions among the components -:math:`u_i(t)` that are linearly independent over :math:`\mathbb{R}`, which equals the rank of -their Wronskian matrix :math:`\big(u^{(j)}(t)\big)_{j \ge 0}` over the meromorphic functions. -Along the solution :math:`\varphi_t(z_0)`, the chain rule gives :math:`u^{(j)}(t) = \partial_z -L_F^j h\big(\varphi_t(z_0)\big)\, \Phi(t)` with the invertible fundamental matrix :math:`\Phi(t) -= \partial \varphi_t / \partial z_0`. For small :math:`t > 0`, :math:`\varphi_t(z_0)` is a point -of :math:`S`, which is invariant under the flow, where the output is defined, so by the lemma of -`Sufficient Lie order`_ the rank is at most :math:`\rho_S`. :math:`\square` - -The rows of the coordinates are the coefficients of :math:`\partial_\theta y = u\, -\partial_\theta z_0`. If the coefficients of :math:`u` up to order :math:`N`, those of negative -order included, reach rank :math:`\rho_S` at the start, they span :math:`U_\infty`, and the -rows up to order :math:`N` span all rows: the order is proven sufficient, as in the proposition -there. The coefficients at the base point are those of generic :math:`\theta` unless the base -point lies where a leading coefficient vanishes; this event is not counted in -``info["order_bound"]``. - -**Free powers of a state at 0.** Let a state :math:`x` start at 0 in every condition and enter -through powers :math:`x^{c_0 + c\alpha}`, with integers :math:`c_0 \ge 0`, :math:`c > 0` and a -coordinate :math:`\alpha > 0` as exponent. Generically :math:`x = c_x t^k (1 + O(t))` with -:math:`k \ge 1` and :math:`c_x \neq 0`, so :math:`x^\alpha` behaves as :math:`t^{k\alpha}`, which -is not analytic at 0 for :math:`\alpha \notin \mathbb{N}`. The recast :math:`B = x^\alpha` of -`Non-rational terms`_ needs :math:`x \ne 0` at the start. Instead, with the formal variable -:math:`S = (c_x t^k)^\alpha`, - -.. math:: - :label: eq-start-power - - x^\alpha = S\, Q, \qquad Q = \Big(\frac{x}{c_x t^k}\Big)^{\alpha}, - -where :math:`Q` is a power series in :math:`t` with constant term 1. Every state and output -becomes a power series in :math:`t` and :math:`S`. A coefficient of :math:`t^n S^m`, kept with -the *index* :math:`n` (the exponent of :math:`t` at :math:`\alpha = 1`, so :math:`n \ge km`), -stands for the function :math:`t^{n - km + km\alpha}`. Differentiation in :math:`t` maps it to -:math:`\lambda_{n,m} = n + km(\alpha - 1)` times the coefficient of index :math:`n - 1`, so the -states follow from :math:`\lambda_{n+1,m}\, x_{n+1,m} = f_{n,m}`, and :math:`Q` from the -derivation of the index, :math:`n Q_n = A_0^{-1} \sum_{j=1}^{n} (\alpha j + j - n)\, A_j Q_{n-j}` -with :math:`A = x / (c_x t^k)` and :math:`Q_0 = A_0^\alpha`, where :math:`A_0 - 1` is nilpotent. -:math:`Q_n` needs :math:`x` up to index :math:`n + k`, which is the index of :math:`S Q_n`, so the -recursion runs order by order as for analytic outputs. The coefficients :math:`d_{n,m}` of an -output are rational in :math:`\theta` where no :math:`\lambda` vanishes, which holds for -:math:`\alpha > 0`: :math:`\lambda_{n,m} \ge \min(1, \alpha)\, n`. The same bound shows that the -series converges for small :math:`t > 0`: the recursion divides by at least :math:`\min(1, \alpha)` -times the divisor of a Taylor series, so Cauchy's majorant of the right-hand side divided by -:math:`\min(1, \alpha)` dominates it. - -**Lemma.** For distinct real numbers :math:`q_1, \dots, q_r`, the functions :math:`t^{q_j}` and -:math:`t^{q_j} \log t` are linearly independent over :math:`\mathbb{R}` on every interval -:math:`(0, \varepsilon)`, also as terms of convergent sums whose exponents have no accumulation -point. - -*Proof.* Let :math:`\sum_j (a_j + b_j \log t)\, t^{q_j} = 0` with :math:`q_1 < q_2 < \dots` and -:math:`j` the first index with :math:`(a_j, b_j) \neq 0`. Divided by :math:`t^{q_j}`, the other -terms tend to 0 as :math:`t \to 0^+`, since :math:`t^\delta \log t \to 0` for :math:`\delta > 0`, -while :math:`a_j + b_j \log t` does not. :math:`\square` - -For :math:`\alpha \notin \mathbb{Q}`, distinct :math:`(n, m)` give distinct exponents -:math:`n - km + km\alpha`, and with several powers the exponents :math:`n + \sum_i k_i m_i -(\alpha_i - 1)` are distinct when :math:`1, \alpha_1, \dots, \alpha_K` are linearly independent -over :math:`\mathbb{Q}`; this holds for generic coordinates if the exponents are distinct -coordinates, and two powers of states at 0 with the same exponent are refused. The gradient of -the prediction is - -.. math:: - - \partial_\theta y = \sum_{n,m} c_x^{m\alpha} \Big(\partial_\theta d_{n,m} - + m\, d_{n,m} \big(\alpha\, \partial_\theta c_x / c_x + \log c_x\, \partial_\theta \alpha\big) - + km\, d_{n,m} \log t\; \partial_\theta \alpha\Big)\, t^{n - km + km\alpha}, - -so by the lemma a direction lies in the kernel if and only if it annihilates the vectors in -parentheses without the logarithm of :math:`t` and, separately, the vectors :math:`km\, d_{n,m}\, -\partial_\theta \alpha`. Once a coefficient with :math:`m > 0` is nonzero, the latter span -:math:`\partial_\theta \alpha`, and the transcendental term :math:`\log c_x\, \partial_\theta -\alpha` lies in their span. The rows are therefore :math:`\partial_\theta d_{n,m} + m\, -d_{n,m}\, \alpha\, \partial_\theta c_x / c_x`, rational in :math:`\theta`, and one row -:math:`\partial_\theta \alpha`. With several powers, the rows of the logarithm are -:math:`\sum_i k_i m_i\, \partial_\theta \alpha_i`; the engine refuses an expansion in which the -vectors :math:`(k_i m_i)_i` of the nonzero coefficients do not span every power that occurs. -The engine computes :math:`d_{n,m}` with :math:`S` held fixed in the dual numbers and adds the -term of :math:`c_x`, the leading coefficient of :math:`x`, from the dual of :math:`c_x`. The ranks -are taken at random points, where :math:`\alpha` is generic. - -Truncation at the Lie order :math:`N` keeps the indices :math:`n \le N`, and each power of -:math:`S` counts :math:`k` orders, so the monomials have total degree at most :math:`N/k` in the -:math:`S`. Every coefficient computed is exact, and the rank grows to the final value with -:math:`N`. The stopping rule does not apply: the rows :math:`\partial_z L_F^j h` do not exist at -the start, and a start moved off :math:`x = 0` changes the type of the expansion, so no start -reaches the ceiling. The order stops after the plateau and the saturation guard, the result -says that the Lie order is not proven sufficient, and ``info["limits"]`` names the power. Events, -``equilibrate`` and a state that starts at 0 in one condition only are refused for such powers. - -Closed forms and proofs ------------------------ - -The kernel at a point gives the non-identifiable directions as numbers. To read them as -generators, and to reduce the model, symident reconstructs them in closed form and then tries to -prove them over :math:`\mathbb{Q}`. - -Scalings -~~~~~~~~ - -A *scaling* is a symmetry :math:`\Phi_\lambda(\theta)_i = e^{\alpha_i \lambda}\, \theta_i` with -integer *weights* :math:`\alpha_i`, so :math:`\xi_i = \alpha_i \theta_i`. A function is -*homogeneous* of weight :math:`a` when the scaling multiplies it by :math:`e^{a \lambda}`. With -weights :math:`\alpha_x` of the states as well, the scaling is a symmetry when every -right-hand side has the weight of its state, every observable, event time and multiplicative -event value the weight zero, and every initial value and replaced or added event value the -weight of its state. These conditions are linear in the weights and read off the exponents of -the monomials of all expressions together; their integer solutions form a lattice, the -*integer kernel*, and its basis gives the scalings exactly. They are taken out first and checked -again symbolically. A scaling that holds only on an invariant set, such as -:math:`(k_1, k_2) \mapsto (e^\lambda k_1, e^\lambda k_2)` for :math:`\dot x = k_1 - k_2 x` -started at rest, is not an exact symmetry and fails the check. The scaling of the example in -Equation :eq:`eq-example` is exact, with weights :math:`(0, 0, -1, 1, 1)`. - -General directions -~~~~~~~~~~~~~~~~~~ - -The other non-identifiable directions are *general directions*. The coordinates are ordered with -the initial values of the free states first, in the order of the model, followed by the -parameters in a fixed sorted order. Gauss-Jordan elimination of the rows takes its pivot -columns from left to right, and a *free coordinate* is one without pivot, whose column depends -on the columns to its left. Each kernel vector has the component one on its free coordinate and -zero on the others; every other component is then a rational function of the coordinates. -Alternatively, a direction is fitted in log coordinates, :math:`\xi_i / \theta_i`, and multiplied -back, or chosen with the smallest support outside the scalings, with the component one on the -leftmost coordinate of the support. - -The components are reconstructed from samples. Perturbation finds the variables of each entry; -the entry is sampled at many points and primes and fitted by dense interpolation, by sparse -interpolation after [BenOr1988]_ or by univariate rational interpolation along lines, and it is -lifted to rational coefficients by the Chinese remainder theorem and rational reconstruction -[Wang1982]_. The *route*, as ``Symmetry.route`` names it, is one of - -- ``fit``: rational reconstruction from samples over several primes; ``read-off``: a fast pass - that reads Laurent monomials on the support, with the other coordinates held; ``fit per - prime``: points that each prime solves, joined by the Chinese remainder theorem; each possibly - ``in log coordinates`` and with the kind of fit in parentheses, ``constant``, ``dense`` (a - monomial table up to ``degree_cap``) or ``sparse``; -- ``forward fit per prime``: under ``equilibrate``, with the resting states drawn and the - turnover rates solved, as in the forward seed; -- ``narrow fit``: the kernel restricted to the columns of the support of one direction, in which - it is one-dimensional, with ``exchange groups`` where coordinates that enter only through their - sum or their product were held at the base point and substituted back; ``jets (order k)``: the - generator read from the Taylor coefficients of the kernel entries along a support of at most - six coordinates; -- ``homotopy fit``: the fit along lines below. - -A *sample bank* of points over the union of the relevant coordinates, with kernels per point and -prime, is shared by all dense fits. Before it is reported, every closed form, and a direction -along one coordinate that fills the kernel, is checked at seeded points uniform modulo the -verification prime, the *kernel check* of `Error bounds`_; under ``equilibrate`` on the -coordinates the closed form states, from which the resting-state copies per condition follow. - -A direction that no sampling route closes is fitted along lines :math:`\theta_b + \mu\, -\delta` through the base point: the kernel entries become power series in :math:`\mu` (under -``equilibrate`` with the resting state continued along the line), and Padé forms on a *star*, -several lines in independent directions :math:`\delta`, are fitted as rational functions. An -entry that is not rational in the parameters alone is fitted in parameters and resting states -modulo their balances, the state :math:`x` of condition :math:`c` being named ``x_c``. Each -entry is checked at a prime outside those of the fit, and the direction against the kernel at -two points uniform modulo the verification prime. ``reconst_control(homotopy=False)`` turns -this route off. - -Orbit geometry -~~~~~~~~~~~~~~ - -Each direction with a closed form is classified by the geometry of its orbits, -``Symmetry.kind``, up to a common factor :math:`c(\theta)` of the components: - -- a *scaling*, :math:`\xi_i = c\, w_i \theta_i` with numbers :math:`w_i`, has lines in - logarithmic coordinates as orbits and monomial invariants; a pin - :math:`\theta_i = 1` meets every orbit once; -- a *translation*, :math:`\xi_i = c\, v_i` with numbers :math:`v_i`, has lines in linear - coordinates as orbits and linear invariants. It is proven like a scaling, from the linear - structure of the model: the right-hand sides, observables, initial values and events do not - change along :math:`v`, checked over :math:`\mathbb{Q}`, with the field on the states where - :math:`v` moves initial values. In the positive orthant an orbit ends on the boundary, so the - section lies on a face, :math:`\theta_i = 0`, reached in the limit; -- every other direction is *curved*. - -Translations and curved directions are general directions (``Symmetry.type``). The labels -:math:`X_1, X_2, \dots` of the report and of the reduction count the scalings first, then the -translations and the curved directions. - -Invariant fields and gauge -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Some directions follow from the model equations without sampling. For a model with resting -states, a *global symmetry* is a field of one regime, found by a detection of that regime with -free initial values and extended to the initial and event values, that lies in the kernel. A -*static subsystem* is a set of states at rest that no event moves; parameters that only its -balances hold give fields that leave every such rest in place. Both are reported with these -names as route. Where every direction of the kernel lies in the span of fields that satisfy the -conditions of `Proofs over Q`_ at random points, the *invariant fields*, the rank holds at every -order (``info["rank_fields"]``), with an error bound in ``info["rank_fields_bound"]``. (A) is -checked as a zero and (B), (C) as membership in the span, at two random points; a wrong identity -passes only where a polynomial vanishes there, which the bound covers. Membership at random -points shows (B) and (C) as identities over the rational functions, the hypothesis of the -proposition in `Proofs over Q`_, with coefficients that may have poles on the trajectory. - -With ``gauge``, the detection first finds the scalings and fixes one coordinate per scaling, as -a basis of the weights in the order of preference given and, with general directions, the one -that leaves the fewest nonzero entries in the remaining kernel. A second pass with these -coordinates fixed reconstructs the general directions. Without ``gauge``, -``info["gauge_suggestion"]`` names this choice. - -Proofs over Q -~~~~~~~~~~~~~ - -A closed form is *proven* when it is shown to be a symmetry without random points. For a scaling -this is the check of `Scalings`_. For a general direction, symident *lifts* the direction to a -field :math:`Y = \xi_\theta\, \partial_\theta + \xi_x\, \partial_x` on parameters and states, -i.e., it finds state components :math:`\xi_x`, and proves the conditions below over -:math:`\mathbb{Q}` for every regime of a condition, with event maps :math:`E_e` between the -regimes. They are stated for fields :math:`X_1, \dots, X_m` per regime and the unit directions -:math:`\partial_u` of parameters :math:`u` that enter no regime, whose span is -:math:`\mathcal{D}`; :math:`X'_l` are the fields of the regime after an event, and :math:`v` is -the direction lifted onto the start :math:`z_0`. - -.. math:: - :label: eq-fields - - \begin{aligned} - &\text{(A)} \quad X_l(h) = 0 \ \text{for every output } h, \\ - &\text{(B)} \quad [F, X_l] = \textstyle\sum_k c_{lk}\, X_k + \sum_u c_{lu}\, \partial_u, \\ - &\text{(C)} \quad \mathrm{D}E_e\, X_l = \textstyle\sum_k c'_{lk}\, X'_k \circ E_e + \sum_u c'_{lu}\, \partial_u, \\ - &\text{(D)} \quad v = \textstyle\sum_l a_l\, X_l(z_0) + \sum_u a_u\, \partial_u, - \ \text{the } X_l \text{ regular at } z_0, \text{ and } v(\tau_e) = 0 \text{ for every event time } \tau_e, - \end{aligned} - -with :math:`a` numbers and :math:`c, c'` rational functions of states and parameters, which may -have poles. A proof over :math:`\mathbb{Q}` takes the lift as the one field of each regime, with -:math:`[F, Y] = 0` and :math:`\mathrm{D}E_e\, Y = Y' \circ E_e`; the invariant fields of -`Invariant fields and gauge`_ take the fields of the regimes. Where :math:`[F, Y] \neq 0`, the -proof takes as :math:`X_l` the lift together with the lifts proven before, and (B) and (C) with -coefficients solved at a random point and checked over :math:`\mathbb{Q}` on the other -coordinates: :math:`[F, Y] = \lambda Y + \sum_j \mu_j Z_j` holds, e.g., for a translation of -two initial values whose sum the dynamics keeps, where the flow scales :math:`Y`. With unknown -inputs the jets of an input, the input included, take no identity: their components are the -prolongation :math:`\xi_{w_{j+1}} = F(\xi_{w_j}) + \lambda \xi_{w_j} + \sum_j \mu_j \xi^{Z_j}_{w_j}`, -which makes (B) hold there, so a field whose parameter components hold the input is allowed. -Components are tried as found, canonical, over a common denominator and divided by each of their -first four components. - -**Proposition.** Under (A) to (D) the direction lies in the kernel at every Lie order and every -gap length. - -*Proof.* Let :math:`\mathcal{A}` be the rational functions :math:`g` of a regime with :math:`X_l(g) = 0` -and :math:`\partial_u g = 0` for all :math:`l, u`. By (A), :math:`h \in \mathcal{A}`. By (B), -:math:`X_l(F g) = F(X_l g) - [F, X_l](g) = 0`, and :math:`[F, \partial_u] = 0`, so :math:`F` -maps :math:`\mathcal{A}` into itself; by (C), :math:`g \circ E_e \in \mathcal{A}` for :math:`g` in :math:`\mathcal{A}` of the -next regime. Let :math:`\mathcal{A}_k` be the functions of segment :math:`k` built from its outputs -and from :math:`g \circ E_e` with :math:`g \in \mathcal{A}_{k+1}` by Lie derivatives along -:math:`F`. They lie in :math:`\mathcal{A}` and are analytic along the trajectory, as is every expression -of the model where it is defined. With :math:`z^{(k)}` the start of segment :math:`k` and -:math:`\varphi_t` the flow of :math:`F`, the claim is that the derivative of -:math:`\chi(z^{(k)})` along :math:`v` vanishes for every :math:`\chi \in \mathcal{A}_k`. For -:math:`k = 1` it is :math:`\sum_l a_l\, X_l(\chi)(z_0) + \sum_u a_u\, \partial_u \chi(z_0) = 0` -by (D). If it holds for -:math:`k`, the derivative of :math:`\chi(\varphi_t(z^{(k)}))` along :math:`v` is analytic -in :math:`t` on the segment, and its derivatives at :math:`t = 0` are those of -:math:`L_F^j \chi \in \mathcal{A}_k` at :math:`z^{(k)}`, which vanish, so it vanishes on the -whole segment. With :math:`\chi` an output this is the kernel of every row; with -:math:`\chi = g \circ E_e` at the event time, which :math:`v` does not move, it is the claim -for :math:`k + 1`. :math:`\square` - -The proof needs (B) and (C) as identities of rational functions only. The flow need not keep -the span :math:`\mathcal{D}`: for :math:`X = x^2\, \partial_y` and :math:`F = \partial_x`, -:math:`[F, X] = (2/x)\, X`, yet the flow moves :math:`\partial_y` from :math:`x = -1` to -:math:`x = 0`, where :math:`\mathcal{D} = 0`. The proof follows the functions that the fields -annihilate instead, which a drop of rank does not affect. The identities are proven over -:math:`\mathbb{Q}` per state equation, observable, initial value and event, by symbolic -cancellation. The state components are the closed form read on the states, the initial-value -identities solved for the parameters that set the initial values, or a combination of the -symmetries of the model equations. - -An identity is first evaluated modulo the prime :math:`2^{61} - 1` at a random point; a nonzero -value refutes it exactly. Otherwise its numerator is expanded in a polynomial ring over -:math:`\mathbb{Q}` with a cap on the terms of every polynomial and on the term products of one -multiplication; past a cap the identity is undecided, and the direction keeps the level of its -kernel check. - -Unproven directions -~~~~~~~~~~~~~~~~~~~ - -``info["proof"]`` lists every direction that no proof closes, with its ``support`` and the -``reason`` of each failed route: - -- ``lift of the closed form: [Y, F] on x does not vanish``: the field with state components read - from the closed form is no symmetry, and no other lift was found. -- ``output is not a polynomial in t``: the output identities decide only outputs polynomial in - time. -- ``no combination of the regime fields moves the parameters alike``, ``no combined lift`` (with - the cause, such as more than 8 regimes or work above ``reconst_control(exact_work_cap=)``): the - regimes need state components that agree on the parameters. -- ``events after the start``, ``an event at the start``, ``an input switches on at the start``: - the proof at the resting states covers a start at rest with the inputs at rest that no event - follows or changes. With events, states that no event reaches and that rest alone, such as a - subsystem driving the states the events set, become constant coordinates on their resting - variety, parametrized by a linearly entering parameter; the field holds the component of each - resting state that keeps the variety tangent, and the following states :math:`s` get components - :math:`\xi_s = A s + a`, with a matrix :math:`A` and a vector :math:`a` solved from the - identities of regimes, outputs and events. This covers one resting condition, with reason - ``resting subsystem as coordinates`` and the failing identity. -- ``an inverted power recast``, ``the resting states have no rational parametrization``, ``more - than 8 resting states per condition``: a balance solved for a recast power, without rational - parametrization by the parameters, or with more than the 8 states for which the resting - Jacobian is inverted symbolically stays unproven, the last also in ``info["limits"]``. -- ``no exact proof with these nuisance coordinates``: the unknown-input coordinates have no lift. - -Error bounds ------------- - -Several steps above take place at random points. A statement found there can be wrong, and -symident bounds the probability of this where a degree bound of the polynomials involved is -known. The random choices are the verification prime :math:`p`, drawn per detection from its -seed, and points uniform modulo :math:`p`, each from a seed of its own. All bounds rest on the -Schwartz-Zippel lemma [Schwartz1980]_ [Zippel1979]_: a nonzero polynomial of degree :math:`D` in -:math:`m` variables over a field vanishes at a point drawn uniformly from :math:`A^m`, for a -finite subset :math:`A` of the field, with probability at most :math:`D / |A|`. - -**The order bound.** A wrong certificate of the Lie or gap order needs a polynomial to vanish at -one of the random points of `Sufficient Lie order`_ or `Conditions and events`_: the step that -ends the subspace :math:`U`, or a minor of the rows of an order, on a resting variety with the -degree of Equation :eq:`eq-rest-bound`. With the degrees of the rational system, the -probabilities add up to ``info["order_bound"]``, each multiplied by the number of points drawn -until its point was taken, since the point taken is wrong only if one of them is; -``info["order_draws"]`` is the largest such number, and the points of the gap order are drawn -once. ``info["order_bound_why"]`` names the reason for a missing bound. - -**The kernel check.** A closed form :math:`v` passes the check at a point if it lies in the -kernel there. A point where the kernel is not defined, at a pole or without a resting state, is -skipped. A wrong closed form gives a nonzero *kernel identity* -:math:`\sum_j \mathrm{OIM}_{lj}\, v_j` for some row :math:`l`, which cleared is a polynomial of -degree :math:`D`, so it passes at one point with probability at most :math:`D / p` and at two -points with probability at most :math:`(D / p)^2`. With :math:`n_k` the most points a check drew -for the two that passed (``info["bound"]["draws"]``), the pair is one of -:math:`\binom{n_k}{2}`. For :math:`n_v` verified directions and the largest :math:`D`, - -.. math:: - :label: eq-kernel-bound - - \Pr\big[\text{a wrong direction is verified}\big] \le - n_v \binom{n_k}{2} \Big(\frac{D}{p}\Big)^2 + \text{order bound}, - -which ``info["bound"]`` holds. The bound needs a rational model without root events, event times -rational in the parameters, and Lie and gap orders proven sufficient, since the check runs at the -orders used. It covers the closed forms of the routes checked at points uniform modulo -:math:`p` (``fit``, ``read-off``, ``narrow fit``, ``jets``, ``homotopy fit``); a form of another -route, such as a static subsystem or the forward fit, is checked at particular points only and -stays ``checked``. - -**The bound at rest.** Under ``equilibrate`` a check point draws the coordinates uniformly modulo -:math:`p` and solves the balances :math:`f_i` of each condition there. A point counts where, -unless linear elimination solves the balances, every state is nonzero. The resting states are -algebraic, not rational, in the coordinates, so the lemma above is applied on the resting -variety. Let :math:`Z` be an irreducible component of the resting variety with -:math:`\dim Z = d`, and :math:`P` a polynomial of degree :math:`D` that does not vanish on -:math:`Z`; :math:`V(P)` denotes its zero set and a *hypersurface* the zero set of one nonzero -polynomial. Then :math:`Z \cap V(P)` has degree at most :math:`D \deg Z \le D \prod_i \deg f_i`, -the *Bezout number* of the balances [Heintz1983]_, its projection to the coordinates lies in a -hypersurface of at most that degree [Heintz1983]_, and therefore - -.. math:: - :label: eq-rest-bound - - \Pr_\theta\big[\exists x:\ (\theta, x) \in Z,\ P(\theta, x) = 0\big] \le - \frac{D\, \deg Z}{p}. - -Let :math:`D_\theta` and :math:`D_x` be the columns of :math:`D_N` for the coordinates and for the -states, and :math:`\operatorname{adj}` the adjugate matrix. With :math:`J_x` invertible, a closed -form :math:`v` extends to the kernel of the joint rows exactly where - -.. math:: - - \det(J_x)\, D_\theta v - D_x \operatorname{adj}(J_x)\, J_\theta v = 0 . - -Multiplied by :math:`\det(J_x)`, this identity also vanishes at a check point with a singular -Jacobian, and it does not vanish on the component where :math:`J_x` is invertible at one -resting point of the condition, which is checked. Its degree is the degree :math:`D` of the -cleared kernel identity with the start as coordinates plus :math:`2 \sum_i (\deg f_i - 1)`. A -closed form that reads resting states of further conditions, ``x_c``, lives on the product of -their varieties over :math:`\theta`. The solves leave the component only above a proper -subvariety of the coordinates of degree at most :math:`\prod_i \deg f_i`, the zeros of the -pivots of a linear elimination or the projection of the other components, provided every root -taken lies on one component over :math:`\mathbb{Q}(\theta)`: a rest solved by linear elimination, -or interior roots conjugate over :math:`\mathbb{Q}(\theta)` (``info["branches"]``), on a split -factor where a balance splits. In Equation :eq:`eq-kernel-bound` the degree :math:`D` is then -replaced by :math:`(D + 2 \sum_i (\deg f_i - 1)) \prod_i \deg f_i + \sum \prod_i \deg f_i`, the -products and the sum taken over the conditions read. Without such a component (branches not -decided), with resting states continued along a line at the check points, or with a power or -exponential in the balances, a direction that the proof leaves open is ``checked``, and -``info["bound"]`` gives the reason. - -**What the bounds exclude.** The bounds are probabilities over the points modulo :math:`p`. They -exclude the chance that :math:`p` divides the *content* of an integer identity, the greatest -common divisor of its coefficients, which then vanishes modulo :math:`p`, or that :math:`p` is -one of the finitely many primes at which an identity nonzero on a resting component vanishes -there modulo :math:`p`. - -Levels and rank status ----------------------- - -The *level* of a closed form says how far it is established: - -- ``exact``: proven over :math:`\mathbb{Q}`, as a scaling of the integer kernel or as a field of - `Proofs over Q`_. -- ``verified``: in the kernel at two seeded points modulo the verification prime, with the error - probability of `Error bounds`_ in ``info["bound"]``. -- ``checked``: the same test where no bound applies (``info["bound"]`` says why), or a test on the - entries that can be evaluated at the points. -- ``open``: no closed form. - -The rank (``info["rank_status"]``) is - -- *proven* when it is full, when it plus the number of independent exact directions is :math:`d`, - or when every direction is proven over :math:`\mathbb{Q}`; -- *verified*, with a probability, when the Lie, gap and series orders are proven sufficient and - every direction is verified with a bound; when every direction lies in the span of invariant - fields, checked at random points with a bound (``info["rank_fields_bound"]``); or when a rank - modulo unknown inputs holds at a random point; -- a *lower bound* otherwise, i.e., the generic rank may be higher and some reported directions may - not exist. - -Besides proofs, a result rests on two assumptions (``info["assumptions"]``, -``Reduction.assumptions``), both part of the declared model: the domain :math:`\Theta` -(``positive``) and, with switches, the start sides that ``regimes`` declares where the initial -values do not decide them. A verified closed form or rank is wrong with probability at most -``error_bound``, including a wrong certified order. Floating point enters the choice of a gauge -and of the ``reduce_cq`` pivots, never a rank, a sign or a closed form. Every other step is -proven or named in the result: a ``checked`` direction, a ``lower bound`` rank, a section claim -under ``unproven``, a limit under ``info["limits"]``, a resting branch under -``info["branches"]``. - -Discrete symmetries -------------------- - -Local identifiability leaves finitely many coordinate values with the prediction of a generic -one; more than one such value in :math:`\Theta` is a *discrete symmetry*, which no generator -shows. ``detect(mode="global")`` searches them after the local analysis. A *discrete symmetry* is a map :math:`\sigma` with :math:`\Psi_N(\sigma(\theta)) = -\Psi_N(\theta)` and :math:`\sigma(\theta) \ne \theta`. It matters for estimation only where -:math:`\sigma(\theta) \in \Theta`: :math:`\theta \mapsto -\theta` of a positive coordinate that -enters as :math:`\theta^2` is no symmetry of the model on :math:`\Theta`. Counts over the -algebraic closure, as in [Hong2020]_ and [ReyBarreiro2023]_, include such values; -:meth:`~symident.Symmetries.discrete` counts in :math:`\Theta`. - -The fiber needs a model rational in the states and coordinates. Three rewrites before the count -keep the fiber. A coordinate :math:`\theta` that enters only through :math:`b^{c\theta}`, with -rational :math:`c`, is read as :math:`X = b^{\theta/L}`, :math:`L` the common denominator of the -exponents, a bijection of :math:`\mathbb{R}` onto the positive reals; a map is reported back as -:math:`\theta' = L \log_b \sigma(X)`, so a swap stays a swap and a discrete scaling becomes a -translation. An observable :math:`y` for which :math:`e^{c y}` is rational, :math:`c \in \{1, -\log 10, \log 2\}`, is replaced by :math:`e^{c y}`, one of the form :math:`e^{r}` by :math:`r`, -and an odd power :math:`r^{p/q}` by :math:`r`: these maps are injective where the observable is -real, so two values of the coordinates have the same output before the rewrite if and only if -they have it after. A factor :math:`e^{a t}`, with :math:`a` free of the states and the clock, -becomes a state :math:`E` with :math:`\dot E = a E` and :math:`E(0) = 1`, whose unique solution it -is; this needs conditions that start at :math:`t = 0`. ``info["discrete"]["rewrites"]`` lists the -rewrites, and a term that stays non-rational is named in the error. - -A model with directions is reduced first (:func:`~symident.reduce`); the reduced model is -locally identifiable, so its *fiber* :math:`\Psi_N^{-1}(\Psi_N(\theta^\ast))` is finite. The -fiber at a point :math:`\theta^\ast` is the solution set of the polynomial system that equates the -Taylor coefficients of the observables up to order :math:`N` with their values at -:math:`\theta^\ast`, away from zeros of coordinates and denominators. msolve -[Berthomieu2021]_ counts its points over the algebraic closure modulo a prime, an upper bound -for the size of the fiber of the model, which more equations can only lower. As in SIAN -[Hong2020]_, the derivatives of the states at the start are unknowns of the system, tied by the -Taylor coefficients of :math:`D(x)\,\dot x = N(x)` and :math:`E(x)\, y = M(x)`. Every -observable starts one order above the highest of the orders whose next coefficient adds no rank to -the Jacobian in the coordinates: at a given start, a coefficient that adds no rank can still remove -points. The orders rise together until the count is the same at two successive steps, or equals -the size of the orbit of the proven candidates, one if there are none, which no higher order -changes, since more equations give a fiber within the one before and the orbit stays in it. The -count of a block is the number of distinct values of a random linear form in the coordinates on -the points of the block: msolve gives the reduced Gröbner basis, the standard monomials span the -quotient, and the number of distinct eigenvalues of the multiplication by the form is the degree of -the square-free part of the minimal polynomial of that multiplication. Points that differ only in the derivatives of the states, or that are -multiple, count once. The series of a known input is a number, a variable -that a linear equation fixes to a number is substituted, a derivative that enters one equation -only, there linearly with a numeric coefficient, leaves with that equation, and the rest splits -into blocks without a shared variable, whose fibers multiply. msolve runs over :math:`\mathbb{F}_p` -with its probabilistic sparse linear algebra. -The conditions are stacked as in the local analysis: each has derivatives of its own, the -coordinates are shared. After an event the gaps are :math:`\varepsilon\, \Delta t_i^0` as in -`Conditions and events`_: the state at the end of a gap is the series of the segment before -evaluated at :math:`\varepsilon\, \Delta t_i^0`, the event maps it to the start of the next -segment, and every coefficient after the event is a power series in :math:`\varepsilon`, kept up -to the *gap order*, which rises with the order. A segment whose start holds coordinates, an event -at an estimated time, is expanded at the start of the condition on the flow continued backward, -so that its coefficients depend on the time of the event. Under ``equilibrate`` the start of a -condition is the solution of the balances over :math:`\mathbb{Q}(\theta)`, with the inputs at zero, -the states that are coordinates at their free resting value and the states without dynamics at -their initial value; where the balances have more than one rational solution, the one with the -most states away from zero, and none without one rational solution. States that no observable -depends on are left out. With switches, as in `Switching models`_, each condition enters from its -start in the regime of the start, decided at a random point, and each allowed regime as a copy -whose start is free on a switching surface :math:`\gamma_j = 0` to an allowed neighbor: at the point -the surface is solved for a state in which it is linear, and in the fiber -:math:`\gamma_j(z', \theta') = 0` is an equation; the clock and the jets of known inputs of a copy -start at known values. A map is ``exact`` with a map of the states in every regime that takes each -surface to itself, :math:`\gamma_j(\varphi(x), \sigma(\theta)) = c\, \gamma_j(x, \theta)` with -:math:`c` free of the states and positive on :math:`\Theta`. A switch on the parameters alone puts -the model in one regime and is not handled. A map reconstructed from the fiber is -checked on the coefficients four orders further up, in :math:`t` and in :math:`\varepsilon`; a -map that fails shows a fiber too large at that order, and the orders rise. -The counts in :math:`\Theta` at the sample points end after the budget and one call of msolve, and -where the proven maps account for the count, the points are the orbits. Over :math:`\mathbb{Q}`, -msolve isolates the real points in boxes, refined until each box decides -the sign of every coordinate declared positive; the count in :math:`\Theta` follows at rational -sample points. Where the rational maps of the next paragraph account for every point counted at a -sample point, and the images give its coefficients exactly, the point and its images are the -fiber, and the count needs no isolation. The number of points in :math:`\Theta` is constant only between the hypersurfaces -on which two points meet or a point crosses the boundary of :math:`\Theta`, so the count is -reported per point and never taken as a global verdict. - -Permutations of the coordinates are tested before the count. If :math:`\sigma` permutes the -coordinates and keeps every Taylor coefficient :math:`c`, then :math:`c(\sigma(\theta)) = -c(\theta)` gives :math:`\partial_i c(\theta) = (\partial_{\sigma(i)} c)(\sigma(\theta))`, so -:math:`c` depends on :math:`\theta_i` if and only if it depends on :math:`\theta_{\sigma(i)}`, and -:math:`\sigma` maps each coordinate onto one with the same set of coefficients that depend on it. -These sets come from one evaluation of the Jacobian at a random point modulo a prime. The -transpositions within each class of equal sets, and then the products of two transpositions that -fail alone, are tested on the coefficients up to four orders past the rank criterion at a random -point modulo the prime, and a candidate that passes is proven as below or kept as ``checked``. -The candidates join the maps of the fiber; they need no count, which only decides whether the -maps are complete. - -Where the other points are rational functions :math:`\sigma_j(\theta)`, they are reconstructed -without matching points across samples. For a coordinate :math:`\theta_i`, the characteristic -polynomial :math:`\prod_j (Z - \sigma_{j,i}(\theta))` over the fiber is invariant under -permutations of the points, so its coefficients are rational functions of :math:`\theta`; msolve -gives them modulo a prime from the rational univariate representation, and they are -interpolated as the generators are. A linear factor over :math:`\mathbb{Q}(\theta)` is a rational -:math:`\sigma_{j,i}`. Coordinates with the fewest arguments come first, until their rational -roots separate the points of the fiber; each other coordinate is then interpolated on each -point, labeled by those roots. A map is ``checked`` when the coefficients agree at random -rational points, and ``exact`` with a map :math:`\varphi` of the states such that - -.. math:: - - F(\varphi(x), \sigma(\theta)) = D\varphi(x)\, F(x, \theta), \qquad - h(\varphi(x), \sigma(\theta)) = h(x, \theta), \qquad - \varphi(x_0(\theta)) = x_0(\sigma(\theta)) - -over :math:`\mathbb{Q}(x, \theta)`: :math:`\varphi` is :math:`\sigma` on a state whose initial value -is a coordinate of its own and the identity on the others, or, where the identity fails, the -solution of :math:`h(\varphi(x), \sigma(\theta)) = h(x, \theta)` and the Lie derivatives of these -equations where they are linear in :math:`\varphi`, or :math:`\varphi` affine in the states of the -block that :math:`\sigma` reaches, the states whose right-hand side or start holds a coordinate -that :math:`\sigma` moves, closed under the states that read them, and the identity elsewhere, with -coefficients solved from the identities where they are linear in them. With events, each segment has such a map, and -at each event :math:`\varphi_{\text{after}}(E(x, \theta)) = E(\varphi_{\text{before}}(x), -\sigma(\theta))`, in every condition. The ``exact`` maps generate a group :math:`G`; at a point -outside the fixed sets of the elements of :math:`G` the orbit is :math:`|G|` points of the fiber. When -:math:`|G|` equals the count, the count is final (``count_final``): the exact maps give a lower -bound equal to the upper one. ``info["discrete"]["certificate"]`` lists the state maps, :math:`|G|`, -the count and the prime, and names the step that is not proven: that the count modulo the prime -at a random point is the count over :math:`\mathbb{C}` at a generic point, an axiom without an error -bound. A map with a positivity certificate for each -image coordinate preserves :math:`\Theta`; a map with an image coordinate negative on -:math:`\Theta` never meets it; otherwise the conditions on :math:`\theta` are listed. Ordering the -coordinates and keeping in each orbit the point that is least in the first coordinate a map -moves gives a *fundamental domain*, a set of inequalities such as :math:`k_{01} < k_{12}`. - -For a reduction, each image of the fundamental domain under the maps is a *branch*. Where a map -:math:`\sigma` has one hypersurface :math:`q = 0` as fixed set and exchanges its sides, -:math:`q(\sigma(\theta)) = -c\, q(\theta)` with :math:`c > 0` on :math:`\Theta`, the branches are -the sides :math:`s\, q > 0`, :math:`s = \pm 1`, named by the inequality, and :math:`q = 0` is their -boundary. On a side, :math:`\delta = s\, q(\theta) > 0` replaces a coordinate :math:`x` in which -:math:`q` is linear; :math:`x` is chosen by structure, a solution :math:`x(\delta, \theta')` with a -positivity certificate first, then the smaller expression, so that neither the chart nor the name of -the branch depends on the names or the order of the parameters. The chart maps free values in the -positive orthant into the side and is chained with the section of the continuous symmetries. It is -``injective`` where the coefficient of :math:`x` in :math:`q` has a sign certificate, since -:math:`\delta = s\, q(\theta)` inverts it, and it ``reach``-es the whole side where -:math:`x(\delta, \theta')` has a positivity certificate; a claim without certificate is listed -under ``unproven``. A fiber of more than two points has no branch charts. - -Reduction and sections ----------------------- - -A reduction replaces the coordinates by combinations that the output determines [Chappell1998]_ -[Evans2000]_ [Massonis2023]_, the invariants :math:`I_l(\theta)` with :math:`X(I_l) = 0` -[Olver1993]_. The directions are reduced in *blocks*, sets of directions with overlapping -supports, each block with the group :math:`G` generated by the flows of its generators. -symident searches, within degree bounds, monomial, polynomial and rational invariants (with a -denominator in one coordinate), Darboux polynomials and exponential factors [Prelle1983]_ -[Goriely2001]_, i.e., polynomials :math:`P` and exponentials :math:`e^{P/Q}` that :math:`X` -multiplies by a polynomial, and invariants by separable quadrature, i.e., by integrating -:math:`\mathrm{d}\theta_i / \xi_i = \mathrm{d}\theta_j / \xi_j` where it separates, and by an -integrating factor. The invariants become new parameters, :math:`I_l(\theta) = q_l`, and the -remaining coordinates are expressed through them. The invariants are coordinates on the orbit -space :math:`\Theta / G`, a *chart*, and the trafo is the section in these coordinates. A chart is -returned only where it is valid on the declared domain, the positive orthant by default; -``Reduction.partial`` names the directions whose chart covers the domain only in part, and -``alternatives=True`` also returns the charts of the other valid choices of the fixed -coordinates. - -A scaling is removed by fixing one of its coordinates at one, such as an initial value or a -scale, a *pin*. Every orbit of a scaling meets the hypersurface :math:`\theta_i = 1` of a moved -coordinate once, so the result is a *global section*: a one-to-one map of the new parameters onto -a *global cross-section*, a set meeting every orbit exactly once, with the invariants as global -coordinates on the orbit space :math:`\Theta / G`. In the example of Equation :eq:`eq-example`, -:math:`A_0 = 1` meets every orbit of the scaling once. A direction along one coordinate is pinned -like a scaling; every orbit meets the pin where a *sign certificate*, a proof that an expression -has one sign on :math:`\Theta`, shows that the generator component on the pinned coordinate has -one sign, else the orbits can be the intervals between the zeros of that component, and the pin -is listed under ``unproven``. - -**Linear flows.** A block of :math:`r` general generators is a *linear flow* when, in the -coordinates :math:`\tilde\theta_i = \theta_i` for a moved coordinate that is not declared -positive and :math:`\tilde\theta_i = \log \theta_i` for a positive one, every component -:math:`\tilde\xi_i` depends only on the coordinates :math:`u` that the block does not move, and -no declared bound involves a moved coordinate. The generators then commute, and the orbit of a -point is the affine set :math:`\{(u, \tilde\theta + \Xi(u) s) : s \in \mathbb{R}^r\}`, with -:math:`\Xi(u)` the matrix of the components, on which every moved coordinate takes every real -value. Pins :math:`\tilde\theta_P = 0` on :math:`r` moved coordinates :math:`P` whose minor -:math:`\det \Xi_P(u)` has one sign on :math:`\Theta` give a global section: -:math:`\tilde\theta_P + \Xi_P(u) s = 0` has exactly one solution on every orbit, so the section is -``injective`` and ``reach``-es every orbit. The invariants are -:math:`\tilde\theta_N - \Xi_N(u) \Xi_P(u)^{-1} \tilde\theta_P` for the other moved coordinates -:math:`N`, and a linear coordinate is pinned to 0, a positive one to 1. This stage runs before -the search for invariants. Among the pin sets, a coordinate that enters only the observables (an -offset of the observation function) is preferred, an initial value is taken last. In a model with -``unknown_inputs``, a direction whose components depend on states or unknown inputs is no field on -the parameters and has no chart; the reduction names the unknown inputs that absorb it. - -The pinned coordinates of a block of scalings, its *transversal*, are chosen among the -coordinates of the support that are not fixed: subsets :math:`T` of the size of the block, taken -in the order of the coordinates, for which the columns :math:`W_T` of the weight matrix -:math:`W` are invertible and :math:`W_T^{-1} W` has integer entries, so that every other -coordinate becomes a monomial of the new parameters; for many candidates a greedy choice by the number of scalings moving each -coordinate. Without a certified transversal the block keeps its invariants only -(``invariant_only``). Before the search for invariants, a block of several general generators is -split by *module reduction*: an elimination order with few new nonzero entries, found at random -points modulo a prime and repeated exactly, gives combinations of the generators with smaller -supports, and independent ones form separate blocks. - -For a block of :math:`r` general generators the invariants :math:`I(\theta) = q` are solved for -coordinates :math:`\theta_s = R(q, g)`, with :math:`r` *gauge coordinates* :math:`g` left. Every -level set :math:`\Lambda_q = \{\theta \in \Theta : I(\theta) = q\}` is one orbit when - -1. :math:`R(q, g)` is the unique solution for every gauge value, so :math:`\Lambda_q` is the graph - of :math:`R(q, \cdot)` over :math:`\mathcal{G}_q = \{g : (R(q, g), g) \in \Theta\}`; -2. the :math:`r \times r` minor of the generator components on :math:`g` has one sign on - :math:`\Theta`, so every orbit is :math:`r`-dimensional and open in :math:`\Lambda_q` (for - generators with poles, the minor of the fields times their denominators); -3. :math:`\mathcal{G}_q` is connected. - -The set :math:`\mathcal{G}_q` is given by one inequality :math:`\pi_k(q, g) > 0` per positive -solved coordinate and square-root factor. It is connected when every inequality is convex in -:math:`g` (affine, a concave quadratic, or, in one positive gauge coordinate, a polynomial with at -most one sign change and so, by Descartes' rule of signs, at most one positive root), or when a -gauge coordinate enters every inequality affinely with a coefficient of known sign, so that the -*fibers*, the sets of that coordinate at fixed other gauge coordinates, are intervals and the set -is connected with its projection, decided the same way. Square roots in :math:`g`, or of a single -positive invariant, are first removed by a square substitution, which is one to one on the -positive half-line. The *section point* :math:`\hat\theta(q)` then lies in :math:`\Lambda_q` and, -by a *positivity certificate*, a proof that each entry is positive on the domain, in -:math:`\Theta`. - -**Coverage.** ``reach`` says that every level set of the invariants is one orbit; with *total -coverage* every orbit then meets the section, under *partial coverage* exactly the orbits whose -invariants lie where the solved entries are positive. Under declared bounds, i.e., expressions in -``positive``, an entry without positivity certificate is kept, with partial coverage, and listed -under ``unproven``. Without bounds it is kept only when the search found no section certified on -the whole domain, and only where a sampled orbit has every entry positive: the transformation then -covers the orbits on which the ``sign_conditions``, the entries as inequalities in :math:`q`, -hold, the sampled one among them, and no others. A positivity certificate treats an *atom*, a -non-polynomial subterm such as :math:`\log x`, as positive only where its sign is proven; an -AM-GM certificate, a lower bound by the inequality of arithmetic and geometric means over pairs of -terms, is strict only by the positive remainder the pairs leave, on a term free of coordinates -that are not declared positive where there are any. - -**Face sections.** A *face* is a boundary set :math:`\theta_f = 0` for coordinates -:math:`\theta_f` of the block; a section on a face lies outside :math:`\Theta` and is reached only -in a limit. It is tried first, and once one is found no other is searched; the new parameters are -the coordinates of the face point, not invariants. With :math:`\theta_f` as gauge coordinates, -the conditions above make every level set one orbit, and :math:`R(q, \theta_f) \to R(q, 0) > 0` -puts the face point :math:`(0, R(q, 0))` in the closure of every orbit of :math:`\Lambda_q`. The -output, constant along the orbit, equals that at the face point when the model is continuous -there: no model expression has a pole at the face, every denominator in the block parameters has -one sign there, and under ``equilibrate`` :math:`x^\ast(\theta)` has a limit. For that limit each -generator is lifted to a field :math:`\tilde X = X + \xi_x \partial_x` tangent to the resting -variety, by the state components of an exact direction or by the implicit derivative -:math:`\xi_x = -J_x^{-1} J_\theta \xi_\theta`; exactly verified invariants of the lifted fields -that solve for the moved states and stay positive at :math:`\theta_f = 0` give the limit along -every orbit. The implicit derivative needs :math:`J_x` regular: proven when :math:`\det J_x` has -one sign on :math:`\Theta`, else checked at random points. Without a lift, the resting state is -continuous when :math:`f` is affine in the states with a resting Jacobian of one sign at the face, -else it is checked at random face points; a checked resting state sets ``face_level`` and -``level`` of the block to ``checked``. - -**Injectivity.** That every orbit meets the cross-section :math:`\mathcal{C}` at most once -(``injective``) is proven, for any number of generators, when the solved coordinates recover every -point of :math:`\mathcal{C}` from the invariants, :math:`\hat\theta(I(\theta)) = \theta` on -:math:`\mathcal{C}`, since two points of one orbit have equal invariants. The identity is shown -over :math:`\mathbb{Q}` on a parametrization of the positive points of :math:`\mathcal{C}`, -monomial where the section equates monomials, else by solving each equation for a coordinate of -degree one; the claim is made for sections with total coverage off a face. For one generator it -also holds when :math:`X` changes the pinned coordinate, or the logarithm of the quotient of the -two sides of the section equation, with one sign on :math:`\Theta`. - -**Zero limits.** With ``zero_limits=True`` each block reports which coordinates can be set to zero: -everywhere, under a condition, or in a limit along the orbits when the face is mapped into itself -by the generators, and whether this is certain (``to_dict()["zero_compatibility"]``). - -An unproven claim is listed under ``unproven`` of the block and makes the block ``open``; a block -is ``verified`` or ``checked`` when a direction or a face resting state has that level, else -``exact``. The transformation is checked over :math:`\mathbb{Q}`, and ``check=True`` runs the -detection again on the reduced model (``Reduction.checks["loop"]``). - -References ----------- - -.. [Ax1971] J. Ax. On Schanuel's conjectures. *Annals of Mathematics* 93(2), 252-268, - 1971. - -.. [BenOr1988] M. Ben-Or and P. Tiwari. A deterministic algorithm for sparse - multivariate polynomial interpolation. *Proceedings of the 20th ACM Symposium on - Theory of Computing*, 301-309, 1988. - -.. [Berthomieu2021] J. Berthomieu, C. Eder and M. Safey El Din. msolve: a library for - solving polynomial systems. *Proceedings of ISSAC 2021*, 51-58, 2021. - -.. [Chappell1998] M. J. Chappell and R. N. Gunn. A procedure for generating locally - identifiable reparameterisations of unidentifiable non-linear systems by the similarity - transformation approach. *Mathematical Biosciences* 148(1), 21-41, 1998. - -.. [Evans2000] N. D. Evans and M. J. Chappell. Extensions to a procedure for generating - locally identifiable reparameterisations of unidentifiable systems. *Mathematical - Biosciences* 168(2), 137-159, 2000. - -.. [Godfrey1983] K. Godfrey. *Compartmental Models and Their Application*. Academic Press, - London, 1983. - -.. [Goriely2001] A. Goriely. *Integrability and Nonintegrability of Dynamical Systems*. - Advanced Series in Nonlinear Dynamics 19, World Scientific, 2001. - -.. [Heintz1983] J. Heintz. Definability and fast quantifier elimination in algebraically - closed fields. *Theoretical Computer Science* 24(3), 239-277, 1983. - -.. [HermannKrener1977] R. Hermann and A. J. Krener. Nonlinear controllability and - observability. *IEEE Transactions on Automatic Control* 22, 728-740, 1977. - -.. [Hong2020] H. Hong, A. Ovchinnikov, G. Pogudin and C. Yap. Global identifiability of - differential models. *Communications on Pure and Applied Mathematics* 73(9), 1831-1879, - 2020. - -.. [Karlsson2012] J. Karlsson, M. Anguelova and M. Jirstrand. An efficient method for - structural identifiability analysis of large dynamic systems. *IFAC Proceedings Volumes* - 45(16), 941-946, 2012. - -.. [Martinelli2015] A. Martinelli. Extension of the observability rank condition to - nonlinear systems driven by unknown inputs. *23rd Mediterranean Conference on Control and - Automation*, 589-595, 2015. - -.. [Martinelli2019] A. Martinelli. Nonlinear unknown input observability: extension of the - observability rank condition. *IEEE Transactions on Automatic Control* 64(1), 222-237, - 2019. - -.. [Massonis2020] G. Massonis and A. F. Villaverde. Finding and breaking Lie symmetries: - implications for structural identifiability and observability in biological modelling. - *Symmetry* 12(3), 469, 2020. - -.. [Massonis2023] G. Massonis, J. R. Banga and A. F. Villaverde. AutoRepar: a method to - obtain identifiable and observable reparameterizations of dynamic models with mechanistic - insights. *International Journal of Robust and Nonlinear Control* 33(9), 5039-5057, 2023. - -.. [Merkt2015] B. Merkt, J. Timmer and D. Kaschek. Higher-order Lie symmetries in - identifiability and predictability analysis of dynamic models. *Physical Review E* 92(1), - 012920, 2015. - -.. [Olver1993] P. J. Olver. *Applications of Lie Groups to Differential Equations*. - Graduate Texts in Mathematics 107, Springer, 2nd edition, 1993. - -.. [Pohjanpalo1978] H. Pohjanpalo. System identifiability based on the power series - expansion of the solution. *Mathematical Biosciences* 41, 21-33, 1978. - -.. [Prelle1983] M. J. Prelle and M. F. Singer. Elementary first integrals of differential - equations. *Transactions of the American Mathematical Society* 279(1), 215-229, 1983. - -.. [ReyBarreiro2023] X. Rey Barreiro and A. F. Villaverde. Benchmarking tools for a priori - identifiability analysis. *Bioinformatics* 39(2), btad065, 2023. - -.. [Savageau1987] M. A. Savageau and E. O. Voit. Recasting nonlinear differential equations - as S-systems: a canonical nonlinear form. *Mathematical Biosciences* 87(1), 83-115, 1987. - -.. [Schwartz1980] J. T. Schwartz. Fast probabilistic algorithms for verification of - polynomial identities. *Journal of the ACM* 27(4), 701-717, 1980. - -.. [Sedoglavic2002] A. Sedoglavic. A probabilistic algorithm to test local algebraic - observability in polynomial time. *Journal of Symbolic Computation* 33(5), 735-755, - 2002. - -.. [Tunali1987] E. T. Tunali and T. J. Tarn. New results for identifiability of nonlinear - systems. *IEEE Transactions on Automatic Control* 32(2), 146-154, 1987. - -.. [Villaverde2016] A. F. Villaverde, A. Barreiro and A. Papachristodoulou. Structural - identifiability of dynamic systems biology models. *PLOS Computational Biology* 12(10), - e1005153, 2016. - -.. [Villaverde2019] A. F. Villaverde, N. Tsiantis and J. R. Banga. Full observability and - estimation of unknown inputs, states and parameters of nonlinear biological models. - *Journal of the Royal Society Interface* 16(156), 20190043, 2019. - -.. [Wang1982] P. S. Wang, M. J. T. Guy and J. H. Davenport. P-adic reconstruction of - rational numbers. *ACM SIGSAM Bulletin* 16(2), 2-3, 1982. - -.. [Yates2009] J. W. T. Yates, N. D. Evans and M. J. Chappell. Structural identifiability - analysis via symmetries of differential equations. *Automatica* 45(11), 2585-2591, - 2009. - -.. [Zippel1979] R. Zippel. Probabilistic algorithms for sparse polynomials. - *Symbolic and Algebraic Computation, EUROSAM '79*, Lecture Notes in Computer Science - 72, 216-226, 1979. +and :math:`k_1`, :math:`k_2`, :math:`s A_0` and :math:`s B_0` are invariants of :math:`X`. diff --git a/docs/method/conditions.rst b/docs/method/conditions.rst new file mode 100644 index 0000000..5a3a0ee --- /dev/null +++ b/docs/method/conditions.rst @@ -0,0 +1,523 @@ +Conditions, events, resting states and inputs +============================================= + +A model is observed under several conditions, with events, from resting states, with inputs or +with switches. This chapter states how each enters the local analysis of :doc:`local` and the +proofs of :doc:`proofs`, and how a PEtab problem maps onto them; the global analysis takes them up +in :ref:`fiber-features`. + +.. _conditions-events: + +Conditions and events +--------------------- + +The rows of the conditions :math:`c = 1, \dots, C` are stacked over the shared coordinates, so +that :math:`\ker \mathrm{OIM} = \bigcap_c \ker \mathrm{OIM}^{(c)}`. + +A segment starts from the end of the previous one, propagated over the *gap* +:math:`\Delta t_i` between the events. To separate directions that exist only for particular +event timings from generic ones, the gaps are placed on the line +:math:`\Delta t_i = \varepsilon\, \Delta t_i^{0}` through the actual gaps :math:`\Delta +t_i^{0}`, and the rank is taken over the Laurent series :math:`\mathbb{F}_p((\varepsilon))` in +the formal variable :math:`\varepsilon`. The kernel at :math:`\varepsilon = 1` is read from +Padé forms, i.e., rational functions of :math:`\varepsilon` matching the series of each kernel +entry, that further coefficients confirm; this acceptance is heuristic and gives a basis of the +kernel only. + +The rows after a gap are power series in :math:`\varepsilon` whose coefficients belong to a +family of functions fixed by the model. Their rank, at points uniform modulo :math:`p`, +therefore gives an upper bound of the rank over the series, with error terms that enter the +order bound. The *gap order* :math:`M`, the number of coefficients kept, rises until the +truncated rank reaches this bound, which proves :math:`M` sufficient; a truncated rank above +the bound refutes it, and nothing is certified. A symbolic event time gives no bound, since it +moves the boundary and shifts the series and the event state outside the family. Without bound +(``equilibrate``, recast terms, such an event time) or at ``reconst_control(gap_order_cap=)``, +the rank is a lower bound, and ``info["limits"]`` says where :math:`M` stopped. + +**Many conditions.** With 24 or more conditions of one segment each, without unknown inputs, +recast terms or, at rest, conserved totals, the analysis runs on a subset :math:`S` of the +conditions. The conditions are taken one of each *structure* in turn, a structure being the set +of coordinates that reach the output of a condition at some Lie order. At a random point, a +condition joins :math:`S` where the rows of the condition raise the rank of the rows of the +conditions before it, or where it is the first to reach a coordinate; the rows go to two orders +past the largest first order of a coordinate, and again to the order the analysis of :math:`S` +reaches, with the conditions of :math:`S` first. At rest the rows of a condition are those on +:math:`\theta` after the resting states of the condition are eliminated. Since the rows of +:math:`S` are rows of the whole problem, + +.. math:: + + \operatorname{rank} \mathrm{OIM} \;\ge\; \operatorname{rank} \mathrm{OIM}^{(S)} = d - k + +for the :math:`k` directions :math:`\xi_1, \dots, \xi_k` found on :math:`S`. The upper bound +needs each :math:`\xi_j` to be a symmetry of every condition :math:`c \notin S`, which is +proven in one of four ways: no coordinate of the support of :math:`\xi_j` reaches the output of +:math:`c`, so that every row of :math:`c` vanishes on the support; :math:`\xi_j` is +proportional to an exact scaling of the whole model, checked on one condition per group of +equal monomials; the lift of the closed form of :math:`\xi_j` is proven on :math:`c` as in +:ref:`proofs-over-q`; or, at rest, the output identities hold at the resting states of :math:`c`. +Then :math:`\ker \mathrm{OIM} \supseteq \operatorname{span}(\xi_1, \dots, \xi_k)` and +the two ranks agree, proven when every :math:`\xi_j` is exact on :math:`S`. A condition where a +direction leaves the kernel at a random point, or where none of the four applies, joins +:math:`S` and the analysis repeats; where :math:`S` would hold more than half of the conditions, +or a direction has no exact closed form, every condition is analyzed. ``info["selection"]`` +lists :math:`S` and how the other conditions are covered; ``SYMIDENT_NOSELECT=1`` analyzes every +condition. + +.. _steady-states: + +Resting states +-------------- + +With ``equilibrate=True`` every condition starts at rest: the initial value is a *resting +state* :math:`x^\ast(\theta)` with :math:`f(x^\ast, 0, \eta) = 0`, inputs at zero. The +*balances* of a condition are the components of :math:`f` cleared to polynomials, and the +*resting variety* :math:`W` is the closure of :math:`\{(\theta, x) : f(x, 0, \eta(\theta)) = +0\}`. No closed form of the resting state is needed: at each point the balances are solved over +:math:`\mathbb{F}_p`, by linear elimination, by resultants for coupled subsystems of one or two +states, or by msolve :cite:p:`Berthomieu2021`. Only msolve excludes states at zero, by a Rabinowitsch +variable :math:`\tau` with :math:`\tau \prod_i x_i = 1`, and a resting state solved modulo one +prime is not resampled at another. The kernel is taken in coordinates and resting states +jointly, with the tangency of a direction :math:`(\xi_\theta, \xi_x)` to :math:`W` as extra +rows rather than through the implicit function theorem. Let :math:`N` be the states that are +neither the pivot of a conserved total (below), nor an input, nor at zero at rest, and +:math:`f_N` their balances. The tangency rows are + +.. math:: + + J_x\, \xi_{x_N} + J_\theta\, \xi_\theta = 0, \qquad J_x = \partial_{x_N} f_N, \quad + J_\theta = \partial_\theta f_N, + +where the columns of :math:`\partial_x f` at the pivots are columns of :math:`J_\theta`, since +the resting value of a pivot is a coordinate; inputs and states at zero enter as rows that hold +them at zero. One balance per total is dropped, that of the pivot. This is exact: each total +:math:`\sum_i a_i x_i` gives :math:`\sum_i a_i f_i = 0`, and the coefficient matrix +:math:`C_P` of the totals at the pivots is invertible, so :math:`f_P = -C_P^{-1} C_N f_N` +vanishes wherever :math:`f_N` does. The full :math:`\partial_x f` is singular with a total, the +reduced :math:`J_x` is square; it is the *resting Jacobian*. A proven rank also needs the +resting Jacobian of every condition solved at the point itself invertible at the base point; +otherwise the rank is a lower bound. + +**Branches.** A *branch* is an irreducible component of :math:`W` over :math:`\mathbb{Q}`. By +default the first condition draws the resting states and solves the balances for the +*turnover rates*, one rate per state that enters the balance of the state linearly (the *forward seed*); +this names the component that the drawn values parametrize. Where a balance has several roots +over :math:`\mathbb{F}_p`, the first nonzero one found is taken and named in +``info["branches"]``: by the factor over :math:`\mathbb{Q}(\theta)` it solves where a balance +splits into factors, else as *conjugate*. Conjugate means that the lexicographic Gröbner basis +of the balances, states at zero removed, has at a point the *shape* +:math:`x_1 - g_1(x_n), \dots, x_{n-1} - g_{n-1}(x_n), P(x_n)` with an irreducible *eliminant* +:math:`P`. Other points take their root on that branch or, without one, are left out. +Conjugate roots have equal rank, and an eliminant irreducible at a point is irreducible over +:math:`\mathbb{Q}(\theta)`. + +**Zero at rest.** A state rests at zero when the right-hand side of the state, with the inputs at zero, is +linear in it with a coefficient that is nonzero while the other such states are zero. In a +reaction network, a species that is consumed but not produced rests at zero as the single +reactant of a consuming reaction, as does the single reactant of positive weight in a reaction +that lowers a weight no reaction raises (a *sink*; a weight assigns each species a number in +:math:`[0, 1]`). Of several such reactants, as in :math:`A + B \to 0`, the first is set to zero +(``info["branches"]``). A state with right-hand side zero at rest, and the pivot of a conserved +total (below), has a free resting value, the initial value. Rates are read at generic values, +so a catalyst at rest is nonzero. Where the coefficient of a state of a total at zero holds +other states, as for :math:`\dot B = B\,(k_1 A - k_2)`, the resting set has a second branch +with the state away from zero, where the coefficient vanishes; ``info["branches"]`` names it, +and ``free_initial`` naming the state takes it. ``free_initial`` naming a state at zero on every +resting state is an error. + +**Conserved totals.** A linear combination :math:`T = \sum_i a_i x_i` of states that the +right-hand sides conserve is a *total*; the coefficients may hold parameters, such as volumes. +Totals are read from the stoichiometry of a reaction network or from the linear laws of the +ODEs, unless given. The basis read off consists of nonnegative laws where these span the laws, +the extreme rays of the cone of nonnegative laws with the fewest species first, so that it does +not depend on the order of the species and each total is positive on the parameter space; a +total with coefficients of both signs is named in ``info["limits"]`` under ``reduce_cq``, which +takes it positive. + +Under ``equilibrate`` each total leaves one resting value free, which one species of the total, +the *pivot*, holds as initial value. The pivots form a set :math:`P` of species, one per +independent total, with an invertible coefficient matrix :math:`C_P`. ``free_initial`` names +them; otherwise they are chosen by the structure of the model, in this order: not at zero at +rest, not an input and not the base of a free power, a coefficient without parameters, in the +fewest totals, observed. Where several sets tie by these criteria, up to six are analyzed and the +result with the best rank status, rank, levels and kinds is kept, so that the result does not +depend on the names or the order of the states and totals. With another pivot the resting +value of another state is the coordinate, so the generators differ, but their spans agree after +the map to the parameters and all resting states at a common resting point. Where directions +stay open, other valid sets are tried as well. ``info["settings"]["free_initial"]`` holds the +pivots of the result. + +With ``reduce_cq`` the pivots are eliminated instead, :math:`x_P = C_P^{-1} (T - C_N x_N)`, and +the values :math:`T` of the totals become coordinates (``info["settings"]["eliminated"]``); the +pivots are chosen as above, except that unobserved species are eliminated first. An event that changes +a species :math:`x_i` of a total changes the total by :math:`a_i\,(E(x_i) - x_i)`, with +:math:`E(x_i)` the value after the event; like every event value it reads the states before the +events. The total is then a state without dynamics, so the segments after the event see the new +total, and an event on an eliminated species changes only the totals. Both parametrizations +describe the same resting variety, so ``reduce_cq`` gives the same rank and the same span of the +directions, mapped to the same space, as the pivots. + +**Rank at the resting start.** Under ``equilibrate`` the rank is that at the declared resting +start, whose coordinates fix the level set of each total. The ceiling of the order certificate +(:ref:`sufficient-lie-order`) is the generic rank on the whole resting variety, so the computed rank +cannot exceed the rank along the trajectories from the declared start; it can only fall short of +it, and is then reported as a lower bound (a singular resting Jacobian, an order not proven +sufficient) or covered by the error bound (a random point). The exact scalings bound the rank +from above, so a rank at that bound proves the order sufficient without random points, with +``info["order_bound"]`` zero. + +**Diagonal start.** Conditions sharing :math:`\theta` have coupled resting states. Rank and +kernel are generic on the joint variety of the conditions, +:math:`\{(\theta, x_1, \dots, x_C) : (\theta, x_c) \in W_c\}`, so any point of it over +:math:`\mathbb{F}_p((\varepsilon))` off an exceptional subvariety gives them. symident seeks a +set :math:`P_Z` of free parameters whose value zero makes all conditions equal to the first, +and the largest set :math:`X_Z` of states whose value zero is then invariant; at +:math:`\theta_{P_Z} = 0`, :math:`x_{X_Z} = 0` the forward seed is a resting point +:math:`\hat z` of all conditions. Along :math:`\theta(\varepsilon) = \hat\theta + \varepsilon\, +\zeta`, with :math:`\zeta` the values of :math:`P_Z` at the sample point, Newton steps lift each +condition to a power series, + +.. math:: + + x_{c,k} = -J_c(\hat z)^{-1}\, [\varepsilon^k]\, f_c\big(x_{c, 0`, +:math:`j = 1, \dots, n_\gamma`. The *declared signs* are the domain declared by ``positive`` +and the start sides declared by ``regimes``. Conditions that the declared signs decide are +resolved; a factor of odd multiplicity of an undecided one is a *switching function* +:math:`\gamma_j`, with *switching surface* :math:`\Gamma_j = \{\gamma_j = 0\}`. A sign vector +:math:`\sigma \in \{+1, -1\}^{n_\gamma}` gives a smooth *regime* :math:`(F_\sigma, h_\sigma)`, +the field and the observables where every :math:`\gamma_j` has the sign :math:`\sigma_j`. A +*root event* (``root`` in place of ``time``) adds the root expression as a switching function +and resets the target state, the *event state*, on :math:`\Gamma_j`. + +**Regimes.** A direction counts only if it is a symmetry of every regime the declared signs +allow. Without ``regimes``, every sign vector counts unless the declared positivity decides +the sign of :math:`\gamma_a - \gamma_b` or :math:`\gamma_a + \gamma_b` against it; none is +dropped for parameter values or for not being reached, so the result holds for every initial +state. A parameter that acts only in a regime excluded by a decided condition stays a +coordinate, with the unit direction :math:`\partial_{\theta_i}` as exact direction. Each +allowed regime enters as a *copy* of the model, i.e., the rows of that regime with initial +states of their own and the parameters shared, from the start of the condition and, with +other regimes allowed, as a copy switched into it (``info["switching"]["conditions"]``). + +**Entry points.** The state at a switch is unknown, so a direction counts only if it is a +symmetry from every point of the surface. A state that starts at zero in every condition, that +every allowed regime keeps at zero with finite derivatives in such states, and that no later +event moves, is zero along every trajectory. It is dropped (``info["zero_states"]``), and a +coordinate that only such states read is a separate direction :math:`\partial_{\theta_i}`; +``info["limits"]`` names a condition with further such states. For a copy switched into a +regime, other invariant sets of the start, such as the level set of a conserved total, are not +used, so the rank of a model with switches can exceed the rank along the trajectories from the +declared start. This concerns switches only; under ``equilibrate`` without switches the rank +cannot exceed it (:ref:`steady-states`). + +**Visibility.** Two regimes :math:`\sigma, \sigma'` are *neighbors* at :math:`\Gamma_j` when +they differ only in the sign of :math:`\gamma_j`. The switch is *visible* when for some +neighbors, observable :math:`h_i` and order :math:`k` + +.. math:: + + \big(L_{F_\sigma}^k h_{\sigma,i} - L_{F_{\sigma'}}^k h_{\sigma',i}\big)\big|_{\Gamma_j} + \ne 0 . + +A nonzero Taylor coefficient at a point of :math:`\Gamma_j`, modulo a prime, proves this. The +switch is *invisible*, or *hidden*, when for every pair the observables agree and every state +reaching them has the same right-hand side, so that every Lie derivative agrees, and +*undecided* otherwise. A root event surface counts as visible. + +**The rule.** Let :math:`\tau_e` be the time and :math:`E_e` the map of the states of event +:math:`e`. A direction :math:`v` is reported non-identifiable when, in every condition, it lies +at the start in a distribution :math:`\mathcal{D} = \operatorname{span}\{Y_1, \dots, Y_m\}` of +fields on parameters and states with + +.. math:: + + [Y_i, F_\sigma] \in \mathcal{D}, \qquad Y_i(h_\sigma) = 0 \qquad + \text{for every regime } \sigma, + +.. math:: + + Y_i(\gamma_j) = 0 \ \text{on } \Gamma_j \ \text{for every visible surface}, \qquad + Y_i(\tau_e) = 0, \qquad \mathrm{D}E_e\, Y_i(z) \in \mathcal{D}\big(E_e(z)\big) \ + \text{for every event and reset}, + +and, at a surface that is not visible and that some :math:`Y_i` moves, for every pair of +neighbors + +.. math:: + + \big(F_\sigma - F_{\sigma'}\big)\big|_{\Gamma_j} \in \mathcal{D}, \qquad + \big(h_\sigma - h_{\sigma'}\big)\big|_{\Gamma_j} = 0 . + +The events and resets are those of the condition: an event that names conditions (``cond``) acts in +those only. No :math:`Y_i` moves a fixed symbol, an input or time. The direction is +:math:`v = \big(\xi, X(x_0)\big)`, with the derivative of the initial values along :math:`X` as +state part (under ``equilibrate``, of the resting state of each regime). Along every regime +flow, :math:`v` stays in :math:`\mathcal{D}` and keeps the observables to first order; at a +visible surface :math:`v` is tangent, so the crossing time stays; at a hidden one the crossing +may move, but the jump lies in :math:`\mathcal{D}` and the observables agree. The rule therefore +never reports a direction that changes the observables, for any sequence of the listed regimes. + +**Lower bound.** The directions of the rule satisfy the rows of copies of the model, whose rank +bounds the rank from below: + +- each regime from the start of each condition, with the events of the condition; +- each regime from a generic point of each visible surface linear in a state, where a direction + of the rule is tangent to the surface; +- each regime from a generic point, when a switch of the condition is not visible; +- each copy switched at a fixed time into every other regime of the condition, with outputs + along *words* of two regimes, :math:`L_{F_\sigma}^a L_{F_{\sigma'}}^b h_{\sigma'}`; +- the switching time :math:`t_j(\theta)` of every visible switch in time alone. + +The *fresh coordinates* are the entry states of the copies that start at surface points. The +kernel of all these rows, projected onto :math:`\theta`, contains every direction of the rule; +a kernel dimension :math:`k_\Delta` gives the lower bound :math:`d - k_\Delta`. A minor that is +nonzero at the sample point modulo a prime is nonzero as a rational function over +:math:`\mathbb{Q}`, so the rank modulo a prime at a point bounds the generic rank from below. +The projection off the fresh coordinates is a difference of two ranks, +:math:`\operatorname{rank} J - \operatorname{rank} J_F` with :math:`J_F` the fresh columns, and can +rise at a special point. It is proven where the fresh columns that enter a row have full column +rank at the sample point: generically :math:`\operatorname{rank} J_F` is then their number, and +:math:`\operatorname{rank} J` at the point bounds the generic one from below. A fresh column +enters no row when the state it starts reaches no observable of the copy. The reach is taken +with the *held* states of the copy at their start values: a set of states whose start values +are free of fresh coordinates and whose right-hand sides vanish identically there, with finite +derivatives, in every regime of the copy. Such states keep their start values, so every Lie +derivative of the copy is one of the fields restricted to that level set. + +Rows of fewer copies keep every direction of the rule in their kernel, so their projection is +an upper bound on the dimension of the rule. The copies without fresh coordinates are taken +first: rows of full rank there prove the full rank, and no other copy is stacked. Otherwise, +where the fresh columns of some start points drop rank at the sample point, the rows of the +other copies give a proven dimension; equal to the dimension of all rows, it proves the +projection. Else the projection is checked with the kernel at a point uniform modulo the +verification prime, and proven there by the same column test. With equal dimension there and +no such proof it is ``verified``, with the chance by :cite:p:`Schwartz1980` that a maximal minor of the +stacked rows or of their fresh columns vanishes there, else a lower bound +(``info["projection"]``, ``info["rank_status"]``). + +**Upper bound.** The candidates are the scalings of :ref:`scalings`, the closed forms of the kernel +of the rows above and the unit direction :math:`\partial_{\theta_i}` of every coordinate; those +failing a condition of the rule are dropped until the family passes. Each identity is tested at +a point with rational coordinates and then proven by symbolic simplification to zero; +:math:`\ell` candidates left, independent at such a point, bound the rank by :math:`d - \ell`. +If :math:`\ell = k_\Delta`, the rank is :math:`d - k_\Delta` and the candidates span the +non-identifiable directions; otherwise :math:`d - k_\Delta` is a lower bound, +``info["switching"]["uncertified"]`` names the rejected candidates, and the unproven kernel +directions, which satisfy only necessary conditions, appear under +``info["switching"]["candidates"]``, not as symmetries. For an undecided switch the rule accepts +tangency or a hidden jump and the rows omit the surface, so both bounds stay valid. + +**Unknown inputs.** The input is continuous where a trajectory crosses a surface and analytic +between crossings; the derivatives of the input may jump at a crossing. The input direction +:math:`G_\sigma = \partial_w F_\sigma`, over the inputs that no observable of :math:`\sigma` +reads, joins the bracket condition, + +.. math:: + + [Y_i, F_\sigma] = \sum_k c_{ik}\, Y_k + a_{i\sigma}\, G_\sigma , + +with rational functions :math:`c_{ik}` and :math:`a_{i\sigma}`, and +:math:`v = \sum_i \beta_i Y_i` changes the input in :math:`\sigma` by :math:`-\sum_i \beta_i +a_{i\sigma}`; an input that an observable reads stays unchanged. Where :math:`G_\sigma \in +\mathcal{D}` the change is free. Otherwise it must not jump where a trajectory crosses +:math:`\Gamma_j` from :math:`\sigma` into a neighbor :math:`\sigma'`: on :math:`\Gamma_j`, + +.. math:: + + a_{i\sigma'} - a_{i\sigma} + - \frac{Y_i(\gamma_j)}{F_\sigma(\gamma_j)} \sum_k e_k\, a_{k\sigma'} = 0 , + \qquad F_\sigma - F_{\sigma'} = \sum_k e_k Y_k , + +the last term counting only at a hidden surface that :math:`Y_i` moves, whose crossing then +shifts. A switch is visible only through orders :math:`k \le r_i`, with :math:`r_i` the lowest +order at which an input can enter :math:`L^k h_i`, read from the symbols of each order; higher +orders hold input derivatives. The jets of each copy are nuisance coordinates (see +:ref:`inputs`), with a start of their own per copy and, at a surface point, the +input value shared by the two neighbors. A copy from a generic point of each regime replaces the +copy switched at a fixed time, which would restart the input off the surfaces, where the changes +of two regimes differ. The rank status is the weaker of the projections off the jets and off the +fresh coordinates. The rule holds per condition, so each condition needs a separate input, +renamed in ``conditions``. + +**Listed regimes.** With ``regimes``, the rule, the rows and the candidates use the listed +regimes of each condition, and a surface counts only with listed regimes on both sides. +Parameters of other regimes stay coordinates and are reported non-identifiable. A sign of +:math:`\gamma_j(x_0)` decided by the declared signs must agree with the first entry, else an +error is raised; an undecided one is declared by ``regimes`` and listed under ``declared`` in +``info["switching"]["conditions"]`` and in ``info["assumptions"]["starts"]``. + +**Limits.** Each of the following is an error, never a result: + +- a surface in the parameters alone whose side ``regimes`` does not give; +- a condition on a switched expression; +- more than 4096 sign vectors; +- ``gauge``, ``reduce_cq``, ``free_initial``, ``engine="symbolic"``; +- a state named ``time``; +- under ``equilibrate``, a resting state without closed form; +- an infeasible listed regime, or a start that contradicts the initial values; +- with unknown inputs: an input read by several conditions, a switch on an input, an event after + the start, an initial or event value that reads an input. + + +.. _petab-mapping: + +PEtab problems +-------------- + +:func:`~symident.read_petab` maps a PEtab problem :cite:p:`Schmiester2021` onto these elements. +Each experiment with measurements is one condition; the estimated parameters are the +coordinates, the other parameters take their nominal values. A preequilibration is the resting +start of ``equilibrate`` (:ref:`steady-states`), with the preequilibration condition in place of +the inputs at zero, and the condition of the experiment as events at the start; it has to be part +of every experiment or of none, since all conditions start alike. + +An experiment without preequilibration whose measurements are all at :math:`t = \infty` is a +*readout at rest*. The output of the experiment is the observables at the resting state :math:`x^\ast(\theta)` of +the condition, :math:`h(x^\ast(\theta), \eta(\theta))`, which is the output of the experiment +under the premise that the trajectory from the start of the condition converges to that resting +state. The experiment enters as a resting start under the condition of the experiment, with no +event after it: the trajectory stays at rest, the output is constant, and only the rows of order +zero at the resting state enter, with the tangency rows of :ref:`steady-states`. Readouts at rest and preequilibrated experiments mix; a +readout at rest next to an experiment that starts without preequilibration is read as a +trajectory, with a warning. diff --git a/docs/method/global.rst b/docs/method/global.rst new file mode 100644 index 0000000..5430e95 --- /dev/null +++ b/docs/method/global.rst @@ -0,0 +1,1034 @@ +Global analysis +=============== + +Local identifiability leaves finitely many coordinate values with the output of a generic one. +A *discrete symmetry* is a map :math:`\sigma` with :math:`\Psi_N(\sigma(\theta)) = +\Psi_N(\theta)` and :math:`\sigma(\theta) \ne \theta`, which no generator shows. It matters +for estimation only where :math:`\sigma(\theta) \in \Theta`: :math:`\theta \mapsto -\theta` +of a positive coordinate that enters as :math:`\theta^2` is no symmetry of the model on +:math:`\Theta`. Counts over the algebraic closure, as in :cite:p:`Hong2020,ReyBarreiro2023`, +include such values; the global analysis (``detect(mode="global")``, +:meth:`~symident.Symmetries.discrete`) counts in :math:`\Theta` as well. + +The global analysis sets up the fiber of a generic point as a polynomial system +(:ref:`fiber`, :ref:`fiber-features`, :ref:`rational-form`), counts the points modulo a prime and +reconstructs the maps between them (:ref:`maps`), and certifies the count, exactly by the field of +the output coefficients (:ref:`exact-count`), with an error bound over :math:`\mathbb{Q}` +(:ref:`verified-count`, :ref:`several-experiments`), or not (:ref:`certificates`). Points +proposed numerically and certified by interval arithmetic (:ref:`monodromy`) propose maps only. + +.. _fiber: + +The fiber +--------- + +A model with directions is reduced first (:func:`~symident.reduce`); the reduced model is +locally identifiable, so the *fiber* :math:`\Psi_N^{-1}(\Psi_N(\theta^\ast))` is finite. The +fiber at a point :math:`\theta^\ast` is the solution set of the polynomial system that equates the +Taylor coefficients of the observables up to order :math:`N` with their values at +:math:`\theta^\ast`, away from zeros of coordinates and denominators. msolve +:cite:p:`Berthomieu2021` counts the points of the system over the algebraic closure modulo a prime, an upper bound +for the size of the fiber of the model, which more equations can only lower. As in SIAN +:cite:p:`Hong2020`, the derivatives of the states at the start are unknowns of the system, tied by the +Taylor coefficients of :math:`D(x)\,\dot x = N(x)` and :math:`E(x)\, g = M(x)`. Every +observable starts one order above the highest of the orders whose next coefficient adds no rank to +the Jacobian in the coordinates: at a given start, a coefficient that adds no rank can still remove +points. The orders rise together until the count is the same at two successive steps, or equals +the size of the orbit of the proven candidates, one if there are none, which no higher order +changes, since more equations give a fiber within the one before and the orbit stays in it. The +count of a block is the number of distinct values of a random linear form in the coordinates on +the points of the block: msolve gives the reduced Gröbner basis, the standard monomials span the +quotient, and the number of distinct eigenvalues of the multiplication by the form is the degree of +the square-free part of the minimal polynomial of that multiplication. Points that differ only in the derivatives of the states, or that are +multiple, count once. The series of a known input is a number, a variable +that a linear equation fixes to a number is substituted, a derivative that enters one equation +only, there linearly with a numeric coefficient, leaves with that equation, and the rest splits +into blocks without a shared variable, whose fibers multiply. msolve runs over :math:`\mathbb{F}_p` +with the probabilistic sparse linear algebra of msolve. + +*Stages.* A block is counted stage by stage. Let :math:`A` be a set of variables of the block, :math:`P_A` +the equations and factors of the saturation that read only variables in :math:`A`, and :math:`P_R` +the others. A point of the block is a pair :math:`(a, r)` with :math:`P_A(a) = 0` and +:math:`P_R(a, r) = 0`, the factors nonzero, so the points of the block are the disjoint union over +the points :math:`a` of :math:`P_A` of the points of :math:`P_R(a, \cdot)`, and the count of the +block is the sum of the counts of the rest at each :math:`a`. This holds for every :math:`A`; the +block triangular form of the incidence of equations and variables :cite:p:`Dulmage1958` only proposes one: +a maximum matching of equations to variables, the graph in which a variable points to the variables +the matched equation of the variable reads, and as :math:`A` the smallest proper set closed under this graph that +holds a strongly connected part of more than one variable, so that the equations in :math:`P_A` +match every variable of :math:`A`. The block is first counted at once under an eighth of ``msolve_entries``, +since the rest after a stage is often small. Then msolve gives the rational parametrization of +:math:`P_A`; where every distinct root of the eliminating polynomial lies in +:math:`\mathbb{F}_p` (in :math:`\mathbb{Q}` for the count over :math:`\mathbb{Q}`, at most 16 +roots), each point is substituted, the fixings above run again, and the rest is counted by stages; +otherwise the block is counted at once. Over :math:`\mathbb{Q}` the stage is first +solved modulo a prime and skipped where a point lies outside :math:`\mathbb{F}_p`, since rational +points reduce to points in :math:`\mathbb{F}_p` for a prime that divides no denominator; the choice +of the route never changes the count. Points :math:`a` that differ only in the derivatives of the states count apart, so +the sum is never below the number of points with distinct coordinates. + +.. _fiber-features: + +Conditions, events, resting states and switches +----------------------------------------------- + +The conditions are stacked as in the local analysis: each has separate derivatives, the +coordinates are shared. After an event the gaps are :math:`\varepsilon\, \Delta t_i^0` as in +:ref:`conditions-events`: the state at the end of a gap is the series of the segment before +evaluated at :math:`\varepsilon\, \Delta t_i^0`, the event maps it to the start of the next +segment, and every coefficient after the event is a power series in :math:`\varepsilon`, kept up +to the *gap order*, which rises with the order. A segment whose start holds coordinates, an event +at an estimated time, is expanded at the start of the condition on the flow continued backward, +so that the coefficients of the segment depend on the time of the event. Under ``equilibrate`` the start of a +condition is the solution of the balances over :math:`\mathbb{Q}(\theta)`, exponentials of the coordinates +included, with the inputs at zero, +the states that are coordinates at their free resting value and the states without dynamics at +their initial value; where the balances have more than one rational solution, the one with the +most states away from zero, and none without one rational solution. States that no observable +depends on are left out. With switches, as in :ref:`switching`, each condition enters from the +start in the regime of the start, decided at a random point, and each allowed regime as a copy +whose start is free on a switching surface :math:`\gamma_j = 0` to an allowed neighbor: at the point +the surface is solved for a state in which it is linear, and in the fiber +:math:`\gamma_j(z', \theta') = 0` is an equation; the clock and the jets of known inputs of a copy +start at known values. A map is ``exact`` with a map of the states in every regime that takes each +surface to itself, :math:`\gamma_j(\varphi(x), \sigma(\theta)) = c\, \gamma_j(x, \theta)` with +:math:`c` free of the states and positive on :math:`\Theta`. A switch on the parameters alone puts +the model in one regime and is not handled. A map reconstructed from the fiber is +checked on the coefficients four orders further up, in :math:`t` and in :math:`\varepsilon`; a +map that fails shows a fiber too large at that order, and the orders rise. + +.. _rational-form: + +Rational form of the fiber +-------------------------- + +The fiber needs a model rational in the states and coordinates. Three rewrites before the count +keep the fiber. A coordinate :math:`\theta` that enters only through :math:`b^{c\theta}`, with +rational :math:`c`, is read as :math:`X = b^{\theta/L}`, :math:`L` the common denominator of the +exponents, a bijection of :math:`\mathbb{R}` onto the positive reals; a map is reported back as +:math:`\theta' = L \log_b \sigma(X)`, so a swap stays a swap and a discrete scaling becomes a +translation. An observable :math:`h` for which :math:`e^{c h}` is rational, :math:`c \in \{1, +\log 10, \log 2\}`, is replaced by :math:`e^{c h}`, one of the form :math:`e^{r}` by :math:`r`, +and an odd power :math:`r^{p/q}` by :math:`r`: these maps are injective where the observable is +real, so two values of the coordinates have the same output before the rewrite if and only if +they have it after. A factor :math:`e^{a t}`, with :math:`a` free of the states and the clock, +becomes a state :math:`E` with :math:`\dot E = a E` and :math:`E(0) = 1`, whose unique solution it +is; this needs conditions that start at :math:`t = 0`. A coordinate :math:`\theta` that +enters only through :math:`e^{c/\theta}`, with rational :math:`c`, is read as :math:`X = e^{a/\theta}`, :math:`a` +the positive rational greatest common divisor of these :math:`c`, so that :math:`X` enters with integer powers; +:math:`\theta \mapsto X` is a bijection of the positive reals onto :math:`(1, \infty)` and of the negative reals +onto :math:`(0, 1)`, and a map is reported back as :math:`\theta' = a / \log \sigma(X)`. The counts in the domain +take :math:`X > 0`, which holds :math:`\theta` real but not positive. A state without dynamics that starts at a +number and that every event sets to a number, such as a clamped input, is that number within each segment, and is +substituted there where a non-rational term reads it. ``info["discrete"]["rewrites"]`` lists the rewrites, and a +term that stays non-rational is named in the error. + +**Non-rational terms.** A term :math:`\varphi(\psi)` of the states that these rewrites +leave, :math:`\varphi` an exponential, a logarithm or a power :math:`b^\mu` with a non-integer +exponent and :math:`\psi` rational, becomes :math:`W \nu` (:math:`W + \nu` for the logarithm), +innermost first, with a new state :math:`\nu` and a new coordinate :math:`W = \varphi(\psi_0)`, +:math:`\psi_0` the value at the start: + +.. math:: + + \nu = e^{\psi - \psi_0},\ \Big(\frac{b}{b_0}\Big)^{\mu},\ \log \frac{\psi}{\psi_0}, \qquad + \dot\nu = \nu\, \dot\psi,\ \ \mu\, \nu\, \frac{\dot b}{b},\ \ \frac{\dot\psi}{\psi}, \qquad + \nu(0) = 1,\ 1,\ 0 . + +A term of the coordinates alone becomes a new coordinate :math:`P`, the :math:`W` of a term with the +same start or an integer power of it, and a coordinate that no +equation reads afterwards is dropped where one :math:`P` determines it on the positive reals +(:math:`b^\mu` or :math:`\log b` with :math:`b = c\, \theta^{\pm 1}`, or :math:`e^{a \theta^{\pm 1} + d}`, +with :math:`c, \mu, a, d` free of :math:`\theta`). A positive state :math:`x` that the model reads only through +:math:`\log x`, through the factor :math:`x` of :math:`\dot x = x R` and through observables :math:`x^k` with an +integer :math:`k \neq 0` is replaced first by :math:`L = \log x`, with :math:`\dot L = R`, the observable +:math:`k L` and the start :math:`P = \log x_0`. This keeps the fiber: :math:`x = e^L` is the unique positive +solution, :math:`x^k \mapsto k \log x` is injective on the positive reals, and :math:`x_0 \mapsto P` is a +bijection onto the reals, so :math:`x_0` is dropped and no relation between a :math:`W` and :math:`x_0` is lost. A term with a known input or the clock, and a root or rational +power, whose start is algebraic, are not rewritten. The *relaxed model* is rational in +:math:`\tilde\theta = (\theta, W, P)`, and the output of the model is the relaxed output on the graph +:math:`\Gamma` of :math:`\theta \mapsto \omega(\theta)`, the starts of the new coordinates. +``discrete()`` counts the relaxed model modulo the continuous directions, as above, and +``info["discrete"]["relaxed"]`` lists the terms, the starts and the dropped coordinates. + +*Proposition.* Suppose (a) every direction of the relaxed model that moves a :math:`W` is exact, a +scaling or a shift of the :math:`W` it moves by constants, and moves no coordinate read by a start +:math:`\omega`, with an invertible matrix of the weights and shifts on the :math:`W` these +directions move, (b) no direction moves a coordinate read by the start +of a :math:`W` that no scaling moves, and (c) these starts are algebraically independent over +:math:`\mathbb{Q}(\theta)`. Then at a generic point the fiber of the model has at most :math:`k` +connected components, :math:`k` the count of the relaxed model modulo the continuous directions, and exactly +:math:`k` where :math:`k = 1` or where the exact maps of the relaxed model that fix every +:math:`W` and every coordinate read by a start have an orbit of :math:`k` points. + +*Proof.* By (a) these directions reach every value of the :math:`W` they move from any point (every +positive value for a scaling), +and by (c) the image of :math:`\theta \mapsto (\theta, \omega(\theta))` on the other :math:`W` is +Zariski dense, so a generic :math:`\theta` lies on a generic orbit of the relaxed model. A point +:math:`\theta'` of the fiber of the model gives the point :math:`(\theta', \omega(\theta'))` of +the relaxed fiber. On an orbit :math:`O` of the relaxed fiber, the :math:`W` that no scaling +moves and, by (b), the coordinates their starts read are constant, so either no point of +:math:`O` or every point after one group element meets these starts; the element :math:`s(q)` of +the directions of (a) that brings :math:`q \in O` to the starts of the moved :math:`W` is unique +and continuous in :math:`q` by (a), since these directions fix what the starts read. So :math:`O \cap \Gamma` is +empty or the image of the connected :math:`O` under :math:`q \mapsto s(q)\, q`, and the fiber of +the model is the union of at most :math:`k` connected sets. A map that fixes the :math:`W` and +what the starts read takes :math:`\Gamma` to itself, so an orbit of :math:`k` points meets +:math:`k` relaxed orbits on :math:`\Gamma`. :math:`\square` + +For exponentials alone, (c) holds where the Jacobian of the exponents :math:`\psi_0` in the +coordinates has full rank at a random point: an integer combination of the :math:`\psi_0` that +is constant has a zero differential, and the lemma of Kolchin and Ostrowski in :ref:`non-rational` +gives the independence. For logarithms alone the same holds with :math:`\mathrm{d} \log +\psi_0`: a combination :math:`\sum_i c_i \log \psi_{0,i}` that is rational has a differential with +simple poles only, so it is constant. Otherwise (c) is a premise, named in +``certificate["premise"]``, and the certificate is ``axiom``. Where (a) or (b) fails, +``certificate["relaxed_why"]`` names the direction, the count is not reported (``count`` None, +the relaxed count under ``relaxed["count"]``), and the certificate is ``open``. + +**Free powers of a state at 0.** A power :math:`x^{c_0 + c\alpha}` of a state +:math:`x` that starts at the number 0, with integers :math:`c_0 \ge 0`, :math:`c > 0` and a +coordinate :math:`\alpha` declared positive, has no start :math:`\psi_0 \neq 0` to relax. With +:math:`k` and :math:`c_x` as in :ref:`singular-starts`, :math:`x^\alpha = Z N` with :math:`Z = +c_x^\alpha` and the *normalized power* :math:`N = (x/c_x)^\alpha = \tilde S Q`, :math:`\tilde S = +t^{k\alpha}`, a series in :math:`t` and :math:`\tilde S` whose coefficients are polynomials in +:math:`\alpha`, the coefficients of :math:`x` and :math:`1/c_x`. The model with :math:`x^\alpha = 0` +gives the coefficients of :math:`x` of layer 0; :math:`k` is the first order at which the coefficient is +nonzero at a random point, which shows it nonzero as a function, and the coefficients below +:math:`k` are computed over :math:`\mathbb{Q}(\theta)` and vanish identically. + +:math:`Z` leaves the model in one of three ways. (i) It cancels against a factor +:math:`c_x^{-\alpha}`: the model is written in :math:`N`. (ii) The model is invariant under +:math:`Z \mapsto \lambda Z`, :math:`P_i \mapsto \lambda^{q_i} P_i` for the new coordinates +:math:`P_i = b_i^{q_i \alpha}` of the relaxation above: then the output depends on +:math:`Z` and :math:`P_i` only through :math:`\tilde P_i = P_i Z^{-q_i} = (b_i / c_x)^{q_i \alpha}`, +the model is taken on the slice :math:`Z = 1` with :math:`\tilde P_i` in place of :math:`P_i`, and a +:math:`\tilde P_i` determines a dropped coordinate as before where :math:`c_x` is positive on the +domain and free of it. The map from :math:`\theta` to the slice is then a bijection, so this step +needs no premise. (iii) Otherwise :math:`Z` is a new coordinate :math:`W` with the start +:math:`c_x^\alpha`, under the proposition above. :math:`c_x` must be positive on the domain by the +declared signs and free of the known inputs. + +In the prolonged model each state has the coefficients :math:`x_{n,m}` of index :math:`n` and +layer :math:`m`, standing for :math:`t^{n - km + km\alpha}`, and the derivative of index :math:`n` +is :math:`\lambda_{n+1,m}\, x_{n+1,m}`, :math:`\lambda_{n,m} = n - km + km\alpha`. The +coefficients :math:`Q_n` are unknowns with :math:`n\, c_x Q_n = \sum_{j=1}^n (\alpha j + j - n) +x_{k+j} Q_{n-j}`, :math:`Q_0 = 1`, and :math:`N` has :math:`Q_{n-k}` in index :math:`n` and layer +:math:`m+1` for layer :math:`m` of :math:`Q`; :math:`c_x = x_{k,0}` is saturated. Let :math:`v_N = 0` +and :math:`v_i = 1 + \min_j v_j` over the states and :math:`N` that the right-hand side of state +:math:`i` reads, and :math:`v_h = \min_j v_j` over those an observable reads. By induction on the +index, every term of layer :math:`m \ge 1` of state :math:`i` has :math:`n - km \ge v_i` where +the base has :math:`v_x \ge k`, so that every term of :math:`Q` has :math:`n - km \ge 0`; a power +with :math:`v_x < k` enters the dynamics of the base below :math:`t^k` and is refused. Unknowns +exist only for these terms, layer :math:`m` up to :math:`\lfloor N/k \rfloor` at order :math:`N`, +and only up to the index that the outputs read: an observable reads the states at the order of the observable, the +equation of index :math:`n` of a state reads the right-hand side at index :math:`n - 1`, and +:math:`N` reads the base at the same index. The unknowns above are determined by the ones below and +change no count. + +**Lemma.** Let :math:`c_x` have one sign on the domain, and let the coefficient :math:`d = +h_{v_h + k, 1}` of an observable :math:`h` have one sign on the domain. Then every point +:math:`\theta'` of the domain with the output of a generic :math:`\theta` has :math:`\alpha' = \alpha`. + +*Proof.* The expansions converge (:ref:`singular-starts`) and have exponents :math:`e = (n - km) + km +\alpha'`. At :math:`\theta'`, :math:`c_x \neq 0` gives the same :math:`k`; the terms of layer +:math:`m \ge 1` have :math:`n - km \ge v_h`, so for :math:`\alpha' > 0` the least exponent among +them is :math:`e' = v_h + k\alpha'`, attained by :math:`d(\theta') \neq 0` alone. Likewise +:math:`e = v_h + k\alpha` with :math:`d(\theta) \neq 0`, and :math:`e \notin \mathbb{Q}` for +generic :math:`\alpha`. The layers 0 have integer exponents. If :math:`e < e'`, the term +:math:`t^e` has the coefficient :math:`d(\theta) \neq 0` at :math:`\theta` and none at +:math:`\theta'`, as :math:`e` is no integer and lies below :math:`e'`; this contradicts the lemma of +:ref:`singular-starts`. If :math:`e' < e` and :math:`k\alpha'` is no integer, the same holds for +:math:`t^{e'}`. If :math:`k\alpha'` is an integer, every exponent at +:math:`\theta'` is an integer and :math:`t^e` again has no coefficient at :math:`\theta'`. So :math:`e += e'` and :math:`\alpha' = \alpha`. :math:`\square` + +The coefficients :math:`c_x` and :math:`d` are computed over :math:`\mathbb{Q}(\theta)`, and one +sign means numerator and denominator positive or negative by the declared signs; where this is not +shown the condition is a premise, ``certificate["premise"]``, and a count otherwise ``verified`` is +``axiom``. The fiber then has the equation :math:`\alpha' = \alpha` and the equations of all +layers, and the bound of the verified count takes the degrees of all of them. The maps are +reconstructed and checked as before but have no state maps, since :math:`N` is no rational +function of the states, and the exact count of the field of the outputs is not taken. +``info["discrete"]["start_powers"]`` names per power :math:`k`, :math:`c_x`, the observable, +:math:`d` and the premises. One such power per condition is taken, without events. + +**Resting states inside a term.** Under ``equilibrate`` the start of the relaxed model is a resting +state, and a state :math:`x_H` inside a transcendental term has a resting value that solves a +transcendental balance. Such resting values :math:`R_H` become coordinates of a *resting chart*: the +transcendental terms at rest are leaves :math:`W = \varphi(\psi(R_H, \theta))`, the balances of the other states +are solved one at a time where each is linear in the state it belongs to, and one coordinate :math:`p_h` per state of +:math:`H` that enters the remaining balances linearly is solved from them, with an invertible coefficient matrix +(a nonzero determinant at a random rational point, which proves it nonzero as a function). Coordinates without a +declared sign come first, then those in the fewest balances. The chart + +.. math:: + + (\theta \setminus p,\ R_H) \mapsto \big(\theta,\ x^\ast\big), \qquad + p = p(\theta \setminus p, R_H, W), \quad x^\ast_H = R_H, \quad x^\ast_N = x^\ast_N(\theta, R_H, W), + +is a bijection onto the points :math:`(\theta, x^\ast)` of the resting set where the coefficient matrix and the +coefficients of the solved states do not vanish: :math:`R_H` reads :math:`x^\ast_H` off a point, and the +balances, linear in :math:`x^\ast_N` and :math:`p`, have the given point as their unique solution. The output of +a point of the resting set is the output from the resting state of the point, so the fiber of the model, as a set of points +:math:`(\theta, x^\ast)`, is the fiber in the chart; the chart model, rational up to the leaves :math:`W` and +with the start :math:`(R_H, x^\ast_N)`, is relaxed as above. In the chart the leaves are exponentials of +coordinates, so (c) follows from the rank of their exponents as before. Several resting states with the same +:math:`\theta` are distinct points of the fiber. The declared sign of :math:`p` is no sign of a chart coordinate, +so the counts in the domain do not hold it (``info["limits"]``). An event on a state inside a term, a known input, +a condition grid and a trafo of the states are not handled. A model with directions and a term of the states is +relaxed first; where the relaxed count bounds the fiber (no ``relaxed_why``), the reduction of the model itself is +skipped. + +**Unknown inputs.** An unknown input enters the fiber through the jets at the start, +unknowns that are no coordinates: the chain of :ref:`inputs` with free starts. A +point of the fiber is then a value of the coordinates with some input of the same output, and +points that differ only in the jets count once. An observable of *relative degree* :math:`r` in the +input :math:`w`, the least order whose Lie derivative reads a jet of :math:`w`, has + +.. math:: + + L^{r + m} h = \partial_w (L^r h)\, w^{(m)} + (\text{terms in } w, \dots, w^{(m - 1)}), + \qquad \partial_w L^r h \ne 0, + +by induction on :math:`m`, since :math:`L^r h` reads :math:`w` but no derivative of it. So the +Taylor coefficient of order :math:`n` reads exactly the jets up to :math:`n - r`; :math:`r` comes +from symbolic Lie derivatives over :math:`\mathbb{Q}`. At the orders of a count, the jets above the +highest order that an observable reads are zero: no output coefficient up to these orders depends +on them, so the coordinates of the fiber are the same, and the equations of the derivatives of the +states, which read them, keep no free direction. An unknown of the system that is no coordinate +and enters no equation is left out, which keeps the coordinates of every point. The model has one +condition, no events, switches or ``equilibrate``, and the exact count by the field of the +outputs is not taken. A map :math:`\sigma` is ``checked`` where the equations of the fiber four +orders higher, with the coordinates at :math:`\sigma(\theta)`, have a solution modulo a prime at +random points, and ``exact`` where the map of the states fails without the inputs and a map +:math:`\psi(x, \theta, w)` of the input values, solved where linear, satisfies + +.. math:: + + F(\varphi(x), \sigma(\theta), \psi) = D\varphi(x)\, F(x, \theta, w), \qquad + h(\varphi(x), \sigma(\theta), \psi) = h(x, \theta, w), \qquad + \varphi(x_0(\theta)) = x_0(\sigma(\theta)) + +over :math:`\mathbb{Q}(x, \theta, w)`, :math:`\varphi` reading no input. Then :math:`(\varphi(x(t)), +\psi(x(t), \theta, w(t)))` solves the model at :math:`\sigma(\theta)` with the output of the +solution at :math:`\theta`; ``state_maps`` lists :math:`\psi` under the name of the input. + +.. _maps: + +Maps between the points of the fiber +------------------------------------ + +Permutations of the coordinates are tested before the count. If :math:`\sigma` permutes the +coordinates and keeps every Taylor coefficient :math:`c`, then :math:`c(\sigma(\theta)) = +c(\theta)` gives :math:`\partial_i c(\theta) = (\partial_{\sigma(i)} c)(\sigma(\theta))`, so +:math:`c` depends on :math:`\theta_i` if and only if it depends on :math:`\theta_{\sigma(i)}`, and +:math:`\sigma` maps each coordinate onto one with the same set of coefficients that depend on it. +These sets come from one evaluation of the Jacobian at a random point modulo a prime. The +transpositions within each class of equal sets, and then the products of two transpositions that +fail alone, are tested on the coefficients up to four orders past the rank criterion at a random +point modulo the prime, and a candidate that passes is proven as below or kept as ``checked``. +The candidates join the maps of the fiber; they need no count, which only decides whether the +maps are complete. + +Where the other points are rational functions :math:`\sigma_j(\theta)`, they are reconstructed +without matching points across samples. For a coordinate :math:`\theta_i`, the characteristic +polynomial :math:`\prod_j (Z - \sigma_{j,i}(\theta))` over the fiber is invariant under +permutations of the points, so the coefficients are rational functions of :math:`\theta`; msolve +gives them modulo a prime from the rational univariate representation, and they are +interpolated as the generators are. A linear factor over :math:`\mathbb{Q}(\theta)` is a rational +:math:`\sigma_{j,i}`. Coordinates with the fewest arguments come first, until their rational +roots separate the points of the fiber; each other coordinate is then interpolated on each +point, labeled by those roots. A map is ``checked`` when the coefficients agree at random +rational points, and ``exact`` with a map :math:`\varphi` of the states such that + +.. math:: + + F(\varphi(x), \sigma(\theta)) = D\varphi(x)\, F(x, \theta), \qquad + h(\varphi(x), \sigma(\theta)) = h(x, \theta), \qquad + \varphi(x_0(\theta)) = x_0(\sigma(\theta)) + +over :math:`\mathbb{Q}(x, \theta)`: :math:`\varphi` is :math:`\sigma` on a state whose initial value +is a coordinate, a different one per state, and the identity on the others, with :math:`x \mapsto x^c` for a state +that starts at 1 with :math:`\dot x = x\, R` where :math:`R(\sigma) = c\, R` for a rational +:math:`c`, or, where these fail, the +solution of :math:`h(\varphi(x), \sigma(\theta)) = h(x, \theta)` and the Lie derivatives of these +equations where they are linear in :math:`\varphi`, or :math:`\varphi` affine in the states of the +block that :math:`\sigma` reaches, the states whose right-hand side or start holds a coordinate +that :math:`\sigma` moves, closed under the states that read them, and the identity elsewhere, with +coefficients solved from the identities where they are linear in them. With events, each segment has such a map, and +at each event :math:`\varphi_{\text{after}}(E(x, \theta)) = E(\varphi_{\text{before}}(x), +\sigma(\theta))`, in every condition. The ``exact`` maps generate a group :math:`G`; at a point +outside the fixed sets of the elements of :math:`G` the orbit is :math:`|G|` points of the fiber. When +:math:`|G|` equals the count, the count is final (``count_final``): the exact maps give a lower +bound equal to the upper one. ``info["discrete"]["certificate"]`` lists the state maps, :math:`|G|`, +the count and the prime. ``complete`` is ``"exact"`` where the field fixed by the exact maps lies +in the field of the output coefficients, which proves the fiber to be the orbit (:ref:`exact-count`); else ``"verified"`` where a count over :math:`\mathbb{Q}` at a random integer point +equals the orbit, with the probability ``count_bound`` that the fiber at a generic point has more +points. Otherwise the certificate names the step that is not proven: that the count modulo the +prime at a random point is the count over :math:`\mathbb{C}` at a generic point, an axiom +(``complete: "axiom"``, with ``count_bound_why``). A map with a positivity certificate for each +image coordinate preserves :math:`\Theta`; a map with an image coordinate negative on +:math:`\Theta` never meets it; otherwise the conditions on :math:`\theta` are listed. Where the fiber is +proven to be the orbit and every element of the group either preserves :math:`\Theta` or never meets +it, ``count_domain`` is one plus the number of elements that preserve it, exactly. Ordering the +coordinates and keeping in each orbit the point that is least in the first coordinate a map +moves gives a *fundamental domain*, a set of inequalities such as :math:`k_{01} < k_{12}`. + +The counts in :math:`\Theta` at the sample points end at the work limits of the global analysis, and +where the proven maps account for the count, the points are the orbits. Over :math:`\mathbb{Q}`, +msolve isolates the real points in boxes, refined until each box decides +the sign of every coordinate declared positive; the count in :math:`\Theta` follows at rational +sample points. Where the rational maps of the next paragraph account for every point counted at a +sample point, and the images give the coefficients of the point exactly, the point and the images are the +fiber, and the count needs no isolation. The number of points in :math:`\Theta` is constant only between the hypersurfaces +on which two points meet or a point crosses the boundary of :math:`\Theta`, so the count is +reported per point and never taken as a global verdict. + +.. _exact-count: + +The exact count +--------------- + +Let :math:`L = \mathbb{Q}(\theta)`, :math:`G` the group of the ``exact`` maps +of :ref:`maps`, acting on :math:`L` by :math:`\sigma(f) = f \circ \sigma`, and +:math:`c` the Taylor coefficients of the observables at the start of the experiments, the first +segment of each condition, with the known inputs at the values drawn for them. Let :math:`T` be +the fiber at a generic point :math:`\theta` for these inputs: the values :math:`\sigma` over +:math:`\overline{L}` with the output of :math:`\theta`. A value with the output of :math:`\theta` +for every input lies in :math:`T`. + +*Theorem.* Let :math:`F = \mathbb{Q}(c)` and :math:`\alpha \in L` with :math:`P_\alpha(Z) = +\prod_{\sigma \in G} (Z - \sigma(\alpha)) \in F[Z]` and :math:`L = F(\alpha)`. Then :math:`T` is the orbit of +:math:`\theta` under :math:`G`, of :math:`|G|` points. + +*Proof.* The output is a function of :math:`\theta` whose coefficients generate a field +:math:`\mathbb{Q}(\Psi) \supseteq F`, and :math:`L` is finite over it, since it is finite over +:math:`F`. A point :math:`\sigma \in T` has coordinates algebraically independent over +:math:`\mathbb{Q}` (the output there has transcendence degree :math:`n`), so :math:`\theta \mapsto \sigma` +defines an embedding of :math:`L` into :math:`\overline{L}` over :math:`\mathbb{Q}(\Psi)`, and every +such embedding gives a point of :math:`T`; so :math:`|T| = [L : \mathbb{Q}(\Psi)]` in characteristic +0. The exact maps keep the output, so the orbit of :math:`\theta` lies in :math:`T`. :math:`\alpha` +is a root of :math:`P_\alpha \in F[Z]`, of degree :math:`|G|`, so :math:`|T| = [L : +\mathbb{Q}(\Psi)] \le [L : F] = [F(\alpha) : F] \le |G|`. :math:`\square` + +The test of the theorem has no random step: random points only propose candidates, and each +candidate is checked exactly. Membership in :math:`F` is proven as a tower: a function is in +:math:`F` once it is a rational function of output coefficients and of functions already shown in +:math:`F`, :math:`f = A(w)/B(w)`, by the identity :math:`A(w(\theta))\, \mathrm{den}_f(\theta) = +\mathrm{num}_f(\theta)\, B(w(\theta))` with :math:`B(w(\theta)) \ne 0`, checked as polynomials in +:math:`\theta` over a common denominator. The output coefficients enter as quotients of polynomials in +:math:`\theta` over powers of a shared list of factors, the denominators of the starts of the states and the values of the +denominators of the right-hand sides and observables at the start, from the Taylor recursion of +:math:`D(x)\, x' = N(x)` order by order: a sum takes the largest power of each factor, so that no gcd is +needed and the denominators grow linearly with the order. The candidates :math:`A, B` come from linear algebra +modulo primes at random points, with rising degree, rebuilt over :math:`\mathbb{Q}`. The functions +shown in :math:`F` are: + +- *Coefficients of input-output relations.* Let :math:`\phi_1, \dots, \phi_r` be the monomials of + degree at most :math:`\delta` in the derivatives of each observable up to an order chosen per observable, + which leaves it out where negative, and in the known inputs that the right-hand sides read, with + their derivatives, the configurations taken with the fewest monomials first (for more + than three observables each one alone and all at one order) and those holding one that gave + relations left out, and :math:`M(c)` the + matrix of the Taylor coefficients of :math:`\phi_j` along the trajectory of the first condition, + whose entries are polynomials in output coefficients and the input values. A vector + :math:`\lambda(\theta)` with :math:`\sum_j \lambda_j \phi_j(g, u) = 0` along every trajectory + lies in the kernel of :math:`M(c(\theta))`; this is checked exactly, the derivatives of the + observables as Lie derivatives, a polynomial identity in the states, the inputs and the + coordinates. Where the rank of :math:`M` at one point modulo a prime is :math:`r - s` and + :math:`s` such vectors are proven, each the identity on the same :math:`s` columns, they are the + basis of the kernel over :math:`\mathbb{Q}(\theta)` with that identity, since a nonzero minor at + one point is nonzero over :math:`\mathbb{Q}(\theta)`; the same basis solves the system over + :math:`F`, so the entries of the basis lie in :math:`F` by Cramer's rule. They are interpolated as + rational functions of the parameters from the relations among the :math:`\phi_j` at random states + for random values of the parameters, the other coordinates held at one value, as polynomials of all + entries at once, else over the denominator of one entry; the identity check decides. Rational right-hand sides and observables enter as rational functions of the states. +- *Coefficients of projections.* A *profile* :math:`h` gives per observable :math:`g_r` a number + :math:`h_r` such that the derivatives :math:`g_r^{(k)}`, :math:`k < h_r`, of all observables are + algebraically independent over :math:`L` and the next derivative of each one is algebraic over + them; the rank of their Jacobian in the states at a random point modulo a prime proposes it, in + rounds over the observables and one observable after the other. The *projection* of + :math:`g_i` is a polynomial relation of :math:`g_i^{(h_i)}` with these derivatives and the input + states read, the generator of the ideal of the relations in these variables :cite:p:`Dong2023`. The + monomials :math:`\phi_j` of the projection are the support of the kernel of the values of the monomials at random + states, for one random value of the parameters, modulo a prime: first with rising total degree + and degree in :math:`g_i^{(h_i)}`, at most 1500 monomials, then inside bounds on the Newton + polytope of the projection, at most 10000, then again by degrees, at most 6000: the largest + sets of degrees below a cap that doubles, since one without a relation holds none of the + smaller ones, and where the kernel has more than one vector, the least set with one. The bounds + on the Newton polytope are counts of points. Let :math:`\Phi` be the map from the states to the + base functions (the derivatives and the inputs of the projection), the parameters at their + value, on a slice of the states: those whose columns keep the Jacobian of :math:`\Phi` at rank + :math:`|\Phi| - 1` stay free, the others take random values, so that the image is dense in the + hypersurface :math:`P = 0` of the projection and a generic point of it has the same number + :math:`k` of preimages. For a weight vector :math:`w` of nonnegative integers and random vectors + :math:`c, b`, the points of the slice with :math:`\Phi(x) = c + b\, t^w` lie over the roots of + :math:`P(c + b\, t^w)`, a polynomial in :math:`t` of degree :math:`\max_{m \in \mathrm{supp}\, + P} \langle w, m \rangle`, :math:`k` points over each; with :math:`c = 0` and :math:`t \ne 0` + over the nonzero roots, :math:`\max - \min` of :math:`\langle w, m \rangle` in number. msolve + :cite:p:`Berthomieu2021` counts the solutions of these systems over the algebraic closure of + :math:`\mathrm{GF}(p)`, the denominators of the base functions inverted by a new unknown, and + :math:`k` as the number of solutions of :math:`\Phi(x) = \Phi(x_0)` at a random :math:`x_0`. + The weights are the total degree, each base function alone, the order of each derivative plus + one and the reverse order, and random weights in :math:`\{0, \dots, 3\}` while more than 10000 + monomials meet the bounds. A point modulo a prime that is not generic can make a count too small + and leave a monomial of :math:`P` out; then the kernel has no vector or the identity check below + fails, so the bounds, like the rest of the support, only propose. :cite:p:`Dong2023` computes the + projections by resultants over :math:`\mathbb{Q}(\theta)`, the extraneous factors removed by a + membership test along power series solutions; here the support comes from one kernel at one + value of the parameters, and the coefficients as follows. The coefficients are normalized at the one of + least degree on a random line and interpolated as rational functions of the parameters over one + denominator :math:`D`: a monomial where the restriction to every line parallel to an axis is a + power of the variable, else interpolated from the values :math:`D(\theta) = \ell(1) / \ell(0)` + with :math:`D(\beta) = 1`, :math:`\ell` the denominator of a random combination of the + coefficients on the line :math:`\beta + t (\theta - \beta)`; the numerators :math:`a_j D` by + sparse interpolation :cite:p:`BenOr1988` or in the box of their degrees per parameter, rebuilt over + :math:`\mathbb{Q}` from more primes, at most 32, until two successive reconstructions agree. The projections of + a profile are found first and taken with the fewest monomials first. A derivative is + :math:`N / (Q^a E^b)`, :math:`Q` the product of the distinct denominators of the right-hand sides + and :math:`E` the denominator of the observable, by :math:`L(N / (Q^a E^b)) = (\tilde N Q E - N + (a \tilde Q E + b \tilde E Q)) / (Q^{a + 2} E^{b + 1})` with :math:`L(P) = \tilde P / Q`, so that + the relation :math:`\sum_j a_j \phi_j = 0` is checked as one identity of polynomials in the states + and coordinates, each term over the powers of :math:`Q` and :math:`E` that it lacks, without gcds. + With rank :math:`r - 1` of :math:`M` at one point modulo a prime, :math:`r` the number of + monomials, the coefficients lie in :math:`F` as in the item before. Every step that proposes + (the profile, the monomials, the degrees, the interpolation) can only make the search fail, + never prove a wrong function. +- *Coefficients of relations by elimination.* Where the projections give no proof, the states are + eliminated as in :cite:p:`Hong2020` (StructuralIdentifiability.jl), with python-flint: the equation of an + observable is differentiated along the flow, the derivatives of the states are removed with the + equations of the model, and one state at a time is removed by a resultant over + :math:`\mathbb{Z}[\theta]`, the determinant of the Bezout matrix (the Sylvester matrix where one + degree is one) after the greatest common divisors of the rows and columns. Every polynomial of + this process vanishes along every trajectory: the equations of the model do, and derivatives, + combinations and resultants of such polynomials do. Of the irreducible factors of such a + polynomial and of the divisors taken out, one vanishes along every trajectory: along one + trajectory their product is zero in the domain of power series, so one factor is, and the + coordinates and starts at which a given factor vanishes along the trajectory form a closed subset + of the open set without a pole at the start, so one of these finitely many subsets is all of it. + A factor nonzero at a point of a trajectory at random coordinates modulo a prime is not that one, + so the product of the factors that vanish at three such points vanishes along every trajectory, + without a random step. The relation of an observable at the end is the only one on the support + where the rank of the Taylor coefficients of the monomials along the trajectory is one less than + their number at a point modulo a prime, as for the projections; the coefficients over one of + fewest terms then lie in :math:`F`, and those whose gradients in the parameters raise the rank + at a random point modulo a prime, fewest terms first, with as many more, join the functions + shown. Where a state :math:`x_i` is removed, an equation :math:`A x_i + B` of degree one in it + (one of the two equations, else their first subresultant, a combination of both) whose + coefficient :math:`A` is nonzero at a point of a trajectory gives :math:`x_i(0) = -B / A`, rational + in the output coefficients, the coordinates and the starts of the states removed after it: the + start lies in :math:`F` once these do. The elimination runs in a separate process while the share of + ``search_entries`` for the relations is not spent and ends at ``elimination_terms``. +- the coordinates that :math:`G` fixes and the coefficients of :math:`P_\alpha`, each a rational + function of the functions before it on the same coordinates, then of small systems of them (the + functions shown in :math:`F` whose coordinates not yet shown lie in those of the function and at + most two more, each divided by the largest monomial in the coordinates shown that divides the + numerator and by the denominator where that reads coordinates shown only, again a function in + :math:`F`, with the coordinates shown that they read, in degrees counted apart for both), then of + all of them, then with the output coefficients added lowest order first; the traces :math:`\sum_{\sigma \in G} \sigma(\theta_i)` of the moved + coordinates and sums over :math:`G` of monomials in them join where they are proven. + +:math:`\alpha` is a moved coordinate with :math:`|G|` distinct images, else a combination of two +or three, with the simplest images. :math:`L = F(\alpha)` is shown coordinate by coordinate, each a +member of :math:`F(\alpha)` once shown, in two ways: + +- as a rational function of functions in :math:`F`, of :math:`\alpha` and of the coordinates shown + before, checked as above; +- for the start of a state :math:`x_i`, by a relation :math:`\sum_j \lambda_j \phi_j(g, u) + x_i + \sum_k \mu_k \psi_k(g, u) = 0` along every trajectory, :math:`\psi_k` the monomials of one degree + less, found and checked as the input-output relations, with :math:`\sum_k \mu_k \psi_k` nonzero + also at the start, and with coefficients rational in parameters already shown in + :math:`F(\alpha)`: at the start, :math:`x_i(0) = -\sum_j \lambda_j \phi_j / \sum_k \mu_k \psi_k`, + with :math:`\phi_j, \psi_k` there polynomials in output coefficients and input values. Fixed + starts join :math:`F` the same way. Such a state :math:`x_i(t)` is the same quotient along the + whole trajectory, so the Taylor coefficients of the state lie in :math:`F` as well, and it joins the + observables of the relations that follow. After the relations among at most 40 of these + monomials, the projection of :math:`x_i` gives it: the relation of + :math:`x_i` with the derivatives :math:`g_r^{(k)}`, :math:`k < h_r`, of degree one in + :math:`x_i`, found, interpolated and checked as a projection, with :math:`\sum_k \mu_k \psi_k` + nonzero at the start shown by the value at one point modulo a prime. Where :math:`x_i` is algebraic + of higher degree over these derivatives, the base takes also :math:`g_r^{(h_r)}` of one observable, at a degree + below the degree :math:`d_r` of the projection of :math:`g_r` in it: the monomials of lower degree in :math:`g_r^{(h_r)}` are a + normal form modulo the projection, so no multiple of it enters the kernel. + +The relations are tried in the order: monomials of the item on input-output relations up to 120, +projections, the elimination, then the others up to 300; the relations of a start among the +monomials up to 40 and then up to 300, after the projection of the start. A configuration or a +profile that needs the derivative of one with more than 5000 terms is left out. The search ends at +the work limits ``search_entries``, ``msolve_entries`` and ``elimination_terms``, or where the relations are tried and none is found. Past a +limit the count is reported without the exact certificate, and the certificate names what was not +reached. A call of msolve fails past the address space ``memory`` of ``discrete()``, 8 GiB by +default. +Constants of the model that are no coordinates are known symbols :math:`\kappa`: :math:`\mathbb{Q}` +is replaced by :math:`\mathbb{Q}(\kappa)` throughout, and the theorem holds for generic values of the +constants. ``info["discrete"]["certificate"]["exact"]`` lists the functions with their expressions, +the relations used and :math:`\alpha`, and ``complete: "exact"``. A short count modulo a prime comes first: where it equals the orbit of the proven candidates, or ends without a count, the +exact count is tried with the group of the candidates, and where it holds, neither the full count +nor the reconstruction of the maps runs. A second search, with the group of all exact maps, starts +from the functions the first one proved to lie in :math:`F`. + +Where the search stops before :math:`L = F(\alpha)` is shown, the functions :math:`f_1, \dots, +f_m` it proved to lie in :math:`F` are counted instead of expressed. Every point of :math:`T` has +the values :math:`f_i(\theta)`, so :math:`T` lies in the fiber of :math:`\theta \mapsto (f(\theta), +c_0(\theta), \dots, c_N(\theta))` for any orders :math:`N`, the starts entering through the output +coefficients. The orders are those of the rank criterion with the gradients of the :math:`f_i` in the +basis first, so that the :math:`f_i` stand for the higher coefficients; the route runs only where +they lower the orders. The :math:`f_i` of least degree whose gradients raise the rank, with as many +more, are counted first, then all of them. As in the count, the orders start one above and rise, +at most to those of the rank criterion of the outputs alone, until the count modulo the prime at a +random point is below :math:`2|G|`; then the count over +:math:`\mathbb{Q}` of the next paragraph, with these :math:`f_i` as pins, bounds :math:`|T|`, and +a count :math:`k` with :math:`|G| \le k < 2|G|` gives :math:`|T| = |G|`, since :math:`|G|` divides +:math:`|T|` (*The orbit* in :ref:`several-experiments`). The smaller variety of the bound takes the +:math:`n` rows from the :math:`f_i` and the output coefficients, those of least degree first. +``certificate["pinned"]`` lists the functions counted, the orders, the counts modulo the prime and +over :math:`\mathbb{Q}`, the bound with the bits of the point and the Bezout number, or why the +route gave none. + +*Coefficients of a large projection, verified.* Where the elimination gives no relation for the +observable of a projection with more than 1500 terms, a few coefficients of the projection join the +:math:`f_i` with an error bound. Let +:math:`S` be the support of :math:`r` monomials :math:`\phi_j` in the base functions :math:`b_v = +N_v / \prod_k F_k^{e_{vk}}`, found as above. + +(a) The Taylor coefficients of the :math:`\phi_j` along the trajectory have rank :math:`r - 1` at a +random point modulo a prime, so at most one relation on :math:`S` holds along the trajectory, and if +one exists, the coefficients over one of them lie in :math:`F` by Cramer's rule, as above. + +(b) The relation exists, verified. A trial takes :math:`r + 6` random states and a random +:math:`\theta` modulo a prime :math:`q` uniform among the primes from :math:`2^{29}` to the largest +engine prime. Times :math:`\prod_k F_k^{T_k}`, :math:`T_k = \max_j t_{jk}`, :math:`t_{jk} = \sum_v +m_{jv} e_{vk}`, a row of the values of the :math:`\phi_j` becomes the values of the polynomials +:math:`P_j = \prod_v N_v^{m_{jv}} \prod_k F_k^{T_k - t_{jk}}` of degree :math:`d_j`. Without a +relation, the determinant of the first :math:`r` rows is a nonzero polynomial in :math:`\theta` and +the states, of degree at most :math:`D = \sum_j d_j` and with integer coefficients whose content +is at most :math:`H`, :math:`\log_2 H \le \log_2 r! + \sum_j \log_2 \|P_j\|_1`, the norms +bounded by those of the :math:`N_v` and :math:`F_k` cleared to integers. A kernel of the values +makes it vanish at the point. At most :math:`\lceil \log_2 H / 29 \rceil` of the primes divide the +content, and the primes drawn from number at least :math:`N` by :math:`x / \ln x < \pi(x) < 1.25506\, +x / \ln x` :cite:p:`Rosser1962`; a row where a denominator vanishes is drawn again, which conditions on an +event of probability :math:`a \ge 1 - (r + 6) \deg \prod_k F_k / (q - 1)`. So a trial shows a +kernel with probability at most :math:`\varepsilon = D / ((2^{29} - 1)\, a) + \lceil \log_2 H / 29 +\rceil / N` by :cite:p:`Schwartz1980`, and :math:`k = 5` independent trials, each with a kernel of one +vector, with probability at most :math:`\varepsilon^k`. + +(c) The coefficients. Where a coefficient :math:`c_{j_0}` is a monomial in the parameters, the +others over it are Laurent polynomials. Axis lines through a random point, of 24 points at the +start, show such a :math:`j_0`: the quotient of every other entry by it has a power of :math:`t` +as denominator on every line, which gives the range of the exponents of each entry per parameter. +The entries with the fewest exponent vectors in their ranges are interpolated by Ben-Or and Tiwari +:cite:p:`BenOr1988` modulo two primes and rebuilt over :math:`\mathbb{Q}`, those whose gradients raise +the rank first, until the rank of the gradients of all entries found on the lines, then as many +more. At every trial of (b) each of them equals the entry of the kernel over entry :math:`j_0`. A +wrong function :math:`w = M / (L\, \theta^a)` would make :math:`M C_{j_0} - L\, \theta^a C_j`, with +:math:`C` the cofactors of the first :math:`r - 1` rows, a nonzero polynomial that vanishes at the +point, so a trial passes with probability at most :math:`\varepsilon_w`, as :math:`\varepsilon` +with the degree and the height of :math:`w` added, and :math:`k` trials with +:math:`\varepsilon_w^k`. + +These functions join the :math:`f_i` of the count, and where they +are counted, the bound of the count is that over :math:`\mathbb{Q}` plus :math:`\varepsilon^k` and +:math:`\varepsilon_w^k` per function counted. ``certificate["pinned"]["relation"]`` lists the +functions, the monomial :math:`j_0`, the trials, the kernels, :math:`D`, :math:`\log_2 H` and the +probabilities, ``relation_bound`` their sum and ``count_bound_q`` the bound over +:math:`\mathbb{Q}` alone. + +.. _verified-count: + +The verified count +------------------ + +Where the exact count is not found, the count is taken again over +:math:`\mathbb{Q}`, by the rational parametrization of msolve, at an integer point +:math:`\theta^\ast` uniform in :math:`\{1, \dots, 2^b\}^n`. A count :math:`k` there bounds the +fiber: + +.. math:: + :label: eq-count-bound + + \Pr\big[|T| > k\big] \le \frac{(N_u + 2D)\, D}{2^b}, + +with :math:`N_u` the number of unknowns and :math:`D` the Bezout number below; :math:`b \ge 64` +is chosen so that the bound is at most :math:`10^{-6}`, up to :math:`b = 256` +(``count_bits``, ``bezout``). The bound holds for a model without events and switches, with every +start a coordinate, a number, a rational function of the coordinates or a jet of an unknown input +(*Unknown inputs* below), at orders no lower than those of the rank criterion; otherwise, or where the count differs, the count stays under the +axiom of :ref:`certificates` and ``count_bound_why`` names the reason. msolve is taken to be +correct. The count over :math:`\mathbb{Q}` calls msolve per block, plain and, where that fails, with a +separating linear form. Before a count, modulo a prime or over :math:`\mathbb{Q}`, a variable :math:`v` that an +equation :math:`a v + b\, m` sets to a monomial :math:`m` free of :math:`v` is substituted, a +coordinate only for a monomial in coordinates: on the variety :math:`v` is a function of the other +unknowns, so the substitution maps the points one to one onto those of the smaller system, and +points with distinct coordinates keep distinct coordinates. The count, and the bound below, which +is computed for the system before the substitution, do not change. Equations of the fiber with more +than 400000 terms, or with a power, product or sum of series of more terms while they are built, or +with more than 10000 unknowns, are not counted: the count stops at that order, and ``limits`` names +the limit. + +*The system.* The unknowns :math:`u = (x, z, w)` are the coordinates, the derivatives of the +states at the start and the variable of the saturation. The Taylor coefficients :math:`b(\theta)` +of the observables are rational functions; written over one denominator :math:`q(\theta)`, the +equations of the fiber become :math:`F_1, \dots, F_s \in \mathbb{Q}[\theta, u]`: the equations of +the model, the output equations :math:`\sum_l E_l(u)\, q\, b_{k-l} - q M_k(u)` and +:math:`w\, s(u) - 1`, with :math:`s` the product of the coordinates and the denominators at the +start. Their degrees in :math:`\theta` follow from the recursion of the series run on degree +bounds instead of values, a division adding the numerator of the divisor to the denominators. +:math:`V = V(F) \subset \mathbb{A}^{n + N_u}` has degree at most :math:`D = \prod_i \deg F_i`, by +the Bezout inequality :math:`\deg(V \cap W) \le \deg V \deg W` :cite:p:`Heintz1983`. + +*Step 1: the points of T are isolated.* For :math:`\sigma \in T` the point :math:`P_\sigma = +(\theta, \sigma, z(\sigma), 1/s)` lies on :math:`V`. The Jacobian of :math:`F` in :math:`u` has +full column rank there: the equation :math:`\mathrm{den}(x)\, z_0 = \mathrm{num}(x)` of a start +rational in the coordinates has the coefficient :math:`\mathrm{den}(\sigma) \ne 0`, the equation of +the derivative of order :math:`k + 1` of a state has the coefficient :math:`(k + 1) D_i(x_0)`, +nonzero by the saturation, and no derivative of higher order, so the derivatives are local +functions of :math:`x`; then the output equations have the Jacobian :math:`-E_0 \cdot \partial_x +\Psi_N` up to a triangular factor, and the rank criterion gives :math:`\operatorname{rank} +\partial_x \Psi_N = n` at a random point modulo a prime, so at every point whose coordinates are +algebraically independent over :math:`\mathbb{Q}`, as those of :math:`\sigma` are. So +:math:`P_\sigma` is an isolated point of :math:`V` over :math:`K = \mathbb{Q}(\theta)` and lies on +the union :math:`V_0` of the components of :math:`V` of dimension :math:`n` that dominate the +coordinates, which has at most :math:`D` points over :math:`\theta`. + +*Step 2: polynomials of bounded degree.* For each unknown :math:`u_j` the closure of the image of +:math:`V_0` under :math:`(\theta, u) \mapsto (\theta, u_j)` is a hypersurface :math:`V(E_j)`, +:math:`E_j \in \mathbb{Q}[\theta, U]` square-free, of degree at most :math:`D`, since a linear map +does not raise the degree. A linear form :math:`\lambda(x)` with integer coefficients separates the +at most :math:`D` values of :math:`x` on :math:`V_0` over :math:`\theta`; the image under +:math:`(\theta, u) \mapsto (\theta, \lambda(x))` is :math:`V(E_\lambda)`, of degree at most +:math:`D`, square-free in :math:`U` over :math:`K`, so :math:`R_\lambda = +\operatorname{Res}_U(E_\lambda, \partial_U E_\lambda) \in \mathbb{Q}[\theta]` is nonzero, of degree +at most :math:`(2D - 1) D`. + +*Step 3: specialization.* Let :math:`a_j`, :math:`a_\lambda` be the leading coefficients in +:math:`U` and :math:`\Delta = a_\lambda R_\lambda \prod_j a_j`, nonzero of degree at most +:math:`(N_u + 2D) D`; by :cite:p:`Schwartz1980` :math:`\Delta(\theta^\ast) = 0` with probability at most +the right side of :eq:`eq-count-bound`. Suppose :math:`\Delta(\theta^\ast) \ne 0`. The map +:math:`\theta \mapsto \theta^\ast` extends to a place of :math:`\bar K` with residue field +:math:`\bar{\mathbb{Q}}` (Chevalley's extension theorem). Every :math:`u_j` of a point of +:math:`V_0` is a root of :math:`E_j` with a leading coefficient nonzero at :math:`\theta^\ast`, so +finite at the place, and the point maps to a solution of :math:`F(\theta^\ast, u) = 0` with +:math:`w` finite, so away from the saturation. The values :math:`\lambda(x)` are the roots of +:math:`E_\lambda`, and with :math:`a_\lambda R_\lambda \ne 0` at :math:`\theta^\ast` they stay +distinct. The series at :math:`\theta^\ast` is the same recursion as over :math:`K`; without a +division by zero, :math:`q(\theta^\ast) \ne 0` and the values are those of :math:`b`, so the system +solved is :math:`F(\theta^\ast, \cdot)` up to nonzero factors. The substitutions of the fixed +variables, the derivatives that leave with their equation and the saturation by one variable per +block keep the values of :math:`x`. The system solved then has at least :math:`|T|` points with +distinct :math:`x`, and the count of msolve, the degree of the rational parametrization, at least +the number of distinct solutions, is at least :math:`|T|`. Counted by stages, each point of a stage is +exact and rational, and the sum over these points of the degrees of the rest is at least the number of +points with distinct :math:`x`, again at least :math:`|T|`. + +*A smaller variety.* The same steps hold for :math:`V' \subset \mathbb{A}^{n} \times +\mathbb{A}^{n + 1}` in :math:`(\theta, x, w)`, cut out by :math:`n` output equations +:math:`\mathrm{num}_i(x)\, \mathrm{den}_i(\theta) - \mathrm{num}_i(\theta)\, \mathrm{den}_i(x)` whose +gradients in :math:`x` are independent at a random point modulo a prime, and by :math:`w\, s'(x) = +1`, :math:`s'` the product of the coordinates, the denominators of the starts and the denominators of +the right-hand sides and observables at the start. A point of :math:`T` is an isolated point of +:math:`V'` over :math:`K`, since these gradients are independent at every point with algebraically +independent coordinates. A point of :math:`T` satisfies every output equation, so the specialization of the point, +with :math:`s' \ne 0` there, gives the derivatives at the start and a solution of the system solved. +With :math:`D' = (1 + \deg s') \prod_i \deg(\mathrm{num}_i\, \mathrm{den}_i)` and :math:`n + 1` +unknowns in place of :math:`D` and :math:`N_u`, the smaller of the two bounds is used. + +*Pins.* A function :math:`f = a/b` that the search of the exact count proves to lie in :math:`F` +takes the same value at every point of :math:`T`: with :math:`f = A(c)/B(c)` and :math:`c(\sigma) = +c(\theta)`, :math:`f(\sigma) = f(\theta)`. The count, the counts at the sample points and the +verified count therefore add the equation :math:`a(x)\, b(\theta) - b(x)\, a(\theta)` per such +function, of degree at most :math:`2 \max(\deg a, \deg b)` in :math:`(\theta, x)`, which only removes +points outside :math:`T`; a coordinate so proven becomes the linear equation :math:`x_i = +\theta_i` and is substituted. Every point of :math:`T` satisfies these equations, so Steps 1 to 3 +hold for :math:`V` with them, and the smaller variety takes the :math:`p` pinned coordinates, each of +degree one, with :math:`n - p` output equations whose gradients are independent modulo the pinned +columns, :math:`D' = (1 + \deg s') \prod_i \deg(\mathrm{num}_i\, \mathrm{den}_i)` over these +:math:`n - p` equations. + +*Unknown inputs.* The jets :math:`v` of the inputs that the output coefficients read (*Unknown +inputs in the count* below) are coordinates of the point, drawn uniform in :math:`\{1, \dots, +2^b\}` with :math:`\theta^\ast`, and :math:`K = \mathbb{Q}(\theta, \hat v)`; the jets above them are +zero in the system and at the point. The unknowns :math:`u` add these jets and the derivatives of +the chains, and :math:`D` takes the degrees in :math:`(\theta, \hat v, u)`, the series run on +degree bounds with the jets of the point as variables. Step 1 needs the Jacobian of the output +coefficients in :math:`(x, v)` of full column rank :math:`n + q`, :math:`q` the number of jets +read; it is checked at a random point modulo a prime, and a minor that is not zero there is not +zero over :math:`\mathbb{Q}`, so the rank holds at every point with algebraically independent +coordinates. A point :math:`(\sigma, v_\sigma)` with the output of :math:`(\theta, \hat v)` is +one: :math:`(\theta, \hat v)` is an isolated solution of :math:`b(\cdot) = b(\sigma, v_\sigma)`, +so algebraic over :math:`\mathbb{Q}(\sigma, v_\sigma)`, which therefore has transcendence degree +:math:`n + q`. The derivatives of the states and of the chains are local functions of :math:`(x, +v)` as before, the chain equations having the coefficient :math:`k + 1`. Steps 2 and 3 hold as +stated with :math:`\theta` replaced by :math:`(\theta, \hat v)`; the bound of +Equation :eq:`eq-count-bound` keeps the same form, since it does not depend on the number of +coordinates of the point. The smaller variety is not used, since the output equations of that variety are in +:math:`x` alone. + +.. _several-experiments: + +Several experiments +------------------- + +The fiber of one experiment needs the Taylor coefficients up to an order +near the number of coordinates over the number of observables, and the degrees of the equations grow +with the order. Experiments that share the parameters need lower orders: :math:`K` copies of the +model with the parameters :math:`\theta` shared and starts :math:`x_0^1, \dots, x_0^K` of their own, +each with another draw of the known inputs. Let :math:`T(\theta, x_0)` be the fiber of one +experiment, :math:`T_K` the fiber of the :math:`K` experiments at :math:`(\theta, x_0^1, \dots, +x_0^K)`, and :math:`\pi` the projection onto :math:`(\theta', x_0'^1)`; always :math:`\pi(T_K) +\subseteq T(\theta, x_0^1)`. The route takes a model with one condition and no events, switches or +clock in the equations, every state with a free start: a coordinate that nothing else reads +:cite:p:`OvchinnikovPogudinThompson2023,Ovchinnikov2022`. + +*Proposition 1.* If :math:`\dot x = f(x, \theta, u)` at a constant input :math:`u` has no +nonconstant rational first integral over :math:`\mathbb{Q}(\theta, u)`, then :math:`\pi(T_K) = +T(\theta, x_0^1)` at a generic point. + +*Proof.* Let :math:`\kappa` be the jets of the known inputs at the start, :math:`\Theta'(\theta, +x_0, \kappa)` the finite set of the :math:`\theta'` of :math:`T(\theta, x_0)`, and :math:`e` the +coefficients of :math:`\prod_{\theta' \in \Theta'} (Z - \lambda(\theta'))` for a linear form +:math:`\lambda`. :math:`T` is cut out by finitely many output equations over :math:`\mathbb{Q}( +\theta, x_0, \kappa)` and is stable under the automorphisms of the algebraic closure over this +field, so :math:`e \in \mathbb{Q}(\theta, x_0, \kappa_0, \dots, \kappa_M)` for some :math:`M`. The +experiment that starts at time :math:`s` from :math:`x(s)`, with the jets :math:`\kappa(s)` of the +inputs there, has the output shifted by :math:`s`, for :math:`\theta` and for every :math:`\theta' +\in \Theta'`; so :math:`\Theta'` is constant along the flow of :math:`X = f \cdot \partial_x + +\sum_j \kappa_{j+1} \partial_{\kappa_j}`, and :math:`X e = 0`. In :math:`X e` only +:math:`\kappa_{M+1} \partial_{\kappa_M} e` reads :math:`\kappa_{M+1}`, so :math:`e` does not read +:math:`\kappa_M`, and down to :math:`\kappa_0`: :math:`f(x, \theta, \kappa_0) \cdot \partial_x e = +0` for every :math:`\kappa_0`, a rational first integral at a constant input, so :math:`e \in +\mathbb{Q}(\theta)`. :math:`\Theta'` therefore does not depend on the starts or the inputs: for +:math:`(\theta', x_0'^1) \in T(\theta, x_0^1)` each experiment :math:`k` has an :math:`x_0'^k` with +:math:`(\theta', x_0'^k) \in T(\theta, x_0^k)`, and these form a point of :math:`T_K` over +:math:`(\theta', x_0'^1)`. :math:`\square` + +*Conservation laws.* Where linear forms :math:`\ell(x) = C(\theta)\, x` in the states, :math:`C` of +rank :math:`c` with entries rational in the parameters, satisfy :math:`C f = 0` identically in the +states and inputs, symident finds a basis of them over :math:`\mathbb{Q}(\theta)` and takes the +premise on the level sets: if the system restricted to :math:`\ell = \gamma` has no nonconstant +rational first integral over :math:`\mathbb{Q}(\theta, \gamma, u)`, every rational first integral +:math:`h` of :math:`f` is a function of :math:`\ell`, since :math:`h` restricted to a generic level set +is constant there. The pairs :math:`(\theta', \ell_{\theta'}(x_0'))` over :math:`T(\theta, x_0)` are +then, as in the proof, functions of :math:`(\theta, \ell_\theta(x_0))` alone, :math:`\ell_{\theta'}` being +constant along the flow at :math:`\theta'`; so the experiments start on the level set of the first: +per law, a pivot state of the reduced echelon form of :math:`C` starts at the value that makes +:math:`\ell(x_0^k) = \ell(x_0^1)`, a rational function of the coordinates, and Proposition 1 holds for the +fiber of these experiments. + +The twisted oscillator :math:`\dot x_1 = (\omega + x_3) x_2`, :math:`\dot x_2 = -\omega x_1`, +:math:`\dot x_3 = 0`, :math:`h = (x_2, x_3)` of :cite:p:`OvchinnikovPogudinThompson2023` (Example 2.7) +shows that the premise is needed: :math:`x_3` is a first integral, one experiment leaves +:math:`\omega` and :math:`-(\omega + x_3)`, and two experiments with different :math:`x_3` leave +:math:`\omega` alone. + +*The premise at one point.* A system :math:`\dot x = F(x)` analytic at an equilibrium :math:`x^\ast` +has at most as many functionally independent rational first integrals near :math:`x^\ast` as the +dimension of the span of :math:`\{k \in \mathbb{Z}^n \setminus 0 : \sum_i k_i \lambda_i = 0\}`, +:math:`\lambda` the eigenvalues of :math:`DF(x^\ast)` :cite:p:`CongLlibreZhang2011` (Theorem 1): none where +the eigenvalues are linearly independent over :math:`\mathbb{Z}`. The parameters (the constant +inputs and known constants among them) where :math:`F`, cleared of denominators, has a nonconstant +rational first integral :math:`A/B` with :math:`\deg A, \deg B \le d` form a closed set :math:`S_d` +defined over :math:`\mathbb{Q}`: :math:`A/B` is one exactly where :math:`A \wedge B \ne 0` and +:math:`B\, L A - A\, L B = 0`, :math:`L` the Lie derivative, a condition linear in :math:`A \wedge +B` and so closed on the Grassmannian of planes of polynomials of degree at most :math:`d`, whose +projection onto the parameters is closed since the Grassmannian is projective. A point +:math:`\theta^\ast`, rational or algebraic, outside every :math:`S_d` puts a generic point outside +every :math:`S_d`: the premise of Proposition 1 holds. + +*The test.* symident takes the constant inputs at random values and the equilibrium first: the +states at random values away from zero, the parameters in products of parameters at random values +until the balances are linear in the others, and those solved over the field :math:`F` of the point +(:math:`\mathbb{Q}`, or :math:`\mathbb{Q}(\alpha)` below), in a random order of the parameters; a +point that forces a parameter to zero is not taken. Where the balances have no such solution, it +draws :math:`\theta^\ast`, solves :math:`f = 0` and :math:`\ell = \gamma^\ast` at random +:math:`\gamma^\ast` with msolve over :math:`\mathbb{Q}`, and takes each Galois orbit of the at most +120 equilibria as a number field :math:`F = \mathbb{Q}[s]/(W)`, :math:`W` monic over +:math:`\mathbb{Z}` of degree at most 12. :math:`J = Df(x^\ast)` over :math:`F` splits into diagonal +blocks, the strongly connected components of the nonzero entries. :math:`CJ = 0` gives :math:`J` the +eigenvalue 0 at least :math:`c` times, and the eigenvalues of :math:`J` on the tangent space of the +level set are the others. With :math:`\chi_j` the characteristic polynomial of block :math:`j` +without the factor :math:`z^{m_j}`, :math:`\sum_j m_j = c`, of degree :math:`n_j`, these eigenvalues +are linearly independent over :math:`\mathbb{Q}` if + +(a) the Galois group of each :math:`\chi_j` over :math:`F` acts 2-transitively on the roots, + +(b) the splitting fields :math:`L_j` of the blocks with :math:`n_j \ge 2` are pairwise distinct, and + +(c) the traces :math:`t_j` of the blocks are linearly independent over :math:`\mathbb{Q}`. + +*Proof.* The group :math:`G` of the compositum over :math:`F` permutes the eigenvalues, so the +:math:`F`-linear relations among them form a submodule :math:`R` of :math:`\bigoplus_j F^{n_j}`. +:math:`F^{n_j}` is the trivial module plus :math:`V_j`, the vectors of sum zero, which is absolutely +irreducible since the permutation character of a 2-transitive group is the trivial character plus an +irreducible one :cite:p:`Isaacs1976` (Chapter 5); :math:`G` acts on :math:`V_j` faithfully through +:math:`\mathrm{Gal}(L_j/F)`, so by (b) the :math:`V_j` are pairwise non-isomorphic. :math:`R` is the +sum of the intersections of :math:`R` with the isotypic parts. :math:`R \supseteq V_j` would make +two roots of :math:`\chi_j` equal, which is irreducible by (a) and so separable; so :math:`R` lies +in the span of the block sums, and a relation over :math:`\mathbb{Q}` is :math:`\sum_j c_j t_j = 0` +with :math:`c_j \in \mathbb{Q}`, which (c) excludes. :math:`\square` For one block this is a case of +:cite:p:`Girstmair1999`: with the Galois group :math:`S_n`, the only linear relation among the roots is a +vanishing trace. + +(a) and (b) follow from Frobenius elements. At a prime :math:`\mathfrak{p} = (p, s - \tau)` of +degree one, with :math:`W` square-free modulo :math:`p` (so that :math:`\mathbb{Z}[s]` is maximal at +:math:`p`), the entries of :math:`J` integral at :math:`p` and :math:`\chi_j` square-free modulo +:math:`\mathfrak{p}`, the degrees of the irreducible factors of :math:`\chi_j` modulo +:math:`\mathfrak{p}` are the cycle type of a Frobenius element on the roots (Dedekind, +:cite:p:`Neukirch1999`, Chapter I). Reduction commutes with the characteristic polynomial, so it is taken +of :math:`J` modulo :math:`\mathfrak{p}`. The multiplicity of the eigenvalue 0 of a block over +:math:`F` is at most the one modulo :math:`\mathfrak{p}`, and the multiplicities add up to at least +:math:`c`; a prime where those modulo :math:`\mathfrak{p}` add up to :math:`c` gives the +:math:`m_j`. An :math:`n_j`-cycle makes the group transitive, an :math:`(n_j - 1)`-cycle then +2-transitive; a cycle type with one 2-cycle and odd cycles otherwise gives a transposition, and the +group is :math:`S_{n_j}` (``group``). Equal splitting fields would let one Frobenius element act on +both blocks, with the same order: a prime at which the orders differ proves (b). The primes are read +from 10007 on, at most 3000 prime ideals. Rational traces of two blocks are always dependent over +:math:`\mathbb{Q}`, and so are traces that an identity of the balances ties with a factor rational +in the states; where (c) fails with :math:`r` blocks, the point is drawn again in +:math:`\mathbb{Q}(\alpha)`, :math:`\alpha` a root of an irreducible polynomial of degree :math:`r`, +the states of a chosen equilibrium as well. The test refuses, with the reason, where the eigenvalue +0 is more frequent than the laws give (a state without dynamics is a law) or a single trace is 0, +the equilibria form a family, or the primes read do not show the cycles. +``info["discrete"]["experiments"]["first_integrals"]`` holds :math:`\theta^\ast`, :math:`F`, the +equilibrium and per block the primes of the cycles. + +*The count.* For :math:`K = 2, \dots, \min(8, \lceil n_\theta / n_y \rceil + 1)`, :math:`n_\theta` +the coordinates other than the starts and :math:`n_y` the observables, the stacked model gets the +orders of the rank criterion; the :math:`K` with the lowest highest order is taken, the fewest +experiments among equal ones, and the orders rise as in the count of one experiment. The count +modulo :math:`p` is that of the distinct values of a random linear form in :math:`(\theta', x_0'^1)` +on the points of each block (the projection of a product is the product of the projections); a +coordinate outside the projection is substituted as a jet is, a coordinate inside only for a +monomial in the coordinates inside, and a count by stages adds the counts of the rest over the +points of a stage, at least the number of distinct projections. + +*The verified count.* :eq:`eq-count-bound` holds for the :math:`K` experiments as one model, with +the projection: in Step 2, :math:`\lambda` is a linear form in :math:`(\theta', x_0'^1)` that +separates the projections of the at most :math:`D` points of :math:`V_0` over :math:`\mathbb{Q}( +\theta, x_0^1, \dots, x_0^K)`, and in Step 3 the values of :math:`\lambda` stay distinct at the +random point, so the solutions there have at least :math:`|\pi(T_K)|` distinct projections, with +:math:`D` and :math:`N_u` those of the stacked system. Over :math:`\mathbb{Q}` a block of at most 64 +points counts the distinct values of the projected coordinates on the points of the rational +parametrization: with :math:`w` the square-free eliminating polynomial, :math:`\mathbb{Q}[t]/(w)` is +the algebra of functions on the points, and the dimension of the subalgebra the projected +coordinates generate, found by exact linear algebra, is the number of their distinct values; a +larger block counts all points. Either count bounds :math:`|\pi(T_K)|`, and by Proposition 1 it +bounds :math:`|T|`. + +*The orbit.* The exact maps form a group :math:`G` that acts on :math:`T` without fixed points at a +generic point: an element that fixes a point of :math:`T` fixes a point with algebraically +independent coordinates and is the identity. So :math:`T` is a union of orbits of :math:`|G|` +points, :math:`|G|` divides :math:`|T|`, and a count below :math:`2|G|` proves :math:`|T| = |G|`: +``count_final``, ``complete: "verified"`` with ``count_bound`` where the count over +:math:`\mathbb{Q}` is below :math:`2|G|`, else ``"axiom"``. The certificate lists the route +(``route``: the number of experiments, the orders, the count and the premise) and adds the premise +and the divisibility to ``proven``. ``experiments`` of :meth:`~symident.Symmetries.discrete` takes +the route first, with ``True`` or a number of experiments; by default it runs where a short count of +one experiment finds none, after the exact count and before the full count. Where the count of one experiment fails too, the count of the experiments stands for it +without maps. A fixed start (a known initial value, a start at rest, :math:`\nu(0) = 1` of the +relaxed model, a start fixed by a reduction), events, conditions, switches or the clock in the +equations leave the route out, and ``info["discrete"]["experiments"]["why"]`` names the reason. + +.. _monodromy: + +Monodromy and certified points +------------------------------ + +Where the exact maps have an orbit smaller than the count, or no count exists, points of the fiber +are proposed numerically at a random rational point :math:`\theta^\ast`. The coefficients are +evaluated by the recursion of the series in complex floating point, with gradients in the +coordinates, never expanded. :math:`n` coefficients :math:`c_I` whose gradients are independent at a +random point modulo a prime, lowest order first, form a square system :math:`c_I(x) = w`. The +coordinates range over :math:`\mathbb{C}^n`, which is irreducible, so the monodromy group of +:math:`c_I` acts transitively on the fiber of :math:`c_I` over a value off the branch locus +:cite:p:`Duff2019`: from :math:`x = \theta^\ast` over :math:`w_0 = c_I(\theta^\ast)`, the known points are +tracked along the triangle :math:`w_0 \to w_1 \to w_2 \to w_0`, :math:`w_1, w_2` random complex +vectors, by an Euler predictor and a Newton corrector with step control, and the end points join +the known ones, until five triangles add none or as many points of the fiber as the count are +known. This runs where :math:`c_I` has at most 200 points modulo a prime at a random point, since +the fiber of :math:`c_I` holds the fiber of the model several times over; otherwise, or where it +stops short, the points are the roots of the rational parametrization of msolve over +:math:`\mathbb{Q}` at :math:`\theta^\ast`, taken numerically. A point is kept where every coefficient +up to the order of the count agrees with the one at :math:`\theta^\ast` to a relative +:math:`10^{-7}`. ``info["discrete"]["monodromy"]`` lists the number of points, the source, the +number of points of :math:`c_I` modulo the prime, the boxes below and the maps. + +*Proposition* (Krawczyk :cite:p:`Krawczyk1969,Moore1977,Rump2010`). Let :math:`\phi: U \to \mathbb{C}^n` +be holomorphic, :math:`X \subset U` a product of closed complex rectangles :math:`X_i` with radii +:math:`r_i > 0`, :math:`m \in X`, :math:`Y` a complex :math:`n \times n` matrix and :math:`J(X)` a +matrix of rectangles that holds :math:`\partial \phi(\xi)` for every :math:`\xi \in X`. Let +:math:`E = I - Y J(X)` and :math:`K = m - Y \phi(m) + E\, (X - m)` in rectangle arithmetic. If +:math:`K_i` lies in the interior of :math:`X_i` and :math:`\sum_j |E_{ij}|\, r_j < r_i` for every +:math:`i`, with :math:`|E_{ij}|` the largest modulus on the rectangle, then :math:`\phi` has exactly one +zero in :math:`X`, and :math:`\partial \phi` is invertible there. + +*Proof.* Let :math:`k(x) = x - Y \phi(x)`. For :math:`x, x' \in X` the segment between them lies in +the convex :math:`X`, and :math:`\phi_l(x) - \phi_l(x') = \int_0^1 \partial \phi_l(x' + s(x - x'))\, ds\, +(x - x')`; the integral lies in the closed convex row :math:`J_l(X)`. So :math:`k(x) - k(x') = (I - +Y \bar J)(x - x')` with every row of :math:`\bar J` in :math:`J(X)`, the entries of :math:`I - Y +\bar J` lie in those of :math:`E`, and in the norm :math:`\max_i |v_i| / r_i` the map :math:`k` is +a contraction on :math:`X`. With :math:`x' = m`, :math:`k(x) \in K \subset X`. By Banach's fixed +point theorem :math:`k` has exactly one fixed point :math:`x^\ast` in :math:`X`. The row sums give +:math:`\|I - Y \bar J\| < 1` for every such :math:`\bar J`, so :math:`Y \bar J` and :math:`Y` are +invertible: :math:`Y \phi(x^\ast) = 0` gives :math:`\phi(x^\ast) = 0`, every zero of :math:`\phi` in +:math:`X` is a fixed point of :math:`k`, and :math:`\partial \phi(x^\ast)` is invertible. :math:`\square` + +For a kept point :math:`\hat x`, :math:`\phi = c_{I'} - c_{I'}(\theta^\ast)` with :math:`n` rows +:math:`I'` of the coefficients up to the order of the count, chosen by a QR decomposition with +pivoting of the Jacobian at :math:`\hat x` with rows of unit norm, :math:`m = \hat x`, :math:`Y` a +floating-point inverse of the Jacobian at :math:`\hat x` and radii :math:`10^{-10}` and then +:math:`10^{-7}` times :math:`1 + |\hat x_i|`. :math:`\phi(m)` and :math:`J(X)` are evaluated by the same +recursion in rectangle arithmetic: every operation in IEEE double precision is correctly rounded, so +the result moved by one floating-point number outward encloses the exact one, and the enclosures +hold the exact values for every point of the operands; :math:`\theta^\ast` and the constants enter +as enclosures of the rationals. Boxes with disjoint rectangles in some coordinate hold distinct +zeros, so the boxes kept, pairwise disjoint, prove that many simple zeros of :math:`\phi` +(``certified``). These are zeros of the square system: a point of the fiber needs every +coefficient equal, an identity that no enclosure shows, since an overdetermined system loses the +solutions under any perturbation. The certified boxes are therefore no lower bound of the count; +the lower bound is the orbit of the exact maps. Where the enclosures of the recursion grow past the +radii, the point stays without a box. + +A map is read from a point :math:`\hat x \ne \theta^\ast`: each image coordinate is matched to +:math:`c\, \theta_j^{\pm 1}` or :math:`\theta_i + d` with Gaussian rationals :math:`c, d` of +denominators up to 12 that reproduce :math:`\hat x_i`, and a combination is kept where the +coefficients at two random points and their images agree to a relative :math:`10^{-7}`. Nothing is +concluded from these numbers: a map proposed so is ``exact`` once the identities of :ref:`maps` +hold over :math:`\mathbb{Q}(i)(x, \theta)`, and then joins the group :math:`G`. A map +over :math:`\mathbb{Q}(i)` whose image of a real point is not real never meets :math:`\Theta`. For +such maps the theorem of the exact count holds as stated: the proof uses that the orbit of +:math:`\theta` lies in :math:`T` and has :math:`|G|` points, that :math:`P_\alpha \in F[Z]`, whose +coefficients are checked to lie in :math:`\mathbb{Q}(\theta)`, and that :math:`L = F(\alpha)`. + +.. _certificates: + +Certificates +------------ + +``info["discrete"]["certificate"]`` states what the count rests on, and ``complete`` sums it up: + +``"exact"`` + the field fixed by the exact maps lies in the field of the output coefficients + (:ref:`exact-count`), so the fiber at a generic point is the orbit of the exact maps; no random + step enters. +``"verified"`` + a count over :math:`\mathbb{Q}` at a random integer point equals the orbit, directly + (:ref:`verified-count`) or for several experiments (:ref:`several-experiments`), with the + probability ``count_bound`` that the fiber at a generic point has more points. +``"axiom"`` + the count holds under an axiom: that the count modulo the prime at a random point is the count + over :math:`\mathbb{C}` at a generic point, or a premise of the rewrites (``premise``), such + as the algebraic independence of the starts of new coordinates; ``count_bound_why`` names the + reason. +``"no"`` + the count exceeds the orbit of the exact maps: further points exist at the sample point, and + the maps between them are not proven. +``"open"`` + no count or no orbit was reached; ``limits`` names the work limits that stopped the analysis. + +``count_final`` is true where the exact maps account for every point of the count. Each map has a +``level``: ``exact`` with a map of the states (:ref:`maps`), ``checked`` where the coefficients +agree at random points. ``preserves_domain`` and ``domain_conditions`` say whether the map keeps +:math:`\Theta`, and ``count_domain`` gives the number of points of the fiber in +:math:`\Theta` where it is exact. The rewritten model and the result in it are listed under +``rewrites``, ``relaxed`` and ``start_powers``. diff --git a/docs/method/local.rst b/docs/method/local.rst new file mode 100644 index 0000000..a8f0c6e --- /dev/null +++ b/docs/method/local.rst @@ -0,0 +1,466 @@ +Local analysis +============== + +The local analysis decides the rank of the observability-identifiability matrix (OIM) and returns +the kernel, the non-identifiable directions at generic coordinates. The OIM is evaluated over +finite fields :math:`\mathbb{F}_p`; the order is certified sufficient where a proven upper bound +of the rank is reached. + +.. _oim: + +Lie derivatives and the observability-identifiability matrix +------------------------------------------------------------ + +The *Lie derivatives* of the output are + +.. math:: + :label: eq-lie + + L_F^0 h = h, \qquad L_F^{k+1} h = F\big(L_F^k h\big). + +For analytic models they determine the output: near :math:`t_0` it is the Lie series + +.. math:: + :label: eq-lie-series + + g(t; \theta) = \sum_{k \ge 0} \frac{(t - t_0)^k}{k!}\, L_F^k h\big(z_0(\theta)\big), + +and elsewhere the analytic continuation of this series, so equal Lie derivatives at :math:`t_0` give equal +outputs :cite:p:`Pohjanpalo1978`. The Lie derivatives up to the *Lie order* :math:`N`, +differentiated with respect to :math:`\theta`, + +.. math:: + :label: eq-oim + + \Psi_N(\theta) = \big(h, L_F^1 h, \dots, L_F^N h\big)\big(z_0(\theta)\big), \qquad + \mathrm{OIM}_N(\theta) = \frac{\partial \Psi_N}{\partial \theta}, + +give the *observability-identifiability matrix* (OIM) :cite:p:`Villaverde2016`. The *rows of +order* :math:`k` are the gradients :math:`\partial_\theta\, L_F^k h_i(z_0(\theta))`, +:math:`i = 1, \dots, n_y`. A generator leaves :math:`\Psi_N` unchanged, so the value of the generator lies in +:math:`\ker \mathrm{OIM}_N(\theta)` for every :math:`N`. Conversely, where the rank of +:math:`\mathrm{OIM}_N` is the largest over all orders and all :math:`\theta`, which holds for +generic :math:`\theta`, every vector of the kernel is the value of a generator: the kernels +have constant dimension there, so a smooth vector field with values in them extends any +kernel vector, and along the flow of that field every Lie derivative, and by Equation :eq:`eq-lie-series` +the output, stays constant. The model is therefore locally structurally identifiable when +:math:`\mathrm{OIM}_N` has rank :math:`d` for some :math:`N`, and the *non-identifiable +directions* are the vectors of the kernel. + +For the example of Equation :eq:`eq-example` the first Lie derivatives are + +.. math:: + + L_F^0 h = s B, \qquad L_F^1 h = s\,(k_1 A - k_2 B), \qquad + L_F^2 h = s\,\big(k_2^2 B - k_1 (k_1 + k_2) A\big), + +evaluated at :math:`(A, B) = (A_0, B_0)`. The rows of :math:`\mathrm{OIM}_N` reach rank four, +and the kernel is spanned by the value of the generator above. + +.. _finite-fields: + +Ranks over finite fields +------------------------ + +symident evaluates :math:`\mathrm{OIM}_N` exactly over :math:`\mathbb{F}_p` in a compiled +*modular engine*: the Lie derivatives as power series in time truncated at order :math:`N`, +the derivatives with respect to :math:`\theta` as dual numbers, all rows at a point in one pass +:cite:p:`Sedoglavic2002`. A point can only underestimate the generic rank, and a random point does so +with small probability :cite:p:`Schwartz1980,Zippel1979`. The rank of the result is taken at the +base point, as the largest over the four engine primes. Randomness enters through the points +uniform modulo the verification prime: one point that checks the rank of the *saturation*, +i.e., of the order chosen, and the points that check closed forms. + +.. _sufficient-lie-order: + +Sufficient Lie order +-------------------- + +The Lie order :math:`N` has to stop, and a rank that stays constant for a few orders is not +final at a special start, such as an initial value fixed to a number, a resting state or the +state after a dose. For :math:`\dot x = \theta`, :math:`h = x^m` and :math:`x_0 = 0`, every +row below order :math:`m` vanishes, and only the row of order :math:`m` shows that +:math:`\theta` is identifiable. symident therefore stops at a proven upper bound of the rank, +the *ceiling* below :cite:p:`HermannKrener1977`. + +Let :math:`D_k` be the matrix of the gradients :math:`\partial_z L_F^j h_i`, :math:`j \le k`, +:math:`i \le n_y`, and :math:`S` an irreducible variety of points :math:`z` that is invariant +under :math:`F`. By the chain rule, +:math:`\mathrm{OIM}_k(\theta) = D_k\big(z_0(\theta)\big)\, \partial_\theta z_0(\theta)`. + +**Lemma.** At a generic point of :math:`S`, once :math:`\operatorname{rank} D_{k+1} = +\operatorname{rank} D_k` for one :math:`k`, the rank stays the same for every later order. + +*Proof.* Let :math:`\Omega_k` be the span of the rows of :math:`D_k` over the rational +functions on :math:`S`. A row is a one-form :math:`\omega = \sum_i \omega_i\, \mathrm{d}z_i`, +and the Lie derivative of :math:`\omega` along :math:`F` is +:math:`(\mathcal{L}_F \omega)_i = \sum_j F_j\, \partial_{z_j} \omega_i + \sum_j \omega_j\, +\partial_{z_i} F_j`. It is additive, satisfies :math:`\mathcal{L}_F(a\, \omega) = F(a)\, \omega ++ a\, \mathcal{L}_F \omega` for functions :math:`a`, and by the chain rule +:math:`\mathcal{L}_F\, \partial_z \varphi = \partial_z F(\varphi)`, so it maps the row of +:math:`L_F^j h_i` to that of :math:`L_F^{j+1} h_i`. Hence + +.. math:: + :label: eq-filtration + + \mathcal{L}_F \sum_{j \le k} a_j\, \partial_z L_F^j h_i + = \sum_{j \le k} F(a_j)\, \partial_z L_F^j h_i + \sum_{j \le k} a_j\, \partial_z L_F^{j+1} h_i . + +If :math:`\Omega_{k+1} = \Omega_k`, the right-hand side lies in :math:`\Omega_k` for every +element of :math:`\Omega_k`, so :math:`\Omega_k` is invariant under :math:`\mathcal{L}_F` and +contains every later row. :math:`\square` + +Let :math:`\rho_S`, the *ceiling*, be this final rank at a generic point of :math:`S`. + +**Proposition.** Let :math:`S` contain the start :math:`z_0(\theta)` of every +:math:`\theta \in \Theta`. If at one start :math:`z_0(\theta^\ast)` the rank of :math:`D_N` +equals :math:`\rho_S`, then :math:`\ker \mathrm{OIM}_k(\theta) = \ker \mathrm{OIM}_N(\theta)` +for all :math:`k \ge N`, both at :math:`\theta^\ast` and at generic :math:`\theta`. + +*Proof.* By the lemma no :math:`D_k` exceeds rank :math:`\rho_S` on :math:`S`, so every minor +of size :math:`\rho_S + 1` vanishes on :math:`S`, and :math:`\operatorname{rank} D_k \le +\rho_S` at every point of :math:`S`. The rank of :math:`D_N(z_0(\theta))` is the rank of a +matrix rational in :math:`\theta`, so at generic :math:`\theta` it is at least the value at +:math:`\theta^\ast`, hence equal to :math:`\rho_S`. Wherever it equals :math:`\rho_S`, the row +spaces of :math:`D_k(z_0(\theta))`, :math:`k \ge N`, contain that of :math:`D_N` and have +dimension at most :math:`\rho_S`, so they coincide, and so do the kernels after multiplication +by :math:`\partial_\theta z_0`. :math:`\square` + +The proposition is what the checks of closed forms need: they run at random coordinate values, +at the order certified at one start. A *resting point* :math:`z_*` is one with +:math:`f(z_*) = 0`; for an autonomous model, where :math:`t` is dropped from :math:`z`, +:math:`F(z_*) = 0` there, and the rows form a *Krylov sequence*, each the previous one times +the same matrix, + +.. math:: + :label: eq-krylov + + \partial_z L_F^{k+1} h(z_*) = \partial_z L_F^k h(z_*)\; \partial_z F(z_*), + +so there one order without change of rank is final at the point itself. + +**The set** :math:`S`. Without ``equilibrate``, :math:`S` consists of the starts shifted by a +subspace :math:`U` of the states, +:math:`S = \{z_0(\theta) + (b, 0, 0) : \theta \in \Theta,\ b \in U\}`, with :math:`U` the +smallest subspace for which :math:`F` stays in :math:`U \times \{0\} \times \mathbb{R}` on +:math:`S`. It is built from :math:`U = \{0\}` by adding the state part of :math:`F` at a random +point of the current :math:`S` until that part lies in :math:`U`. This covers a start at rest, +a subsystem at rest, states that stay at zero, fixed initial values, and linear relations the +dynamics keeps. Under ``equilibrate`` every start is a resting point, and :math:`S` is the +resting variety of the condition (:ref:`steady-states`), on which :math:`f = 0`; a generic point of it +is a random coordinate value with the resting state solved there (the first of 24 draws with a +root). In both cases the rank at the start is taken at the base point. Where the start does +not reach :math:`\rho_S`, e.g., on the level set of a nonlinear conserved quantity, no order +is proven sufficient. The order then stops after a *plateau*, three orders without change of +rank (``SYMIDENT_LIEPLATEAU``), and the result says that the Lie order is not proven +sufficient. + +**Conditions and events.** The rows of several conditions are stacked, and their row space +stops changing once that of every condition has stopped, so every condition is expanded to +a separate order. An event moves the start of the next segment: a state replaced by a value of +the coordinates is removed from :math:`U`, a value added keeps :math:`U`, and an event that +multiplies a state or reads the states adds that state's direction to :math:`U`. The +proposition extends to the power series of :ref:`conditions-events` and is checked at a +vanishing gap. + +**Random points.** :math:`U` and :math:`\rho_S` are taken at points uniform modulo the +verification prime :math:`p`. They are wrong only where a polynomial vanishes: the state part +of :math:`F` at the step that ends :math:`U`, or a minor of size :math:`\rho_S` of the rows of +an order, both composed with the start. Since the generic ranks rise strictly up to their final +value, orders up to the number of columns plus one reveal a wrong plateau. A point is the first of +the draws without a pole of the starts, up to 8, or on a resting variety the first with a root, up +to 24. The probability of a wrong certificate is bounded in :ref:`order-bound`. + +**Without a stopping rule.** A direction that is an exact symmetry, i.e., a scaling under +which every expression is homogeneous (:ref:`scalings`) or a field with the identities of +:ref:`proofs-over-q`, lies in the kernel at every order, so a rank that together with such +independent directions gives :math:`d` is proven for all orders. ``engine="symbolic"`` computes +the Lie derivatives over the rational functions and confirms the order by an exact rank: +where the rows at the initial values reach the generic rank, a nonvanishing minor makes every +later row a combination of earlier ones. Where no order is proven sufficient, a *saturation +guard* (``verify=True``) takes the rank at the base point again six orders further +(``SYMIDENT_VERIFY_MARGIN``) and the gap order of :ref:`conditions-events` two orders further. +If the rank grows, the detection is repeated from that order, up to three times; if it still +grows, the rank is a lower bound, ``info["verification"]`` says where, and a reduction is +refused. + +.. _order-bound: + +Error probability of the order +------------------------------ + +The random choices are the verification prime :math:`p`, drawn per detection from the seed of the detection, and +points uniform modulo :math:`p`, each from a separate seed. All error bounds of symident rest on +the Schwartz-Zippel lemma :cite:p:`Schwartz1980,Zippel1979`: a nonzero polynomial of degree +:math:`D` in :math:`m` variables over a field vanishes at a point drawn uniformly from +:math:`A^m`, for a finite subset :math:`A` of the field, with probability at most :math:`D / |A|`. + +A wrong certificate of the Lie or gap order needs a polynomial to vanish at one of the random +points of :ref:`sufficient-lie-order` or :ref:`conditions-events`: the step that ends the +subspace :math:`U`, or a minor of the rows of an order. The degree of the polynomial is that of the rational system +the modular engine evaluates, with exponentials, free powers and trigonometric functions as +separate states, multiplied by the degree :math:`\deg z_0` of the start, and on a resting variety +by the Bezout number of the balances, Equation :eq:`eq-rest-bound`. The probabilities add up to +``info["order_bound"]``, each multiplied by the number of points drawn until the point was taken, +since the point taken is wrong only if one of them is; ``info["order_draws"]`` is the largest such +number, and the points of the gap order are drawn once. ``info["order_bound_why"]`` names the +reason for a missing bound. + +.. _non-rational: + +Non-rational terms +------------------ + +The modular engine needs rational functions. Elementary functions are therefore recast into +rational form :cite:p:`Savageau1987`, type by type in a fixed order and innermost first within a type; +a nesting across that order, such as :math:`\sin(\exp x)` or :math:`\exp(\arctan x)`, is +refused. A term :math:`\nu = \varphi(\psi)` with :math:`\psi` rational in the states becomes a +new state with right-hand side :math:`\varphi'(\psi)\, \sum_j \partial_{x_j} \psi \, f_j`, +which is rational in :math:`\nu` and :math:`\psi` for + +.. math:: + + \varphi(\psi) = \psi^\alpha:\ \ \frac{\alpha\, \nu}{\psi}, \qquad + \exp(\psi):\ \ \nu, \qquad \log(\psi):\ \ \frac{1}{\psi}, \qquad + \arctan(\psi):\ \ \frac{1}{1 + \psi^2}, \qquad \operatorname{artanh}(\psi):\ \ \frac{1}{1 - + \psi^2}, + +and for :math:`\arcsin`, :math:`\arccos`, :math:`\operatorname{arsinh}` and +:math:`\operatorname{arcosh}` contains a square root, which is recast in turn. Trigonometric +functions go through :math:`\tan(\psi/2)`. A *free power* :math:`b^\mu`, with a parameter +:math:`\mu` as exponent, becomes a state :math:`B = b^\mu` with companion :math:`L_b = \log b`, +so that the field is rational and :math:`\mu` enters through :math:`\partial B / \partial \mu += B L_b`. + +Under ``equilibrate`` a power :math:`b^\mu` of a positive rational number :math:`b` is +rewritten first: next to a power :math:`c^\mu` of a symbol +:math:`c` with the same exponent, :math:`c` stands for :math:`b c` throughout, +:math:`(b c)^\mu` being a power of one symbol, and the result is mapped back. Otherwise +:math:`b` is a constant with :math:`\log b` taken independent of the other constants, as for +logarithms of numbers in log coordinates (named in ``info["limits"]``). + +A new state starts at :math:`\varphi(\psi)` of the initial state. Where this depends on the +coordinates, a transcendental :math:`\varphi` becomes a separate input of the modular engine, +a *leaf*, drawn independently of the argument and tied to it by relation rows +:math:`\mathrm{d}\nu = \varphi'(\psi)\, \mathrm{d}\psi`: a transcendental graph lies in no proper +variety, so a random point on it is generic. With several transcendental constants, such as +:math:`e` and :math:`\pi`, this needs their algebraic independence, which follows from +Schanuel's conjecture and is not proven. An algebraic :math:`\varphi`, a root or rational power, +is exact: through :math:`L = \log \psi` when :math:`\psi` is affine in one coordinate, else by +the root modulo the prime at each sample point, over primes in which every root of the model +exists. Logarithms, fractional powers and bases of free powers are real for a positive argument. +The rank and the kernel are taken at generic points, where every argument is nonzero, so the +detection needs no sign. An argument that the declared signs do not make positive on +:math:`\Theta`, also in initial and event values, is named in ``info["limits"]``. An observable +:math:`\kappa \sum_i a_i \log \rho_i + \beta`, with rational :math:`\rho_i` and constants +:math:`\kappa, a_i, \beta`, is strictly monotone in :math:`\prod_i \rho_i^{a_i} e^{\beta/\kappa}` +and is analyzed as that product. + +An event after the start reads the states just before it. There the state propagated across the +gaps is a power series in the gap lengths whose constant term :math:`\bar x` is the state at zero +gaps, the initial state with the earlier events of the condition applied. A transcendental +:math:`\varphi(\psi(x))` in an event value is the leaf :math:`\varphi(\bar\psi)`, +:math:`\bar\psi = \psi(\bar x)`, times or plus a series in :math:`\psi(x) - \bar\psi`, + +.. math:: + + e^{\psi} = e^{\bar\psi}\, e^{\psi - \bar\psi}, \qquad + \log \psi = \log \bar\psi + \log\Bigl(1 + \frac{\psi - \bar\psi}{\bar\psi}\Bigr), \qquad + \psi^\alpha = e^{\alpha \log \psi}, \qquad + \sin \psi = \sin \bar\psi \cos(\psi - \bar\psi) + \cos \bar\psi \sin(\psi - \bar\psi), + +and since :math:`\psi(x) - \bar\psi` has no constant term, each series ends at the truncation +order; :math:`\cos` and :math:`\tan` follow from the addition theorems. An event on a state +moves the new states of the recast with it, :math:`\nu` to +:math:`\varphi` of :math:`\psi` after the event, so a dose added to a state under a free power +moves :math:`B` and :math:`L_b`, and in log coordinates :math:`L = \log x` becomes +:math:`\log(e^{L} + d)`. Under ``equilibrate`` :math:`\bar x` is the resting state, a +coordinate, and an event at the start takes the leaves at it alone. + +**Terms of resting states.** Under ``equilibrate`` a transcendental term +:math:`\varphi(\psi(x, \theta))` of the states is a leaf :math:`W` in the balances as well, the +same leaf as the initial value of the new state :math:`\nu`. The balances are then rational in +the resting states, the coordinates and the leaves, and the relation rows +:math:`\mathrm{d}W = \varphi'(\psi)\, \mathrm{d}\psi` tie each leaf to the state columns and the +coordinates of the joint kernel (:ref:`steady-states`). The leaves are drawn independently of the +resting states, and the resting states are solved from the balances at the drawn values. Let +:math:`M = \{(\theta, x, W) : f(x, \theta, W) = 0,\ W = \varphi(\psi(x, \theta))\}` be the +resting set and :math:`A` the component of the algebraic set :math:`\{f(x, \theta, W) = 0\}` on +which the drawn points lie. Rank and kernel are rational in :math:`(\theta, x, W)`, so their +generic values on :math:`A` are those on :math:`M` when :math:`M` is Zariski dense in :math:`A`. +This holds under two conditions. First, let :math:`H` be the states and :math:`\theta_A` the +coordinates inside the arguments :math:`\psi`. The resting values :math:`x_H` vary independently +of :math:`\theta_A`, i.e., the tangent space of the resting set projects onto the coordinates +:math:`(\theta_A, x_H)`. Then :math:`(\theta_A, x_H)` and further coordinates form a chart of +:math:`M` in which every argument is rational. Second, no nontrivial integer combination of the +arguments is constant, which the recast ensures by one leaf per basis term, as for leaves of +coordinates. The density then follows from a classical lemma, the exponential case of the +Kolchin-Ostrowski theorem :cite:p:`Kolchin1968`, which extends the case of integrals :cite:p:`Ostrowski1946` +to exponentials of integrals: exponentials :math:`e^{\psi_1}, \dots, e^{\psi_n}` of rational +functions :math:`\psi_i \in \mathbb{C}(z)` are algebraically independent over +:math:`\mathbb{C}(z)` if and only if no nontrivial integer combination :math:`\sum_i n_i \psi_i` +is constant. Proof of the direction used: an algebraic relation reads +:math:`\sum_a c_a(z)\, e^{\langle a, \psi \rangle} = 0` with rational :math:`c_a \neq 0` and +distinct integer vectors :math:`a`, whose exponents differ pairwise by nonconstant functions. On +a generic line through the domain this stays so, with one variable :math:`t`. Take a relation +with the fewest terms, divide by the last term and differentiate in :math:`t`. The constant term +drops, and the other terms :math:`r_j e^{h_j}` become :math:`(r_j' + r_j h_j') e^{h_j}`, a +shorter relation, so every :math:`r_j' + r_j h_j' = 0`. Then :math:`e^{h_j}` is a constant over +:math:`r_j`, a rational function, which a nonconstant rational :math:`h_j` excludes. Logarithms +of rational functions no product of integer powers of which is constant, such as distinct +irreducible factors, are algebraically independent in the same way, and a half-angle tangent +:math:`\tan(\psi/2)` is rational in :math:`e^{i\psi}`. Ax's theorem :cite:p:`Ax1971`, a functional form +of Schanuel's conjecture, generalizes the lemma. The image of :math:`M` is therefore dense in +the space of the chart and the leaves, which has the dimension of :math:`A` where the resting +Jacobian is invertible, and :math:`M` is dense in :math:`A`. The first condition is checked at +the base point; where it fails, an ``InputError`` names the states. An example is +:math:`\dot x = k - x e^{x/k}`, whose resting value no coordinate outside the exponent moves. + +A state that enters the balances only through leaves, such as :math:`x` in :math:`\dot x = p - k +\sin x`, leaves the resting Jacobian singular with the leaves drawn. The resting value of such a +state is drawn, and one leaf of the state that enters the balance becomes a resting unknown, +solved from the balance; the points remain points of :math:`A`. +``info["settings"]["rest_leaves"]`` lists the resting states inside transcendental terms with +their leaves, and under ``drawn`` the states whose resting value is drawn. A leaf of a resting +state is one coordinate for all conditions, so conditions with different resting models are +refused for such a state. A root or rational power of an expression in the states in the resting +model has no leaf and is refused. + +.. _singular-starts: + +Singular starts +--------------- + +The Lie series of Equation :eq:`eq-lie-series` needs an output that is analytic at the start. +Two kinds of terms are not, although the output is analytic for :math:`t > t_0`: a quotient +whose numerator and denominator both vanish at the start, such as the fraction of a species in +one compartment when every compartment starts empty, and a free power :math:`x^\alpha` of a state +that starts at 0. In both cases the output has an expansion at :math:`t_0` whose +coefficients are rational in :math:`\theta`, and these coefficients take the place of the Lie +derivatives. In the following, :math:`t_0 = 0`. + +**Quotients at 0/0.** Let the right-hand side be analytic at the start and let the observable +read the states through a quotient :math:`N/D` whose denominator vanishes at :math:`z_0`. The +states are power series in :math:`t`, and so are :math:`N` and :math:`D`. Let :math:`v` be the +smallest order with :math:`D_v(\theta) \not\equiv 0`. Then + +.. math:: + :label: eq-laurent + + \frac{N}{D} = t^{-v}\, \frac{N}{D_v + D_{v+1} t + \dots}, + +a Laurent series whose coefficients are rational in :math:`\theta` where :math:`D_v(\theta) \ne +0`, and a power series when :math:`N` vanishes to order :math:`v` as well. The engine evaluates +every reciprocal outside the right-hand sides whose operand starts at 0 in this form, after the +states, with the dual numbers inside the coefficients: an operand :math:`a = t^{v}(U + M)`, +with :math:`U` a power series of nonzero constant value and :math:`M` the terms below +:math:`t^v`, which lie in the dual part and the monomials of the gap lengths, has the inverse +:math:`t^{-v} U^{-1} \sum_e (-M U^{-1})^e`, a finite sum since :math:`M` is nilpotent. Each +division costs :math:`v` orders, so the states are expanded further until every output is known +to the Lie order. Rows are the gradients of the coefficients of the output, and the +argument of :ref:`oim` holds for them +unchanged, since it uses only that the coefficients determine the output near the start. +The valuation :math:`v` is taken at the base point, where :math:`D_k(\theta) = 0` for +:math:`k < v` holds together with the gradient; a point where a coefficient that is not +identically zero vanishes gives the expansion of that point, whose rank is a lower bound. A pole +of the output itself is refused, and so is a reciprocal of an operand that starts at 0 inside +the right-hand sides. + +The stopping rule of :ref:`sufficient-lie-order` extends to these outputs. Let :math:`u(t) = +\partial_{z_0} g(t)` be the gradient of the output with respect to the start, a Laurent +series, possibly with a pole: away from the start the quotient is defined, and a start moved +off :math:`D = 0` gives a denominator of order 0. + +**Lemma.** Let :math:`U_\infty` be the span of the coefficients of :math:`u`. Then +:math:`\dim U_\infty \le \rho_S`. + +*Proof.* :math:`\dim U_\infty` is the number of functions among the components +:math:`u_i(t)` that are linearly independent over :math:`\mathbb{R}`, which equals the rank of +their Wronskian matrix :math:`\big(u^{(j)}(t)\big)_{j \ge 0}` over the meromorphic functions. +Along the solution :math:`\varphi_t(z_0)`, the chain rule gives :math:`u^{(j)}(t) = \partial_z +L_F^j h\big(\varphi_t(z_0)\big)\, \Phi(t)` with the invertible fundamental matrix :math:`\Phi(t) += \partial \varphi_t / \partial z_0`. For small :math:`t > 0`, :math:`\varphi_t(z_0)` is a point +of :math:`S`, which is invariant under the flow, where the output is defined, so by the lemma of +:ref:`sufficient-lie-order` the rank is at most :math:`\rho_S`. :math:`\square` + +The rows of the coordinates are the coefficients of :math:`\partial_\theta g = u\, +\partial_\theta z_0`. If the coefficients of :math:`u` up to order :math:`N`, those of negative +order included, reach rank :math:`\rho_S` at the start, they span :math:`U_\infty`, and the +rows up to order :math:`N` span all rows: the order is proven sufficient, as in the proposition +there. The coefficients at the base point are those of generic :math:`\theta` unless the base +point lies where a leading coefficient vanishes; this event is not counted in +``info["order_bound"]``. + +**Free powers of a state at 0.** Let a state :math:`x` start at 0 in every condition and enter +through powers :math:`x^{c_0 + c\alpha}`, with integers :math:`c_0 \ge 0`, :math:`c > 0` and a +coordinate :math:`\alpha > 0` as exponent. Generically :math:`x = c_x t^k (1 + O(t))` with +:math:`k \ge 1` and :math:`c_x \neq 0`, so :math:`x^\alpha` behaves as :math:`t^{k\alpha}`, which +is not analytic at 0 for :math:`\alpha \notin \mathbb{N}`. The recast :math:`B = x^\alpha` of +:ref:`non-rational` needs :math:`x \ne 0` at the start. Instead, with the formal variable +:math:`S = (c_x t^k)^\alpha`, + +.. math:: + :label: eq-start-power + + x^\alpha = S\, Q, \qquad Q = \Big(\frac{x}{c_x t^k}\Big)^{\alpha}, + +where :math:`Q` is a power series in :math:`t` with constant term 1. Every state and output +becomes a power series in :math:`t` and :math:`S`. A coefficient of :math:`t^n S^m`, kept with +the *index* :math:`n` (the exponent of :math:`t` at :math:`\alpha = 1`, so :math:`n \ge km`), +stands for the function :math:`t^{n - km + km\alpha}`. Differentiation in :math:`t` maps it to +:math:`\lambda_{n,m} = n + km(\alpha - 1)` times the coefficient of index :math:`n - 1`, so the +states follow from :math:`\lambda_{n+1,m}\, x_{n+1,m} = f_{n,m}`, and :math:`Q` from the +derivation of the index, :math:`n Q_n = A_0^{-1} \sum_{j=1}^{n} (\alpha j + j - n)\, A_j Q_{n-j}` +with :math:`A = x / (c_x t^k)` and :math:`Q_0 = A_0^\alpha`, where :math:`A_0 - 1` is nilpotent. +:math:`Q_n` needs :math:`x` up to index :math:`n + k`, which is the index of :math:`S Q_n`, so the +recursion runs order by order as for analytic outputs. The coefficients :math:`d_{n,m}` of an +output are rational in :math:`\theta` where no :math:`\lambda` vanishes, which holds for +:math:`\alpha > 0`: :math:`\lambda_{n,m} \ge \min(1, \alpha)\, n`. The same bound shows that the +series converges for small :math:`t > 0`: the recursion divides by at least :math:`\min(1, \alpha)` +times the divisor of a Taylor series, so Cauchy's majorant of the right-hand side divided by +:math:`\min(1, \alpha)` dominates it. + +**Lemma.** For distinct real numbers :math:`q_1, \dots, q_r`, the functions :math:`t^{q_j}` and +:math:`t^{q_j} \log t` are linearly independent over :math:`\mathbb{R}` on every interval +:math:`(0, \varepsilon)`, also as terms of convergent sums whose exponents have no accumulation +point. + +*Proof.* Let :math:`\sum_j (a_j + b_j \log t)\, t^{q_j} = 0` with :math:`q_1 < q_2 < \dots` and +:math:`j` the first index with :math:`(a_j, b_j) \neq 0`. Divided by :math:`t^{q_j}`, the other +terms tend to 0 as :math:`t \to 0^+`, since :math:`t^\delta \log t \to 0` for :math:`\delta > 0`, +while :math:`a_j + b_j \log t` does not. :math:`\square` + +For :math:`\alpha \notin \mathbb{Q}`, distinct :math:`(n, m)` give distinct exponents +:math:`n - km + km\alpha`, and with several powers the exponents :math:`n + \sum_i k_i m_i +(\alpha_i - 1)` are distinct when :math:`1, \alpha_1, \dots, \alpha_K` are linearly independent +over :math:`\mathbb{Q}`; this holds for generic coordinates if the exponents are distinct +coordinates, and two powers of states at 0 with the same exponent are refused. The gradient of +the output is + +.. math:: + + \partial_\theta g = \sum_{n,m} c_x^{m\alpha} \Big(\partial_\theta d_{n,m} + + m\, d_{n,m} \big(\alpha\, \partial_\theta c_x / c_x + \log c_x\, \partial_\theta \alpha\big) + + km\, d_{n,m} \log t\; \partial_\theta \alpha\Big)\, t^{n - km + km\alpha}, + +so by the lemma a direction lies in the kernel if and only if it annihilates the vectors in +parentheses without the logarithm of :math:`t` and, separately, the vectors :math:`km\, d_{n,m}\, +\partial_\theta \alpha`. Once a coefficient with :math:`m > 0` is nonzero, the latter span +:math:`\partial_\theta \alpha`, and the transcendental term :math:`\log c_x\, \partial_\theta +\alpha` lies in their span. The rows are therefore :math:`\partial_\theta d_{n,m} + m\, +d_{n,m}\, \alpha\, \partial_\theta c_x / c_x`, rational in :math:`\theta`, and one row +:math:`\partial_\theta \alpha`. With several powers, the rows of the logarithm are +:math:`\sum_i k_i m_i\, \partial_\theta \alpha_i`; the engine refuses an expansion in which the +vectors :math:`(k_i m_i)_i` of the nonzero coefficients do not span every power that occurs. +The engine computes :math:`d_{n,m}` with :math:`S` held fixed in the dual numbers and adds the +term of :math:`c_x`, the leading coefficient of :math:`x`, from the dual of :math:`c_x`. The ranks +are taken at random points, where :math:`\alpha` is generic. + +Truncation at the Lie order :math:`N` keeps the indices :math:`n \le N`, and each power of +:math:`S` counts :math:`k` orders, so the monomials have total degree at most :math:`N/k` in the +:math:`S`. Every coefficient computed is exact, and the rank grows to the final value with +:math:`N`. The stopping rule does not apply: the rows :math:`\partial_z L_F^j h` do not exist at +the start, and a start moved off :math:`x = 0` changes the type of the expansion, so no start +reaches the ceiling. The order stops after the plateau and the saturation guard, the result +says that the Lie order is not proven sufficient, and ``info["limits"]`` names the power. Events, +``equilibrate`` and a state that starts at 0 in one condition only are refused for such powers. diff --git a/docs/method/proofs.rst b/docs/method/proofs.rst new file mode 100644 index 0000000..652004f --- /dev/null +++ b/docs/method/proofs.rst @@ -0,0 +1,367 @@ +Reconstruction and proofs +========================= + +The kernel at a point gives the non-identifiable directions as numbers. To read them as +generators, and to reduce the model, symident reconstructs them in closed form and then tries to +prove them over :math:`\mathbb{Q}`. + +.. _scalings: + +Scalings +-------- + +A *scaling* is a symmetry :math:`\Phi_\lambda(\theta)_i = e^{\alpha_i \lambda}\, \theta_i` with +integer *weights* :math:`\alpha_i`, so :math:`\xi_i = \alpha_i \theta_i`. A function is +*homogeneous* of weight :math:`a` when the scaling multiplies it by :math:`e^{a \lambda}`. With +weights :math:`\alpha_x` of the states as well, the scaling is a symmetry when every +right-hand side has the weight of the state, every observable, event time and multiplicative +event value the weight zero, and every initial value and replaced or added event value the +weight of the state. These conditions are linear in the weights and read off the exponents of +the monomials of all expressions together; their integer solutions form a lattice, the +*integer kernel*, and a basis of it gives the scalings exactly. They are taken out first and checked +again symbolically. A power :math:`x^e` whose exponent :math:`e` holds no state and only +coordinates of weight zero has the weight :math:`e\,\alpha_x`, since +:math:`(e^{\alpha_x \lambda} x)^e = e^{e \alpha_x \lambda} x^e` on the principal branch, also for +a state that starts at 0; the recast :math:`E = \theta^e` of a free power of a coordinate has +the weight :math:`e\,\alpha_\theta`, and :math:`L = \log \theta` is translated by +:math:`\alpha_\theta`. A scaling that holds only on an invariant set, such as +:math:`(k_1, k_2) \mapsto (e^\lambda k_1, e^\lambda k_2)` for :math:`\dot x = k_1 - k_2 x` +started at rest, is not an exact symmetry and fails the check. The scaling of the example in +Equation :eq:`eq-example` is exact, with weights :math:`(0, 0, -1, 1, 1)`. + +.. _general-directions: + +General directions +------------------ + +The other non-identifiable directions are *general directions*. The coordinates are ordered with +the initial values of the free states first, in the order of the model, followed by the +parameters in a fixed sorted order. Gauss-Jordan elimination of the rows takes the pivot +columns from left to right, and a *free coordinate* is one without pivot, whose column depends +on the columns to the left. Each kernel vector has the component one on one free coordinate and +zero on the others; every other component is then a rational function of the coordinates. +Alternatively, a direction is fitted in log coordinates, :math:`\xi_i / \theta_i`, and multiplied +back, or chosen with the smallest support outside the scalings, with the component one on the +leftmost coordinate of the support. + +The components are reconstructed from samples. Perturbation finds the variables of each entry; +the entry is sampled at many points and primes and fitted by dense interpolation, by sparse +interpolation after :cite:p:`BenOr1988` or by univariate rational interpolation along lines, and it is +lifted to rational coefficients by the Chinese remainder theorem and rational reconstruction +:cite:p:`Wang1982`. The *route*, as ``Symmetry.route`` names it, is one of + +- ``fit``: rational reconstruction from samples over several primes; ``read-off``: a fast pass + that reads Laurent monomials on the support, with the other coordinates held; ``fit per + prime``: points that each prime solves, joined by the Chinese remainder theorem; each possibly + ``in log coordinates`` and with the kind of fit in parentheses, ``constant``, ``dense`` (a + monomial table up to ``degree_cap``) or ``sparse``; +- ``forward fit per prime``: under ``equilibrate``, with the resting states drawn and the + turnover rates solved, as in the forward seed; +- ``narrow fit``: the kernel restricted to the columns of the support of one direction, in which + it is one-dimensional, with ``exchange groups`` where coordinates that enter only through their + sum or their product were held at the base point and substituted back; ``narrow read-off``: + entries constant, or constant multiples of the coordinates (a scaling on the support), read at + the base point and held at two fresh points; ``narrow (a column without rows)``: the direction + along a coordinate whose column of the kernel matrix vanishes; ``jets (order k)``: the + generator read from the Taylor coefficients of the kernel entries along a support of at most + six coordinates. With many conditions the narrow route reads the kernels of a *cover*, the + conditions whose rows reach the rank of all of them at the base point, and finds the + coordinates that move a direction by whether the direction still annihilates the rows with a + group of coordinates perturbed, from jets seeded along the direction; each closed form is then + checked on every condition; +- ``homotopy fit``: the fit along lines below. + +A *sample bank* of points over the union of the relevant coordinates, with kernels per point and +prime, is shared by all dense fits. Before it is reported, every closed form, and a direction +along one coordinate that fills the kernel, is checked at seeded points uniform modulo the +verification prime, the *kernel check* of :ref:`kernel-check`; under ``equilibrate`` on the +coordinates the closed form states, from which the resting-state copies per condition follow. + +A direction that no sampling route closes is fitted along lines :math:`\theta_b + \mu\, +\delta` through the base point: the kernel entries become power series in :math:`\mu` (under +``equilibrate`` with the resting state continued along the line), and Padé forms on a *star*, +several lines in independent directions :math:`\delta`, are fitted as rational functions. An +entry that is not rational in the parameters alone is fitted in parameters and resting states +modulo their balances, the state :math:`x` of condition :math:`c` being named ``x_c``. Each +entry is checked at a prime outside those of the fit, and the direction against the kernel at +two points uniform modulo the verification prime. ``reconst_control(homotopy=False)`` turns +this route off. + +.. _orbit-geometry: + +Orbit geometry +-------------- + +Each direction with a closed form is classified by the geometry of the orbits, +``Symmetry.kind``, up to a common factor :math:`c(\theta)` of the components: + +- a *scaling*, :math:`\xi_i = c\, w_i \theta_i` with numbers :math:`w_i`, has lines in + logarithmic coordinates as orbits and monomial invariants; a pin + :math:`\theta_i = 1` meets every orbit once; +- a *translation*, :math:`\xi_i = c\, v_i` with numbers :math:`v_i`, has lines in linear + coordinates as orbits and linear invariants. It is proven like a scaling, from the linear + structure of the model: the right-hand sides, observables, initial values and events do not + change along :math:`v`, checked over :math:`\mathbb{Q}`, with the field on the states where + :math:`v` moves initial values. In the positive orthant an orbit ends on the boundary, so the + section lies on a face, :math:`\theta_i = 0`, reached in the limit; +- every other direction is *curved*. + +Translations and curved directions are general directions (``Symmetry.type``). The labels +:math:`X_1, X_2, \dots` of the report and of the reduction count the scalings first, then the +translations and the curved directions. + +.. _invariant-fields: + +Invariant fields and gauge +-------------------------- + +Some directions follow from the model equations without sampling. For a model with resting +states, a *global symmetry* is a field of one regime, found by a detection of that regime with +free initial values and extended to the initial and event values, that lies in the kernel. A +*static subsystem* is a set of states at rest that no event moves; parameters that only the +balances of the subsystem hold give fields that leave every such rest in place. Both are reported with these +names as route. Where every direction of the kernel lies in the span of fields that satisfy the +conditions of :ref:`proofs-over-q` at random points, the *invariant fields*, the rank holds at every +order (``info["rank_fields"]``), with an error bound in ``info["rank_fields_bound"]``. (A) is +checked as a zero and (B), (C) as membership in the span, at two random points; a wrong identity +passes only where a polynomial vanishes there, which the bound covers. Membership at random +points shows (B) and (C) as identities over the rational functions, the hypothesis of the +proposition in :ref:`proofs-over-q`, with coefficients that may have poles on the trajectory. + +With ``gauge``, the detection first finds the scalings and fixes one coordinate per scaling, as +a basis of the weights in the order of preference given and, with general directions, the one +that leaves the fewest nonzero entries in the remaining kernel. A second pass with these +coordinates fixed reconstructs the general directions. Without ``gauge``, +``info["gauge_suggestion"]`` names this choice. + +.. _proofs-over-q: + +Proofs over Q +------------- + +A closed form is *proven* when it is shown to be a symmetry without random points. For a scaling +this is the check of :ref:`scalings`. For a general direction, symident *lifts* the direction to a +field :math:`Y = \xi_\theta\, \partial_\theta + \xi_x\, \partial_x` on parameters and states, +i.e., it finds state components :math:`\xi_x`, and proves the conditions below over +:math:`\mathbb{Q}` for every regime of a condition, with event maps :math:`E_e` between the +regimes. They are stated for fields :math:`X_1, \dots, X_m` per regime and the unit directions +:math:`\partial_u` of parameters :math:`u` that enter no regime, whose span is +:math:`\mathcal{D}`; :math:`X'_l` are the fields of the regime after an event, and :math:`v` is +the direction lifted onto the start :math:`z_0`. + +.. math:: + :label: eq-fields + + \begin{aligned} + &\text{(A)} \quad X_l(h) = 0 \ \text{for every output } h, \\ + &\text{(B)} \quad [F, X_l] = \textstyle\sum_k c_{lk}\, X_k + \sum_u c_{lu}\, \partial_u, \\ + &\text{(C)} \quad \mathrm{D}E_e\, X_l = \textstyle\sum_k c'_{lk}\, X'_k \circ E_e + \sum_u c'_{lu}\, \partial_u, \\ + &\text{(D)} \quad v = \textstyle\sum_l a_l\, X_l(z_0) + \sum_u a_u\, \partial_u, + \ \text{the } X_l \text{ regular at } z_0, \text{ and } v(\tau_e) = 0 \text{ for every event time } \tau_e, + \end{aligned} + +with :math:`a` numbers and :math:`c, c'` rational functions of states and parameters, which may +have poles. A proof over :math:`\mathbb{Q}` takes the lift as the one field of each regime, with +:math:`[F, Y] = 0` and :math:`\mathrm{D}E_e\, Y = Y' \circ E_e`; the invariant fields of +:ref:`invariant-fields` take the fields of the regimes. Where :math:`[F, Y] \neq 0`, the +proof takes as :math:`X_l` the lift together with the lifts proven before, and (B) and (C) with +coefficients solved at a random point and checked over :math:`\mathbb{Q}` on the other +coordinates: :math:`[F, Y] = \lambda Y + \sum_j \mu_j Z_j` holds, e.g., for a translation of +two initial values whose sum the dynamics keeps, where the flow scales :math:`Y`. With unknown +inputs the jets of an input, the input included, take no identity: their components are the +prolongation :math:`\xi_{w_{j+1}} = F(\xi_{w_j}) + \lambda \xi_{w_j} + \sum_j \mu_j \xi^{Z_j}_{w_j}`, +which makes (B) hold there, so a field whose parameter components hold the input is allowed. +Components are tried as found, canonical, over a common denominator and divided by each of their +first four components. + +**Proposition.** Under (A) to (D) the direction lies in the kernel at every Lie order and every +gap length. + +*Proof.* Let :math:`\mathcal{A}` be the rational functions :math:`\varphi` of a regime with :math:`X_l(\varphi) = 0` +and :math:`\partial_u \varphi = 0` for all :math:`l, u`. By (A), :math:`h \in \mathcal{A}`. By (B), +:math:`X_l(F \varphi) = F(X_l \varphi) - [F, X_l](\varphi) = 0`, and :math:`[F, \partial_u] = 0`, so :math:`F` +maps :math:`\mathcal{A}` into itself; by (C), :math:`\varphi \circ E_e \in \mathcal{A}` for :math:`\varphi` in :math:`\mathcal{A}` of the +next regime. Let :math:`\mathcal{A}_k` be the functions of segment :math:`k` built from the outputs of the segment +and from :math:`\varphi \circ E_e` with :math:`\varphi \in \mathcal{A}_{k+1}` by Lie derivatives along +:math:`F`. They lie in :math:`\mathcal{A}` and are analytic along the trajectory, as is every expression +of the model where it is defined. With :math:`z^{(k)}` the start of segment :math:`k` and +:math:`\varphi_t` the flow of :math:`F`, the claim is that the derivative of +:math:`\chi(z^{(k)})` along :math:`v` vanishes for every :math:`\chi \in \mathcal{A}_k`. For +:math:`k = 1` it is :math:`\sum_l a_l\, X_l(\chi)(z_0) + \sum_u a_u\, \partial_u \chi(z_0) = 0` +by (D). If it holds for +:math:`k`, the derivative of :math:`\chi(\varphi_t(z^{(k)}))` along :math:`v` is analytic +in :math:`t` on the segment, and the derivatives at :math:`t = 0` are those of +:math:`L_F^j \chi \in \mathcal{A}_k` at :math:`z^{(k)}`, which vanish, so it vanishes on the +whole segment. With :math:`\chi` an output this is the kernel of every row; with +:math:`\chi = \varphi \circ E_e` at the event time, which :math:`v` does not move, it is the claim +for :math:`k + 1`. :math:`\square` + +The proof needs (B) and (C) as identities of rational functions only. The flow need not keep +the span :math:`\mathcal{D}`: for :math:`X = x^2\, \partial_y` and :math:`F = \partial_x`, +:math:`[F, X] = (2/x)\, X`, yet the flow moves :math:`\partial_y` from :math:`x = -1` to +:math:`x = 0`, where :math:`\mathcal{D} = 0`. The proof follows the functions that the fields +annihilate instead, which a drop of rank does not affect. The identities are proven over +:math:`\mathbb{Q}` per state equation, observable, initial value and event, by symbolic +cancellation. The state components are the closed form read on the states, the initial-value +identities solved for the parameters that set the initial values, a combination of the +symmetries of the model equations, or a solution on the *support* of the direction. The +identities of the lift are linear in :math:`\xi_x`. The support starts at the states whose +equation, initial value or output reads a parameter that the direction moves and grows by the +states whose equations read it; on it, :math:`\xi_x` is a polynomial of degree one in the states, +and of degree two on at most 12 states, solved from the identities at random points modulo a +prime. The lift of :math:`c(\theta)\, Y` is :math:`c(\theta)` times the lift of :math:`Y`, so the +coefficients are read as rational numbers, from two primes, times a factor :math:`c(\theta)`: +one, a component, a component divided by the coordinate it moves, or the inverse of the common +denominator of the components, where the quotient agrees at two parameter points. Otherwise up to +8 coefficients are solved over the rational functions of the parameters from as many independent +identities at points with small coordinates. The solution is a candidate; the identities over +:math:`\mathbb{Q}` decide. The regimes of conditions with the same initial values try the lift of +the first such regime first. + +An identity is first evaluated modulo the prime :math:`2^{61} - 1` at a random point; a nonzero +value refutes it exactly. Otherwise the numerator is expanded in a polynomial ring over +:math:`\mathbb{Q}` with a cap on the terms of every polynomial and on the term products of one +multiplication; past a cap the identity is undecided, and the direction keeps the level of the +kernel check. + +.. _unproven: + +Unproven directions +------------------- + +``info["proof"]`` lists every direction that no proof closes, with the ``support`` and the +``reason`` of each failed route: + +- ``lift of the closed form: [Y, F] on x does not vanish``: the field with state components read + from the closed form is no symmetry, and no other lift was found. +- ``output is not a polynomial in t``: the output identities decide only outputs polynomial in + time. +- ``no combination of the regime fields moves the parameters alike``, ``no combined lift`` (with + the cause, such as more than 8 regimes or work above ``reconst_control(exact_work_cap=)``): the + regimes need state components that agree on the parameters. +- ``events after the start``, ``an event at the start``, ``an input switches on at the start``: + the proof at the resting states covers a start at rest with the inputs at rest that no event + follows or changes. With events, states that no event reaches and that rest alone, such as a + subsystem driving the states the events set, become constant coordinates on their resting + variety, parametrized by a linearly entering parameter; the field holds the component of each + resting state that keeps the variety tangent, and the following states :math:`s` get components + :math:`\xi_s = A s + a`, with a matrix :math:`A` and a vector :math:`a` solved from the + identities of regimes, outputs and events. This covers one resting condition, with reason + ``resting subsystem as coordinates`` and the failing identity. +- ``an inverted power recast``, ``the resting states have no rational parametrization``, ``more + than 8 resting states per condition``: a balance solved for a recast power, without rational + parametrization by the parameters, or with more than the 8 states for which the resting + Jacobian is inverted symbolically stays unproven, the last also in ``info["limits"]``. +- ``no exact proof with these nuisance coordinates``: the unknown-input coordinates have no lift. + +.. _kernel-check: + +Error probability of a closed form +---------------------------------- + +**The kernel check.** A closed form :math:`v` passes the check at a point if it lies in the +kernel there. A point where the kernel is not defined, at a pole or without a resting state, is +skipped. A wrong closed form gives a nonzero *kernel identity* +:math:`\sum_j \mathrm{OIM}_{lj}\, v_j` for some row :math:`l`, which cleared is a polynomial of +degree :math:`D`, so it passes at one point with probability at most :math:`D / p` and at two +points with probability at most :math:`(D / p)^2`. With :math:`n_k` the most points a check drew +for the two that passed (``info["bound"]["draws"]``), the pair is one of +:math:`\binom{n_k}{2}`. For :math:`n_v` verified directions and the largest :math:`D`, + +.. math:: + :label: eq-kernel-bound + + \Pr\big[\text{a wrong direction is verified}\big] \le + n_v \binom{n_k}{2} \Big(\frac{D}{p}\Big)^2 + \text{order bound}, + +which ``info["bound"]`` holds. The bound needs a rational model without root events, event times +rational in the parameters, and Lie and gap orders proven sufficient, since the check runs at the +orders used. It covers the closed forms of the routes checked at points uniform modulo +:math:`p` (``fit``, ``read-off``, ``narrow``, ``jets``, ``homotopy fit``); a form of another +route, such as a static subsystem or the forward fit, is checked at particular points only and +stays ``checked``. + +**The bound at rest.** Under ``equilibrate`` a check point draws the coordinates uniformly modulo +:math:`p` and solves the balances :math:`f_i` of each condition there. A point counts where, +unless linear elimination solves the balances, every state is nonzero. The resting states are +algebraic, not rational, in the coordinates, so the Schwartz-Zippel lemma (:ref:`order-bound`) is applied on the resting +variety. Let :math:`Z` be an irreducible component of the resting variety with +:math:`\dim Z = d`, and :math:`P` a polynomial of degree :math:`D` that does not vanish on +:math:`Z`; :math:`V(P)` denotes the zero set of :math:`P` and a *hypersurface* the zero set of one nonzero +polynomial. Then :math:`Z \cap V(P)` has degree at most :math:`D \deg Z \le D \prod_i \deg f_i`, +the *Bezout number* of the balances :cite:p:`Heintz1983`, the projection of this intersection to the coordinates lies in a +hypersurface of at most that degree :cite:p:`Heintz1983`, and therefore + +.. math:: + :label: eq-rest-bound + + \Pr_\theta\big[\exists x:\ (\theta, x) \in Z,\ P(\theta, x) = 0\big] \le + \frac{D\, \deg Z}{p}. + +Let :math:`D_\theta` and :math:`D_x` be the columns of :math:`D_N` for the coordinates and for the +states, and :math:`\operatorname{adj}` the adjugate matrix. With :math:`J_x` invertible, a closed +form :math:`v` extends to the kernel of the joint rows exactly where + +.. math:: + + \det(J_x)\, D_\theta v - D_x \operatorname{adj}(J_x)\, J_\theta v = 0 . + +Multiplied by :math:`\det(J_x)`, this identity also vanishes at a check point with a singular +Jacobian, and it does not vanish on the component where :math:`J_x` is invertible at one +resting point of the condition, which is checked. The degree of the identity is the degree :math:`D` of the +cleared kernel identity with the start as coordinates plus :math:`2 \sum_i (\deg f_i - 1)`. A +closed form that reads resting states of further conditions, ``x_c``, lives on the product of +their varieties over :math:`\theta`. The solves leave the component only above a proper +subvariety of the coordinates of degree at most :math:`\prod_i \deg f_i`, the zeros of the +pivots of a linear elimination or the projection of the other components, provided every root +taken lies on one component over :math:`\mathbb{Q}(\theta)`: a rest solved by linear elimination, +or interior roots conjugate over :math:`\mathbb{Q}(\theta)` (``info["branches"]``), on a split +factor where a balance splits. In Equation :eq:`eq-kernel-bound` the degree :math:`D` is then +replaced by :math:`(D + 2 \sum_i (\deg f_i - 1)) \prod_i \deg f_i + \sum \prod_i \deg f_i`, the +products and the sum taken over the conditions read. Without such a component (branches not +decided), with resting states continued along a line at the check points, or with a power or +exponential in the balances, a direction that the proof leaves open is ``checked``, and +``info["bound"]`` gives the reason. + +**What the bounds exclude.** The bounds above are probabilities over the points modulo :math:`p`. They +exclude the chance that :math:`p` divides the *content* of an integer identity, the greatest +common divisor of the coefficients, which then vanishes modulo :math:`p`, or that :math:`p` is +one of the finitely many primes at which an identity nonzero on a resting component vanishes +there modulo :math:`p`. The counts that follow have no bad primes: the exact one has no random +choice, the verified one runs over :math:`\mathbb{Q}`. + +.. _levels: + +Levels and rank status +---------------------- + +The *level* of a closed form says how far it is established: + +- ``exact``: proven over :math:`\mathbb{Q}`, as a scaling of the integer kernel or as a field of + :ref:`proofs-over-q`. +- ``verified``: in the kernel at two seeded points modulo the verification prime, with the error + probability of :ref:`kernel-check` in ``info["bound"]``. +- ``checked``: the same test where no bound applies (``info["bound"]`` says why), or a test on the + entries that can be evaluated at the points. +- ``open``: no closed form. + +The rank (``info["rank_status"]``) is + +- *proven* when it is full, when it plus the number of independent exact directions is :math:`d`, + or when every direction is proven over :math:`\mathbb{Q}`; +- *verified*, with a probability, when the Lie, gap and series orders are proven sufficient and + every direction is verified with a bound; when every direction lies in the span of invariant + fields, checked at random points with a bound (``info["rank_fields_bound"]``); or when a rank + modulo unknown inputs holds at a random point; +- a *lower bound* otherwise, i.e., the generic rank may be higher and some reported directions may + not exist. + +Besides proofs, a result rests on two assumptions (``info["assumptions"]``, +``Reduction.assumptions``), both part of the declared model: the domain :math:`\Theta` +(``positive``) and, with switches, the start sides that ``regimes`` declares where the initial +values do not decide them. A verified closed form or rank is wrong with probability at most +``error_bound``, including a wrong certified order. Floating point enters the choice of a gauge +and of the ``reduce_cq`` pivots, never a rank, a sign or a closed form. Every other step is +proven or named in the result: a ``checked`` direction, a ``lower bound`` rank, a section claim +under ``unproven``, a limit under ``info["limits"]``, a resting branch under +``info["branches"]``. diff --git a/docs/method/reduction.rst b/docs/method/reduction.rst new file mode 100644 index 0000000..256b2c2 --- /dev/null +++ b/docs/method/reduction.rst @@ -0,0 +1,268 @@ +Reduction +========= + +A reduction replaces the coordinates by combinations that the output determines :cite:p:`Chappell1998,Evans2000,Massonis2023`, the invariants :math:`I_l(\theta)` with :math:`X(I_l) = 0` +:cite:p:`Olver1986`. The directions are reduced in *blocks*, sets of directions with overlapping +supports, each block with the group :math:`G` generated by the flows of the generators of the block. +symident searches, within degree bounds, monomial, polynomial and rational invariants (with a +denominator in one coordinate), Darboux polynomials and exponential factors :cite:p:`Prelle1983,Goriely2001`, i.e., polynomials :math:`P` and exponentials :math:`e^{P/Q}` that :math:`X` +multiplies by a polynomial, and invariants by separable quadrature, i.e., by integrating +:math:`\mathrm{d}\theta_i / \xi_i = \mathrm{d}\theta_j / \xi_j` where it separates, and by an +integrating factor. The invariants become new parameters, :math:`I_l(\theta) = q_l`, and the +remaining coordinates are expressed through them. The invariants are coordinates on the orbit +space :math:`\Theta / G`, a *chart*, and the trafo is the section in these coordinates. A chart is +returned only where it is valid on the declared domain, the positive orthant by default; +``Reduction.partial`` names the directions whose chart covers the domain only in part, and +``alternatives=True`` also returns the charts of the other valid choices of the fixed +coordinates. Among the charts, one with total coverage comes before a rational one. + +.. _red-scalings: + +Scalings +-------- + +A scaling is removed by fixing one of the coordinates it moves at one, such as an initial value or a +scale, a *pin*. Every orbit of a scaling meets the hypersurface :math:`\theta_i = 1` of a moved +coordinate once, so the result is a *global section*: a one-to-one map of the new parameters onto +a *global cross-section*, a set meeting every orbit exactly once, with the invariants as global +coordinates on the orbit space :math:`\Theta / G`. In the example of Equation :eq:`eq-example`, +:math:`A_0 = 1` meets every orbit of the scaling once. A direction along one coordinate is pinned +like a scaling; every orbit meets the pin where a *sign certificate*, a proof that an expression +has one sign on :math:`\Theta`, shows that the generator component on the pinned coordinate has +one sign, else the orbits can be the intervals between the zeros of that component, and the pin +is listed under ``unproven``. + +The pinned coordinates of a block of scalings, the *transversal* of the block, are chosen among the +coordinates of the support that are not fixed: subsets :math:`T` of the size of the block, taken +in the order of the coordinates, for which the columns :math:`W_T` of the weight matrix +:math:`W` are invertible and :math:`W_T^{-1} W` has integer entries, so that every other +coordinate becomes a monomial of the new parameters; for many candidates a greedy choice by the number of scalings moving each +coordinate. Without a certified transversal the block keeps the invariants only +(``invariant_only``). A scaling keeps the sign of every coordinate, so a pin on a coordinate that +is not declared positive misses the orbits where that coordinate is negative or zero; transversals +of positive coordinates come first. Where the only transversal outside the support of the general +directions is such a signed one, the pins :math:`\theta_T = 1` are taken on positive coordinates +inside that support, and each general generator :math:`X` becomes :math:`X - \sum_i \lambda_i +S_i`, with the scalings :math:`S_i = \sum_c W_{ic} \theta_c \partial_{\theta_c}` and +:math:`\lambda` solved from :math:`\sum_i \lambda_i W_{it} \theta_t = \xi_t` for :math:`t \in T`, +divided by the greatest common divisor of the numerators of the components. The matrix +:math:`(W_{it} \theta_t)` is invertible where the pins are positive, so the new generators span the +same distribution as before together with the scalings, and they leave :math:`\theta_T = 1` in +place. Every orbit meets :math:`\theta_T = 1`; there, the orbits of the new generators are the +intersections with the orbits of all directions, so the certificates of the general block hold for +the whole group. Of up to four positive transversals, the one with the shortest new generators is +kept. Before the search for invariants, a block of several general generators is +split by *module reduction*: an elimination order with few new nonzero entries, found at random +points modulo a prime and repeated exactly, gives combinations of the generators with smaller +supports, and independent ones form separate blocks. + +.. _red-linear: + +Linear flows +------------ + +A block of :math:`r` general generators is a *linear flow* when, in the +coordinates :math:`\tilde\theta_i = \theta_i` for a moved coordinate that is not declared +positive and :math:`\tilde\theta_i = \log \theta_i` for a positive one, every component +:math:`\tilde\xi_i` depends only on the coordinates :math:`u` that the block does not move, and +no declared bound involves a moved coordinate. The generators then commute, and the orbit of a +point is the affine set :math:`\{(u, \tilde\theta + \Xi(u) s) : s \in \mathbb{R}^r\}`, with +:math:`\Xi(u)` the matrix of the components, on which every moved coordinate takes every real +value. Pins :math:`\tilde\theta_P = 0` on :math:`r` moved coordinates :math:`P` whose minor +:math:`\det \Xi_P(u)` has one sign on :math:`\Theta` give a global section: +:math:`\tilde\theta_P + \Xi_P(u) s = 0` has exactly one solution on every orbit, so the section is +``injective`` and ``reach``-es every orbit. The invariants are +:math:`\tilde\theta_N - \Xi_N(u) \Xi_P(u)^{-1} \tilde\theta_P` for the other moved coordinates +:math:`N`, and a linear coordinate is pinned to 0, a positive one to 1. This stage runs before +the search for invariants. Among the pin sets, a coordinate that enters only the observables (an +offset of the observation function) is preferred, an initial value is taken last. + +.. _red-general: + +General blocks +-------------- + +For a block of :math:`r` general generators the invariants :math:`I(\theta) = q` are solved for +coordinates :math:`\theta_s = R(q, \vartheta)`, with :math:`r` *gauge coordinates* :math:`\vartheta` left. Every +level set :math:`\Lambda_q = \{\theta \in \Theta : I(\theta) = q\}` is one orbit when + +1. :math:`R(q, \vartheta)` is the unique solution for every gauge value, so :math:`\Lambda_q` is the graph + of :math:`R(q, \cdot)` over :math:`\mathcal{G}_q = \{\vartheta : (R(q, \vartheta), \vartheta) \in \Theta\}`; +2. the :math:`r \times r` minor of the generator components on :math:`\vartheta` has one sign on + :math:`\Theta`, so every orbit is :math:`r`-dimensional and open in :math:`\Lambda_q` (for + generators with poles, the minor of the fields times their denominators); +3. :math:`\mathcal{G}_q` is connected. + +The set :math:`\mathcal{G}_q` is given by one inequality :math:`\pi_k(q, \vartheta) > 0` per positive +solved coordinate and square-root factor. It is connected when every inequality is convex in +:math:`\vartheta` (affine, a concave quadratic, or, in one positive gauge coordinate, a polynomial with at +most one sign change and so, by Descartes' rule of signs, at most one positive root), or when a +gauge coordinate enters every inequality affinely with a coefficient of known sign, so that the +*fibers*, the sets of that coordinate at fixed other gauge coordinates, are intervals and the set +is connected with the projection, decided the same way. Square roots in :math:`\vartheta`, or of a single +positive invariant, are first removed by a square substitution, which is one to one on the +positive half-line. The *section point* :math:`\hat\theta(q)` then lies in :math:`\Lambda_q` and, +by a *positivity certificate*, a proof that each entry is positive on the domain, in +:math:`\Theta`. + +**Split products.** Sections equate *balances*, monomials or summands of the invariants. An +invariant :math:`A - B` whose two summands each have one sign on :math:`\Theta` takes both signs +across the orbits, and the orbits of either sign leave the domain on different faces. For such an +invariant the products :math:`u v = 1` of a positive coordinate :math:`u` of :math:`A` and one +:math:`v` of :math:`B` are candidates as well. They are tried after the other balances, alone or +with one other balance, as many balances as generators, and only where the Jacobian of the +logarithms of the balance ratios along the generators, a determinant of polynomials over positive +denominators, has one sign on :math:`\Theta` by a sign certificate: the section is then transversal +to the orbits everywhere. Injectivity, ``reach`` and the positivity of the entries are proven as for +any section. + +**Section charts.** Where the section point solved from the invariants holds a root, the section +itself can still be rational, and the count of discrete symmetries (:meth:`Symmetries.discrete`), +which needs a rational reduced model, takes it so: when every orbit meets it (total coverage) exactly once +(``injective``), and the balances of the section solve, one after the other, for a coordinate of degree one with a +coefficient of one sign, each solved coordinate certified of the declared sign, the remaining +coordinates of the section are the new parameters. The trafo is then rational and maps their domain +one to one onto the points of the section in :math:`\Theta`, hence onto the orbits; the meaning of +a new parameter is the coordinate of the section point of the orbit, solved from the invariants. + +**Coverage.** ``reach`` says that every level set of the invariants is one orbit; with *total +coverage* every orbit then meets the section, under *partial coverage* exactly the orbits whose +invariants lie where the solved entries are positive. Under declared bounds, i.e., expressions in +``positive``, an entry without positivity certificate is kept, with partial coverage, and listed +under ``unproven``. Without bounds it is kept only when the search found no section certified on +the whole domain, and only where a sampled orbit has every entry positive: the transformation then +covers the orbits on which the ``sign_conditions``, the entries as inequalities in :math:`q`, +hold, the sampled one among them, and no others. A positivity certificate treats an *atom*, a +non-polynomial subterm such as :math:`\log x`, as positive only where the sign of the atom is proven; an +AM-GM certificate, a lower bound by the inequality of arithmetic and geometric means over pairs of +terms, is strict only by the positive remainder the pairs leave, on a term free of coordinates +that are not declared positive where there are any. + +**Face sections.** A *face* is a boundary set :math:`\theta_f = 0` for coordinates +:math:`\theta_f` of the block; a section on a face lies outside :math:`\Theta` and is reached only +in a limit. It is tried first, and once one is found no other is searched; the new parameters are +the coordinates of the face point, not invariants. With :math:`\theta_f` as gauge coordinates, +the conditions above make every level set one orbit, and :math:`R(q, \theta_f) \to R(q, 0) > 0` +puts the face point :math:`(0, R(q, 0))` in the closure of every orbit of :math:`\Lambda_q`. The +output, constant along the orbit, equals that at the face point when the model is continuous +there: no model expression has a pole at the face, every denominator in the block parameters has +one sign there, and under ``equilibrate`` :math:`x^\ast(\theta)` has a limit. For that limit each +generator is lifted to a field :math:`\tilde X = X + \xi_x \partial_x` tangent to the resting +variety, by the state components of an exact direction or by the implicit derivative +:math:`\xi_x = -J_x^{-1} J_\theta \xi_\theta`; exactly verified invariants of the lifted fields +that solve for the moved states and stay positive at :math:`\theta_f = 0` give the limit along +every orbit. The implicit derivative needs :math:`J_x` regular: proven when :math:`\det J_x` has +one sign on :math:`\Theta`, else checked at random points. Without a lift, the resting state is +continuous when :math:`f` is affine in the states with a resting Jacobian of one sign at the face, +else it is checked at random face points; a checked resting state sets ``face_level`` and +``level`` of the block to ``checked``. + +**Injectivity.** That every orbit meets the cross-section :math:`\mathcal{C}` at most once +(``injective``) is proven, for any number of generators, when the solved coordinates recover every +point of :math:`\mathcal{C}` from the invariants, :math:`\hat\theta(I(\theta)) = \theta` on +:math:`\mathcal{C}`, since two points of one orbit have equal invariants. The identity is shown +over :math:`\mathbb{Q}` on a parametrization of the positive points of :math:`\mathcal{C}`, +monomial where the section equates monomials, else by solving each equation for a coordinate of +degree one; the claim is made for sections with total coverage off a face. For one generator it +also holds when :math:`X` changes the pinned coordinate, or the logarithm of the quotient of the +two sides of the section equation, with one sign on :math:`\Theta`. + +**Zero limits.** With ``zero_limits=True`` each block reports which coordinates can be set to zero: +everywhere, under a condition, or in a limit along the orbits when the face is mapped into itself +by the generators, and whether this is certain (``to_dict()["zero_compatibility"]``). + +An unproven claim is listed under ``unproven`` of the block and makes the block ``open``; a block +is ``verified`` or ``checked`` when a direction or a face resting state has that level, else +``exact``. The transformation is checked over :math:`\mathbb{Q}`, and ``check=True`` runs the +detection again on the reduced model (``Reduction.checks["loop"]``). + +.. _red-inputs: + +Unknown inputs +-------------- + +In a model with ``unknown_inputs`` :math:`w`, a direction changes the input +trajectory together with :math:`\theta` and the initial values, so a section in :math:`(\theta, +x_0)` gives the output of a point only with another input. The reduction keeps the inputs free and +proves, per direction, that they absorb the change, in one of two ways; a direction with neither +proof is not reduced, and the reason names the inputs. For a model with one condition, no events +and no ``equilibrate``, :math:`\dot x = f(x, \theta, w, u)`, output :math:`h(x, \theta)`, with the +time derivative :math:`D = f \cdot \partial_x`: + +*Inversion.* Suppose there are as many observables as unknown inputs, none reads an input, and the +matrix :math:`M = \partial_w D(h)` has a determinant that is not zero as a rational function. Let +:math:`(\hat\theta, \hat x_0, \hat w)`, :math:`\hat w` continuous, give the output :math:`\hat g` +on :math:`[0, T]` with :math:`\det M \ne 0` along the trajectory. Then every :math:`(\theta', +x_0')` with :math:`h(x_0', \theta') = \hat g(0)` gives :math:`\hat g` with an input :math:`w'` +wherever :math:`D(h)(x', \theta', w') = \dot{\hat g}` has a continuous solution :math:`w'` in the +domain of the inputs with a state :math:`x'` of :math:`\dot x' = f(x', \theta', w')`, +:math:`x'(0) = x_0'`, on :math:`[0, T]`; near :math:`(\hat\theta, \hat x_0)` it does. + +*Proof.* :math:`e(t) = h(x'(t), \theta') - \hat g(t)` has :math:`\dot e = D(h)(x', \theta', w') - +\dot{\hat g} = 0` and :math:`e(0) = 0`. Near the trajectory, the implicit function theorem solves +:math:`D(h)(x, \theta, w) = \dot{\hat g}(t)` for :math:`w = W(t, x, \theta)`, continuous in +:math:`t` and :math:`C^1` in :math:`(x, \theta)` on a neighborhood of the compact graph of +:math:`(\hat x, \hat\theta, \hat w)`, and the solution of :math:`\dot x = f(x, \theta, W)` +exists on :math:`[0, T]` for data near :math:`(\hat x_0, \hat\theta)` by continuous dependence. +:math:`\square` + +Every exact direction :math:`X` has :math:`X(h) = 0` at the start, the rows of order zero, so the +orbits of :math:`X` in :math:`(\theta, x_0)` keep :math:`h(x_0, \theta)`, and a section of the directions, chosen +as for a model without inputs, gives the output of every point under the condition above. + +*Pointwise lift.* Suppose the direction, up to a factor, has parameter components +:math:`\xi_\theta(\theta)`, state components :math:`\xi_x(\theta, x)` (the components on the +initial values read as functions of the states), and input components :math:`\xi_w(\theta, x, +w)` solved from the identities + +.. math:: + :label: eq-input-lift + + D(\xi_x) = V(f), \qquad V(h) = 0, \qquad V = \xi_\theta\, \partial_\theta + \xi_x\, + \partial_x + \xi_w\, \partial_w , + +over :math:`\mathbb{Q}`, and a given initial value :math:`x_0(\theta)` moves with the parameters, +:math:`\xi_x(\theta, x_0(\theta)) = \xi_\theta \cdot \partial_\theta x_0`. Let +:math:`\Phi_\varepsilon` be the flow of :math:`V`. On :math:`[0, T]` set :math:`\theta(\varepsilon)`, +:math:`x(t, \varepsilon)` and :math:`w(t, \varepsilon)` to the components of +:math:`\Phi_\varepsilon(\hat\theta, \hat x(t), \hat w(t))`; by compactness they exist for +:math:`|\varepsilon| < \varepsilon_0`, and :math:`(\theta, x)` follows the flow of +:math:`(\xi_\theta, \xi_x)`, which reads no input, so :math:`x` is :math:`C^1` in :math:`t`. Then +:math:`x(\cdot, \varepsilon)` solves the model with :math:`\theta(\varepsilon)` and the input +:math:`w(\cdot, \varepsilon)` and gives :math:`\hat g`. + +*Proof.* With :math:`R = \partial_t x - f(x, \theta, w)`, :math:`\partial_\varepsilon \partial_t x += \partial_t \xi_x(\theta, x) = \partial_x \xi_x\, \partial_t x` and :math:`\partial_\varepsilon +f(x, \theta, w) = V(f) = D(\xi_x) = \partial_x \xi_x\, f`, so :math:`\partial_\varepsilon R = +\partial_x \xi_x\, R` with :math:`R(t, 0) = 0`, hence :math:`R = 0`; and :math:`\partial_\varepsilon +h(x, \theta) = V(h) = 0`. :math:`\square` + +The orbits of :math:`\xi_\theta` thus keep the output as long as the input stays in the domain of the inputs, +:math:`w > 0` where declared positive; near every point it does. The reduction removes the field +:math:`\xi_\theta` on the parameters, with the invariants, sections and coverage of the parameter +field; the initial values of the states and the inputs stay free in the reduced model. A lift with +:math:`\xi_w = 0` is a symmetry of the model, reduced as without inputs. ``Reduction.blocks`` holds +per block ``inputs``: the inputs, the proof (``"inversion"`` with the ``determinant``, or +``"lift"`` with the components), and the ``condition`` on the input and the trajectory, which the +report repeats. The section claims of the block, ``reach`` and ``injective``, are those of the +orbits of the field the reduction removes; that the section point gives the output rests on this +condition. + +.. _red-branches: + +Branches of discrete symmetries +------------------------------- + +For a reduction, each image of the fundamental domain under the maps is a *branch*. Where a map +:math:`\sigma` has one hypersurface :math:`q = 0` as fixed set and exchanges the two sides of it, +:math:`q(\sigma(\theta)) = -c\, q(\theta)` with :math:`c > 0` on :math:`\Theta`, the branches are +the sides :math:`s\, q > 0`, :math:`s = \pm 1`, named by the inequality, and :math:`q = 0` is their +boundary. On a side, :math:`\delta = s\, q(\theta) > 0` replaces a coordinate :math:`x` in which +:math:`q` is linear; :math:`x` is chosen by structure, a solution :math:`x(\delta, \theta')` with a +positivity certificate first, then the smaller expression, so that neither the chart nor the name of +the branch depends on the names or the order of the parameters. The chart maps free values in the +positive orthant into the side and is chained with the section of the continuous symmetries. It is +``injective`` where the coefficient of :math:`x` in :math:`q` has a sign certificate, since +:math:`\delta = s\, q(\theta)` inverts it, and it ``reach``-es the whole side where +:math:`x(\delta, \theta')` has a positivity certificate; a claim without certificate is listed +under ``unproven``. A fiber of more than two points has no branch charts. diff --git a/docs/method/references.rst b/docs/method/references.rst new file mode 100644 index 0000000..3d0c6fb --- /dev/null +++ b/docs/method/references.rst @@ -0,0 +1,4 @@ +References +========== + +.. bibliography:: diff --git a/docs/refs.bib b/docs/refs.bib new file mode 100644 index 0000000..2920d6d --- /dev/null +++ b/docs/refs.bib @@ -0,0 +1,515 @@ +@article{Ax1971, + author = {Ax, James}, + title = {On {Schanuel's} conjectures}, + journal = {Annals of Mathematics}, + volume = {93}, + number = {2}, + pages = {252--268}, + year = {1971}, + doi = {10.2307/1970774} +} + +@inproceedings{BenOr1988, + author = {Ben-Or, Michael and Tiwari, Prasoon}, + title = {A deterministic algorithm for sparse multivariate polynomial interpolation}, + booktitle = {Proc. 20th Annu. ACM Symp. Theory Comput. (STOC)}, + publisher = {ACM}, + address = {New York, NY, USA}, + pages = {301--309}, + year = {1988}, + doi = {10.1145/62212.62241} +} + +@inproceedings{Berthomieu2021, + author = {Berthomieu, J{\'e}r{\'e}my and Eder, Christian and Safey El Din, Mohab}, + title = {msolve: a library for solving polynomial systems}, + booktitle = {Proc. 2021 Int. Symp. Symbolic Algebraic Comput. (ISSAC)}, + publisher = {ACM}, + address = {New York, NY, USA}, + pages = {51--58}, + year = {2021}, + doi = {10.1145/3452143.3465545} +} + +@article{Chappell1998, + author = {Chappell, Michael J. and Gunn, Roger N.}, + title = {A procedure for generating locally identifiable reparameterisations of unidentifiable non-linear systems by the similarity transformation approach}, + journal = {Mathematical Biosciences}, + volume = {148}, + number = {1}, + pages = {21--41}, + year = {1998}, + doi = {10.1016/S0025-5564(97)10004-9} +} + +@article{CongLlibreZhang2011, + author = {Cong, Wei and Llibre, Jaume and Zhang, Xiang}, + title = {Generalized rational first integrals of analytic differential systems}, + journal = {Journal of Differential Equations}, + volume = {251}, + number = {10}, + pages = {2770--2788}, + year = {2011}, + doi = {10.1016/j.jde.2011.05.016} +} + +@article{Dong2023, + author = {Dong, Ruiwen and Goodbrake, Christian and Harrington, Heather A. and Pogudin, Gleb}, + title = {Differential elimination for dynamical models via projections with applications to structural identifiability}, + journal = {SIAM Journal on Applied Algebra and Geometry}, + volume = {7}, + number = {1}, + pages = {194--235}, + year = {2023}, + doi = {10.1137/22M1469067} +} + +@article{Duff2019, + author = {Duff, Timothy and Hill, Cvetelina and Jensen, Anders and Lee, Kisun and Leykin, Anton and Sommars, Jeff}, + title = {Solving polynomial systems via homotopy continuation and monodromy}, + journal = {IMA Journal of Numerical Analysis}, + volume = {39}, + number = {3}, + pages = {1421--1446}, + year = {2019}, + doi = {10.1093/imanum/dry017} +} + +@article{Dulmage1958, + author = {Dulmage, A. L. and Mendelsohn, N. S.}, + title = {Coverings of bipartite graphs}, + journal = {Canadian Journal of Mathematics}, + volume = {10}, + pages = {517--534}, + year = {1958}, + doi = {10.4153/CJM-1958-052-0} +} + +@article{Evans2000, + author = {Evans, Neil D. and Chappell, Michael J.}, + title = {Extensions to a procedure for generating locally identifiable reparameterisations of unidentifiable systems}, + journal = {Mathematical Biosciences}, + volume = {168}, + number = {2}, + pages = {137--159}, + year = {2000}, + doi = {10.1016/S0025-5564(00)00047-X} +} + +@article{Girstmair1999, + author = {Girstmair, Kurt}, + title = {Linear relations between roots of polynomials}, + journal = {Acta Arithmetica}, + volume = {89}, + number = {1}, + pages = {53--96}, + year = {1999}, + doi = {10.4064/aa-89-1-53-96} +} + +@article{Bellman1970, + author = {Bellman, R. and {\AA}str{\"o}m, K. J.}, + title = {On structural identifiability}, + journal = {Mathematical Biosciences}, + volume = {7}, + number = {3--4}, + pages = {329--339}, + year = {1970}, + doi = {10.1016/0025-5564(70)90132-X} +} + +@book{Goriely2001, + author = {Goriely, Alain}, + title = {Integrability and Nonintegrability of Dynamical Systems}, + series = {Advanced Series in Nonlinear Dynamics}, + volume = {19}, + publisher = {World Scientific}, + address = {Singapore}, + year = {2001}, + doi = {10.1142/3846} +} + +@article{Hass2019, + author = {Hass, Helge and Loos, Carolin and Raim{\'u}ndez-{\'A}lvarez, Elba and Timmer, Jens and Hasenauer, Jan and Kreutz, Clemens}, + title = {Benchmark problems for dynamic modeling of intracellular processes}, + journal = {Bioinformatics}, + volume = {35}, + number = {17}, + pages = {3073--3082}, + year = {2019}, + doi = {10.1093/bioinformatics/btz020} +} + +@article{Heintz1983, + author = {Heintz, Joos}, + title = {Definability and fast quantifier elimination in algebraically closed fields}, + journal = {Theoretical Computer Science}, + volume = {24}, + number = {3}, + pages = {239--277}, + year = {1983}, + doi = {10.1016/0304-3975(83)90002-6} +} + +@article{HermannKrener1977, + author = {Hermann, Robert and Krener, Arthur J.}, + title = {Nonlinear controllability and observability}, + journal = {IEEE Transactions on Automatic Control}, + volume = {22}, + number = {5}, + pages = {728--740}, + year = {1977}, + doi = {10.1109/TAC.1977.1101601} +} + +@article{Hong2020, + author = {Hong, Hoon and Ovchinnikov, Alexey and Pogudin, Gleb and Yap, Chee}, + title = {Global identifiability of differential models}, + journal = {Communications on Pure and Applied Mathematics}, + volume = {73}, + number = {9}, + pages = {1831--1879}, + year = {2020}, + doi = {10.1002/cpa.21921} +} + +@book{Isaacs1976, + author = {Isaacs, I. Martin}, + title = {Character Theory of Finite Groups}, + series = {Pure and Applied Mathematics}, + volume = {69}, + publisher = {Academic Press}, + address = {New York}, + year = {1976}, + doi = {10.1016/S0079-8169(08)X6037-4} +} + +@article{Karlsson2012, + author = {Karlsson, Johan and Anguelova, Milena and Jirstrand, Mats}, + title = {An efficient method for structural identifiability analysis of large dynamic systems}, + journal = {IFAC Proceedings Volumes}, + volume = {45}, + number = {16}, + pages = {941--946}, + year = {2012}, + doi = {10.3182/20120711-3-BE-2027.00381} +} + +@article{Kolchin1968, + author = {Kolchin, E. R.}, + title = {Algebraic groups and algebraic dependence}, + journal = {American Journal of Mathematics}, + volume = {90}, + number = {4}, + pages = {1151--1164}, + year = {1968}, + doi = {10.2307/2373294} +} + +@article{Krawczyk1969, + author = {Krawczyk, Rudolf}, + title = {{Newton-Algorithmen} zur {Bestimmung} von {Nullstellen} mit {Fehlerschranken}}, + journal = {Computing}, + volume = {4}, + number = {3}, + pages = {187--201}, + year = {1969}, + doi = {10.1007/BF02234767} +} + +@inproceedings{Martinelli2015, + author = {Martinelli, Agostino}, + title = {Extension of the observability rank condition to nonlinear systems driven by unknown inputs}, + booktitle = {Proc. 23rd Mediterranean Conf. Control Automat. (MED)}, + publisher = {IEEE}, + address = {Piscataway, NJ, USA}, + pages = {589--595}, + year = {2015}, + doi = {10.1109/MED.2015.7158811} +} + +@article{Martinelli2019, + author = {Martinelli, Agostino}, + title = {Nonlinear unknown input observability: extension of the observability rank condition}, + journal = {IEEE Transactions on Automatic Control}, + volume = {64}, + number = {1}, + pages = {222--237}, + year = {2019}, + doi = {10.1109/TAC.2018.2798806} +} + +@article{Massonis2020, + author = {Massonis, Gemma and Villaverde, Alejandro F.}, + title = {Finding and breaking {Lie} symmetries: implications for structural identifiability and observability in biological modelling}, + journal = {Symmetry}, + volume = {12}, + number = {3}, + eid = {469}, + year = {2020}, + doi = {10.3390/sym12030469} +} + +@article{Massonis2023, + author = {Massonis, Gemma and Banga, Julio R. and Villaverde, Alejandro F.}, + title = {{AutoRepar}: a method to obtain identifiable and observable reparameterizations of dynamic models with mechanistic insights}, + journal = {International Journal of Robust and Nonlinear Control}, + volume = {33}, + number = {9}, + pages = {5039--5057}, + year = {2023}, + doi = {10.1002/rnc.5887} +} + +@article{Merkt2015, + author = {Merkt, Benjamin and Timmer, Jens and Kaschek, Daniel}, + title = {Higher-order {Lie} symmetries in identifiability and predictability analysis of dynamic models}, + journal = {Physical Review E}, + volume = {92}, + number = {1}, + eid = {012920}, + year = {2015}, + doi = {10.1103/PhysRevE.92.012920} +} + +@article{Moore1977, + author = {Moore, R. E.}, + title = {A test for existence of solutions to nonlinear systems}, + journal = {SIAM Journal on Numerical Analysis}, + volume = {14}, + number = {4}, + pages = {611--615}, + year = {1977}, + doi = {10.1137/0714040} +} + +@book{Neukirch1999, + author = {Neukirch, J{\"u}rgen}, + title = {Algebraic Number Theory}, + series = {Grundlehren der mathematischen Wissenschaften}, + volume = {322}, + publisher = {Springer}, + address = {Berlin, Heidelberg}, + year = {1999}, + doi = {10.1007/978-3-662-03983-0} +} + +@book{Olver1986, + author = {Olver, Peter J.}, + title = {Applications of {Lie} Groups to Differential Equations}, + series = {Graduate Texts in Mathematics}, + volume = {107}, + publisher = {Springer}, + address = {New York}, + year = {1986}, + doi = {10.1007/978-1-4684-0274-2} +} + +@article{Ostrowski1946, + author = {Ostrowski, Alexandre}, + title = {Sur les relations alg{\'e}briques entre les int{\'e}grales ind{\'e}finies}, + journal = {Acta Mathematica}, + volume = {78}, + pages = {315--318}, + year = {1946}, + doi = {10.1007/BF02421605} +} + +@article{Ovchinnikov2022, + author = {Ovchinnikov, Alexey and Pillay, Anand and Pogudin, Gleb and Scanlon, Thomas}, + title = {Multi-experiment parameter identifiability of {ODEs} and model theory}, + journal = {SIAM Journal on Applied Algebra and Geometry}, + volume = {6}, + number = {3}, + pages = {339--367}, + year = {2022}, + doi = {10.1137/21M1389845} +} + +@article{OvchinnikovPogudinThompson2023, + author = {Ovchinnikov, Alexey and Pogudin, Gleb and Thompson, Peter}, + title = {Parameter identifiability and input-output equations}, + journal = {Applicable Algebra in Engineering, Communication and Computing}, + volume = {34}, + number = {2}, + pages = {165--182}, + year = {2023}, + doi = {10.1007/s00200-021-00486-8} +} + +@article{Pohjanpalo1978, + author = {Pohjanpalo, Hannu}, + title = {System identifiability based on the power series expansion of the solution}, + journal = {Mathematical Biosciences}, + volume = {41}, + number = {1--2}, + pages = {21--33}, + year = {1978}, + doi = {10.1016/0025-5564(78)90063-9} +} + +@article{Prelle1983, + author = {Prelle, M. J. and Singer, M. F.}, + title = {Elementary first integrals of differential equations}, + journal = {Transactions of the American Mathematical Society}, + volume = {279}, + number = {1}, + pages = {215--229}, + year = {1983}, + doi = {10.1090/S0002-9947-1983-0704611-X} +} + +@article{Raia2011, + author = {Raia, Valentina and Schilling, Marcel and B{\"o}hm, Martin and Hahn, Bettina and Kowarsch, Andreas and Raue, Andreas and Sticht, Carsten and Bohl, Sebastian and Saile, Maria and M{\"o}ller, Peter and Gretz, Norbert and Timmer, Jens and Theis, Fabian and Lehmann, Wolf-Dieter and Lichter, Peter and Klingm{\"u}ller, Ursula}, + title = {Dynamic mathematical modeling of {IL13}-induced signaling in {Hodgkin} and primary mediastinal {B}-cell lymphoma allows prediction of therapeutic targets}, + journal = {Cancer Research}, + volume = {71}, + number = {3}, + pages = {693--704}, + year = {2011}, + doi = {10.1158/0008-5472.CAN-10-2987} +} + +@article{ReyBarreiro2023, + author = {Rey Barreiro, Xabier and Villaverde, Alejandro F.}, + title = {Benchmarking tools for a priori identifiability analysis}, + journal = {Bioinformatics}, + volume = {39}, + number = {2}, + eid = {btad065}, + year = {2023}, + doi = {10.1093/bioinformatics/btad065} +} + +@article{Rosser1962, + author = {Rosser, J. Barkley and Schoenfeld, Lowell}, + title = {Approximate formulas for some functions of prime numbers}, + journal = {Illinois Journal of Mathematics}, + volume = {6}, + number = {1}, + pages = {64--94}, + year = {1962}, + doi = {10.1215/ijm/1255631807} +} + +@article{Rump2010, + author = {Rump, Siegfried M.}, + title = {Verification methods: rigorous results using floating-point arithmetic}, + journal = {Acta Numerica}, + volume = {19}, + pages = {287--449}, + year = {2010}, + doi = {10.1017/S096249291000005X} +} + +@article{Savageau1987, + author = {Savageau, Michael A. and Voit, Eberhard O.}, + title = {Recasting nonlinear differential equations as {S}-systems: a canonical nonlinear form}, + journal = {Mathematical Biosciences}, + volume = {87}, + number = {1}, + pages = {83--115}, + year = {1987}, + doi = {10.1016/0025-5564(87)90035-6} +} + +@article{Schmiester2021, + author = {Schmiester, Leonard and Sch{\"a}lte, Yannik and Bergmann, Frank T. and others}, + title = {{PEtab}: interoperable specification of parameter estimation problems in systems biology}, + journal = {PLOS Computational Biology}, + volume = {17}, + number = {1}, + eid = {e1008646}, + year = {2021}, + doi = {10.1371/journal.pcbi.1008646} +} + +@article{Schwartz1980, + author = {Schwartz, J. T.}, + title = {Fast probabilistic algorithms for verification of polynomial identities}, + journal = {Journal of the ACM}, + volume = {27}, + number = {4}, + pages = {701--717}, + year = {1980}, + doi = {10.1145/322217.322225} +} + +@article{Sedoglavic2002, + author = {Sedoglavic, Alexandre}, + title = {A probabilistic algorithm to test local algebraic observability in polynomial time}, + journal = {Journal of Symbolic Computation}, + volume = {33}, + number = {5}, + pages = {735--755}, + year = {2002}, + doi = {10.1006/jsco.2002.0532} +} + +@article{Tunali1987, + author = {Tunali, E. T. and Tarn, T. J.}, + title = {New results for identifiability of nonlinear systems}, + journal = {IEEE Transactions on Automatic Control}, + volume = {32}, + number = {2}, + pages = {146--154}, + year = {1987}, + doi = {10.1109/TAC.1987.1104544} +} + +@article{Villaverde2016, + author = {Villaverde, Alejandro F. and Barreiro, Antonio and Papachristodoulou, Antonis}, + title = {Structural identifiability of dynamic systems biology models}, + journal = {PLOS Computational Biology}, + volume = {12}, + number = {10}, + eid = {e1005153}, + year = {2016}, + doi = {10.1371/journal.pcbi.1005153} +} + +@article{Villaverde2019, + author = {Villaverde, Alejandro F. and Tsiantis, Nikolaos and Banga, Julio R.}, + title = {Full observability and estimation of unknown inputs, states and parameters of nonlinear biological models}, + journal = {Journal of the Royal Society Interface}, + volume = {16}, + number = {156}, + eid = {20190043}, + year = {2019}, + doi = {10.1098/rsif.2019.0043} +} + +@article{Wang1982, + author = {Wang, Paul S. and Guy, M. J. T. and Davenport, J. H.}, + title = {P-adic reconstruction of rational numbers}, + journal = {ACM SIGSAM Bulletin}, + volume = {16}, + number = {2}, + pages = {2--3}, + year = {1982}, + doi = {10.1145/1089292.1089293} +} + +@article{Yates2009, + author = {Yates, James W. T. and Evans, Neil D. and Chappell, Michael J.}, + title = {Structural identifiability analysis via symmetries of differential equations}, + journal = {Automatica}, + volume = {45}, + number = {11}, + pages = {2585--2591}, + year = {2009}, + doi = {10.1016/j.automatica.2009.07.009} +} + +@inproceedings{Zippel1979, + author = {Zippel, Richard}, + title = {Probabilistic algorithms for sparse polynomials}, + booktitle = {Proc. Int. Symp. Symbolic Algebraic Manipulation (EUROSAM '79)}, + series = {Lecture Notes in Computer Science}, + volume = {72}, + publisher = {Springer}, + address = {Berlin, Heidelberg}, + pages = {216--226}, + year = {1979}, + doi = {10.1007/3-540-09519-5_73} +} diff --git a/pyproject.toml b/pyproject.toml index c984855..1f8158e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build" [project] name = "symident" -version = "0.17.0" +version = "0.18.0" description = "Structural identifiability of ODE models by Lie symmetries over finite fields" readme = "README.md" requires-python = ">=3.10" @@ -30,7 +30,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Scientific/Engineering :: Bio-Informatics", ] -dependencies = ["numpy>=1.24", "sympy>=1.12", "scipy>=1.11"] +dependencies = ["numpy>=1.24", "sympy>=1.12", "scipy>=1.11", "python-flint>=0.7.0"] [project.urls] Homepage = "https://github.com/dModverse/symident" @@ -41,7 +41,7 @@ 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"] -docs = ["sphinx>=8", "numpydoc", "pydata-sphinx-theme", "myst-parser"] +docs = ["sphinx>=8", "numpydoc", "pydata-sphinx-theme", "myst-parser", "sphinxcontrib-bibtex>=2.6"] [tool.scikit-build] wheel.packages = ["src/symident"] diff --git a/src/symident/__init__.py b/src/symident/__init__.py index f39dd14..4d4a081 100644 --- a/src/symident/__init__.py +++ b/src/symident/__init__.py @@ -8,4 +8,4 @@ __all__ = ["Model", "Symmetries", "Symmetry", "Reduction", "detect", "reduce", "read_petab", "PEtabError", "reconst_control", "install_msolve", "switches"] -__version__ = "0.17.0" +__version__ = "0.18.0" diff --git a/src/symident/api.py b/src/symident/api.py index 3c3dde9..adc281a 100644 --- a/src/symident/api.py +++ b/src/symident/api.py @@ -6,7 +6,7 @@ import numpy as np -from . import report, state +from . import _core, report, state from .detection import pivot_choice, symmetry_detection from .errors import InputError from .options import reconst_control @@ -14,8 +14,15 @@ from .reduction.core import check_levels, detection_positive, finish_reduction from .sym.domain import declared +# 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") + def _rhs_from_reactions(species, smatrix, rates): + """The right-hand sides of a reaction network, state name to expression.""" S = np.asarray(smatrix, dtype=float) out = {} for j, s in enumerate(species): @@ -37,7 +44,7 @@ class Model: ---------- odes : dict, optional Right-hand sides, state name to expression (``^`` or ``**`` for powers), with - switches such as ``piecewise()`` and comparisons allowed (see the user guide). + switches such as ``piecewise()`` and comparisons allowed (see the guide). Derived from ``reactions`` when omitted. observables : dict or list of dict Observables, name to expression; a list gives one dict per condition. @@ -55,7 +62,7 @@ class Model: A list holds one transformation per condition. conditions : pandas.DataFrame or dict, optional One row per condition; a numeric cell fixes a symbol, a string replaces it by an - expression or another name, and a column named like a state sets its initial value. + expression or another name, and a column named like a state sets the initial value of that state. As a dict: ``{"rows": [...], "cols": {name: [values]}}``. events : list of dict, optional Events with keys ``var``, ``time``, ``value`` and ``method`` (``replace``, @@ -68,7 +75,7 @@ class Model: Input states, zero at the start and at rest; an event sets them. unknown_inputs : sequence of str Unknown functions of time of no assumed form, symbols in the right-hand sides and - observables without an equation. A direction may change them along with the parameters (see the user guide). + observables without an equation. A direction may change them along with the parameters (see the guide). known_inputs : sequence of str Known functions of time of no assumed form, symbols in the right-hand sides and observables without an equation; their values and time derivatives are known. @@ -80,7 +87,7 @@ class Model: The regimes an experiment visits, for a model with switches: each entry is a comparison or a list of comparisons that selects the regimes on those sides, the first entry the regime at the start; a dict gives one list per condition name. - Without it every regime counts. See the user guide. + Without it every regime counts. See the guide. equilibrate : bool, optional The default of :func:`detect`'s ``equilibrate`` for this model. positive : bool or sequence of str, optional @@ -159,9 +166,6 @@ def _trace(on): -_ATOMS = frozenset((str, int, float, bool, type(None))) - - 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.""" @@ -187,6 +191,7 @@ def _model_copy(model): out.__dict__ = {k: _data_copy(v) for k, v in vars(model).items()} return out + class Symmetry(dict): """One non-identifiable direction, a dict whose entries are also attributes. @@ -296,20 +301,20 @@ class Symmetries: they do not apply). * ``order_bound``, ``order_bound_why``: the probability that a certified order is not sufficient, or why there is none; ``order_draws``: the most points drawn for one - random point of the Lie order certificate, which multiplies its terms. + random point of the Lie order certificate, which multiplies the terms of the certificate. * ``bound``: the probability that a wrong closed form passes the kernel check, or why none applies. ``proof``: per direction verified on every entry, why the exact proof did not apply; ``attempts``: per open direction, the routes tried and why they failed. * ``verification``: the saturation guard, with ``ok`` and ``reason``; where ``ok`` is False the rank still grows past the order used. - * ``projection``: the rank modulo the unknown inputs, or modulo resting states whose - Jacobian is singular at the base point. + * ``projection``: the rank modulo the unknown inputs, modulo the fresh coordinates of + switch surfaces, or modulo resting states whose Jacobian is singular at the base point. * ``unknown_inputs``, ``known_inputs``: per input the jets and the order up to which they are exact. * ``assumptions``: the declared ``domain`` and switch ``starts`` the result assumes, and the ``error_bound`` of a verified closed form or rank. - * ``limits``: the time limits, budgets and orders that stopped part of the + * ``limits``: the work caps and orders that stopped part of the analysis; while it is not empty, a direction without closed form may have one. ``errors``: exceptions a route recorded. * ``branches``: resting states with several roots modulo a prime, and the one taken. @@ -372,7 +377,7 @@ def summary(self, verbose=False): """ return _Text("\n".join(report.summary_lines(self._raw, verbose))) - def solution_count(self, order=None, timeout=600): + def solution_count(self, order=None): """The number of values of the coordinates that give the output of a generic one. Local identifiability leaves finitely many such values; more than one is a discrete @@ -387,14 +392,13 @@ def solution_count(self, order=None, timeout=600): ---------- order : int, optional The highest Taylor coefficient; twice the number of coordinates by default. - timeout : float - Seconds msolve may take. Returns ------- dict or None ``{"count", "order", "prime"}``, or None where the model is not rational, msolve - fails or times out, or the solutions are not finitely many. Points where a + fails, reaches the work caps (``msolve_entries`` and ``msolve_terms`` of + :meth:`discrete`), or the solutions are not finitely many. Points where a coordinate or a denominator vanishes are not counted. Raises @@ -430,9 +434,10 @@ def solution_count(self, order=None, timeout=600): raise ValueError("solution_count() handles one condition without events") seg = parts[0]["segments"][0] f, g, ic = seg["f"], seg["g"], seg["ic"] - return solution_count(f, g, ic, list(self.info["coordinates"]), order, timeout=timeout) + return solution_count(f, g, ic, list(self.info["coordinates"]), order) - def discrete(self, order=None, points=5, timeout=600, budget=300, cores=1): + 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 @@ -445,8 +450,15 @@ def discrete(self, order=None, points=5, timeout=600, budget=300, cores=1): (``"exact"``). Permutations of coordinates with the same dependence of the output are tested as candidates first. A model with logarithmic coordinates, observables under an injective function or factors ``exp(a*time)`` is rewritten into rational form with the - same fiber, and the results are given in the coordinates of the model. A sigma that maps - no point of the domain into it is listed but not relevant. + same fiber, and the results are given in the coordinates of the model. Other non-rational + terms of the states become new states and new coordinates, their values at the start; the + count is then that of this relaxed model (``info["relaxed"]``). A free power x^alpha of a + state that starts at 0 enters through (x/c)^alpha, c the leading Taylor coefficient of x, as + a series in t and t^(k*alpha) (``info["start_powers"]``). A sigma that maps no point of + the domain into it is listed but not relevant. The jets of unknown inputs are unknowns of the + count, not coordinates; a sigma may change the input (``state_maps``). A result of ``reduce_cq`` + is counted on the level sets of the conserved totals, with the species solved through the + totals in ``info["eliminated"]``. Parameters ---------- @@ -455,13 +467,39 @@ def discrete(self, order=None, points=5, timeout=600, budget=300, cores=1): points : int or list of dict The number of random points of the count in the domain, or the points themselves as ``{coordinate: value}``. - timeout : float - Seconds one call of msolve may take. - budget : float - Seconds the reconstruction of the maps may take; past it, the counts are reported - without closed forms. cores : int Threads of msolve. + memory : float, optional + GiB of address space one call of msolve may take, 8 by default; past it the call + fails. + experiments : bool or int, optional + The count of several experiments with shared parameters and free starts, projected + onto the parameters and starts of the first, which bounds the fiber of a model with + free starts and no rational first integral, proven at one point of the parameters + (docs/method/global.rst, "Several experiments"). By default it runs where a short count of + one experiment finds none; ``True`` runs it first with the number of experiments from + the rank criterion, a number ``K`` with ``K`` experiments, ``False`` never. + ``info["experiments"]`` reports it, or why it does not apply. + msolve_entries : int, optional + The nonzero entries of the matrices of the F4 rounds that one call of msolve may reduce, + 4 * 10^8 by default, read from the output of msolve; the call ends after the round that + passes it, without a result. The first short count and the count of a block before the + stages take a fraction of it. + msolve_terms : int, optional + The most terms of one system given to msolve, 10^5 by default; a larger system is not + solved. + search_entries : int, optional + The entries of the matrices over finite fields that the exact count may reduce, 5 * 10^8 + by default, in the search for the invariant functions as rational functions of the + output coefficients (docs/method/global.rst, "The exact count"). + elimination_terms : int, optional + The most terms of a polynomial of the elimination of the states in the exact count, + 3 * 10^6 by default. + + The global analysis stops on these work limits and on further fixed caps on orders, + points and candidates, never on a clock, so that the result is the same on every machine. + A count or a proof that reaches a limit ends without a result, and ``info["limits"]`` or + the certificate names the limit and the value of the limit. Returns ------- @@ -472,40 +510,84 @@ def discrete(self, order=None, points=5, timeout=600, budget=300, cores=1): None with the ``domain_conditions`` under which sigma(theta) lies in the domain) and ``fixed_set``, the factors on which sigma fixes theta. ``info``: ``order``, ``count`` (solutions over the algebraic closure at a random point modulo a prime), + ``count_bound`` (the probability that a generic point has more, None where the count + is exact or has no bound), + ``count_domain`` (the points of the fiber of a generic point of the domain inside the + domain, where the count is final and each map keeps the domain or leaves it entirely, + else None), ``counts`` per point (``complex``, ``real``, ``in_domain``, ``undecided``), ``closed_forms``, ``count_final`` (every solution is the image of a proven sigma), ``fundamental_domain`` (inequalities that keep one point of each orbit), ``rewrites``, ``candidates``, ``timing`` (seconds per stage), ``certificate`` (what - the result rests on: the invariance per map, the size of the orbit, the count and - the axiom of the count) and ``limits``. + the result rests on: the invariance per map, the size of the orbit, ``exact`` with the + invariant functions as rational functions of the output coefficients, the verified + count with ``count_bound``, or the axiom of the count where neither applies, and + ``complete``: ``"exact"``, ``"verified"``, ``"axiom"``, ``"no"`` or ``"open"``; with the + count of several experiments also ``route``, and ``pinned`` where the exact search stopped + and the functions it proved were counted), ``experiments`` (the number of experiments, + the orders, the count and the certificate ``first_integrals`` of the premise, or ``why`` + the route does not apply) and ``limits``. Raises ------ ValueError - Unless the result is identifiable and was detected without ``equilibrate`` and - ``reduce_cq``, on a model with one condition and no events, switches or unknown - inputs. + Unless the result is identifiable and was detected without ``equilibrate``, on a + model with one condition and no events or switches, and for a model with unknown inputs + and events, switches or more than one condition. MsolveMissingError 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} + 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}") + with work.msolve_memory(memory), work.caps(**limits): + return self._discrete(order, points, cores, experiments) + + 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) + if not (out["info"].get("certificate") or {}).get("relaxed_why"): + return out + except ValueError: + pass # the continuous symmetries first: the reduced model has a finite fiber - red = self._reduced_detection() - out = red.discrete(order=order, points=points, timeout=timeout, budget=budget, cores=cores) + try: + red = self._reduced_detection() + 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) + 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)} - self.info["discrete"] = out["info"] - self.discrete_symmetries = self._raw["discrete_symmetries"] = out["symmetries"] - # a reduction computed before holds no discrete symmetries - self.__dict__.pop("_reductions", None) - return out + return self._keep_discrete(out) coords = list(self.info["coordinates"]) - # 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()") + 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()") + except NotRationalError as exc: + return self._relaxed_discrete(exc, order=order, points=points, cores=cores, experiments=experiments) st = self.info.get("settings") or {} positive = st.get("positive", True) if rw["logs"] and positive is not True: @@ -513,19 +595,127 @@ def discrete(self, order=None, points=5, timeout=600, budget=300, cores=1): 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, list(self.model.odes), order=order, - start=self.info.get("lie_order_used"), points=points, timeout=timeout, budget=budget) + 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()} + free = [t for t in self.model.totals or {} if t in set(coords)] + if free: + # the domain of a free total holds the total, not the species solved through it + 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") + 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) + + def _keep_discrete(self, out): + """The result `out` of discrete(), stored on this result.""" self.info["discrete"] = out["info"] self.discrete_symmetries = self._raw["discrete_symmetries"] = out["symmetries"] + # a reduction computed before holds no discrete symmetries self.__dict__.pop("_reductions", None) return out + def _relaxed_discrete(self, exc, **opts): + """discrete() on the relaxed model of detection.relax: the count there, modulo the continuous directions, bounds + 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 + m = self.model + 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))): + raise exc + coords = list(self.info["coordinates"]) + odes, trafo, positive, events, chart = m.odes, m.trafo, st.get("positive", True), None, None + try: + 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 {}) + 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 + 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) + 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 + 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") + 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"]], + "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 [])} + 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'])"] + 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") + if why is not None: + # the count of the relaxed model bounds nothing here + info["relaxed"]["count"], info["count"] = count, None + info["count_domain"] = None + cert["relaxed_why"] = why + if cert.get("complete") in ("exact", "verified", "axiom"): + cert["complete"] = "open" + info["count_final"] = False + elif premise is not None: + # with the premises of the count of the relaxed model + cert["premise"] = "; ".join(p for p in (cert.get("premise"), premise) if p) + if cert.get("complete") in ("exact", "verified"): + cert["complete"] = "axiom" + 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") + for s in out["symmetries"]: + if s.get("map"): + s["relaxed"] = True + return self._keep_discrete(out) + def _reduced_detection(self): """The detection on the model reduced by :meth:`reduce`, which must be locally identifiable.""" st = self.info.get("settings") or {} @@ -533,23 +723,21 @@ def _reduced_detection(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) - red = res.reduce().to_dict() + # 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"])) - m = copy.copy(self.model) - rm = reduced_model(m.odes, m.observables, m.trafo, m.conditions, m.events, red["trafo"], - bool(st.get("equilibrate"))) - if rm["why"] is not None: - raise ValueError("discrete(): " + rm["why"]) - m.trafo, m.conditions = rm["trafo"], rm["conditions"] - m.fixed = list(dict.fromkeys(list(m.fixed or []) + list(res.gauge or []) + list(red.get("fixed") or []) + - rm["fixed"])) - r = detect(m, positive=st.get("positive", True), engine=st.get("sym_engine", "modular"), - equilibrate=bool(st.get("equilibrate"))) + 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"))) if not r.identifiable: raise ValueError("discrete(): the reduced model is not locally identifiable") r._section = red.get("trafo") + r._relaxed = getattr(self, "_relaxed", False) return r def _fiber_parts(self, order, what, switches=True): @@ -573,18 +761,23 @@ def _fiber_parts(self, order, what, switches=True): from .sym.switching import _SWITCHY m = self.model st = self.info.get("settings") or {} - if m.unknown_inputs: + unknown = [str(w) for w in m.unknown_inputs or []] + if unknown and what != "discrete()": raise ValueError(f"{what} handles no unknown inputs") - if st.get("reduce_cq"): - raise ValueError(f"{what} needs a result of detect() without reduce_cq") equil = bool(st.get("equilibrate")) if equil and getattr(m, "known_inputs", None): raise ValueError(f"{what} handles no known inputs under equilibrate") f0 = {str(k): str(v) for k, v in dict(m.odes).items()} obs = m.observables + events = as_events(m.events) or [] + recon = {} + 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 texts = list(f0.values()) + [str(v) for o in (obs_list or [obs]) for v in dict(o).values()] - events = as_events(m.events) or [] roots = [e for e in events if e.get("root") is not None] hy = None if self.info.get("switching") or roots or any(_SWITCHY.search(v) for v in texts): @@ -612,7 +805,8 @@ 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(v) for k, v in dict((trafos[c] if trafos else m.trafo) or {}).items()} + 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)) @@ -641,7 +835,7 @@ def apply(e, steps=steps): regimes = self._regimes(hy, c, apply, tr, cells, inputs, start, what) if hy is not None else None fc = f0 if regimes is not None: - # the condition runs in the regime of its start; each allowed regime is a copy with a free start + # the condition runs in the regime of the start; each allowed regime is a copy with a free start fc, g = regimes[0]["f"], regimes[0]["g"] g = {k: apply(v) for k, v in g.items()} f = {k: apply(fc[k]) for k in observed_states(fc, g, ev)} @@ -675,10 +869,18 @@ def key(e): taken = set(get_symbols(list(f.values()) + list(g.values()))) | set(f) f, jets = _input_jets(f, known, 2 * order + 12, taken) ic.update({x: x for names in jets.values() for x in names}) + free_jets = {} + 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) # the clock advances at rate one from the start f["time"], ic["time"] = "1", start one_seg = K == 1 and not keys segs = [{"f": f, "g": g, "ic": ic, "t": start, "label": "" if one_seg else f"{rows[c]}:"}] + if free_jets: + segs[0]["inputs"], segs[0]["input_of"] = list(free_jets), free_jets for t in keys: evs = [{k: e[k] for k in ("var", "method", "value")} for e in later if key(e) == t] segs.append({"f": f, "g": g, "events": evs, "t": t, "label": f"{rows[c]}@{t}:"}) @@ -690,7 +892,7 @@ def key(e): fr = {x: apply(r["f"][x]) for x in observed_states(r["f"], gr, [])} icr = {x: None for x in fr} if known: - # the input is known at the switch as well: its jets take known values + # the input is known at the switch as well: the jets take known values taken = set(get_symbols(list(fr.values()) + list(gr.values()))) | set(fr) fr, jets_r = _input_jets(fr, known, 2 * order + 12, taken) icr.update({x: x for names in jets_r.values() for x in names}) @@ -707,15 +909,15 @@ def key(e): 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 ()), list(m.odes)) + parts, rewrites, logs = rationalize(parts, list(self.info.get("coordinates") or ()), states) except NotRationalError: raise except SYMPY_FAILS as exc: raise ValueError(f"{what} needs a model rational in the states and coordinates") from exc - return parts, {"rewrites": rewrites, "logs": logs} + return parts, {"rewrites": rewrites, "logs": logs, "states": states, "eliminated": recon} def _switches(self, f, obs, events, what): - """The model in the indicators of its undecided switches (sym.switching.Hybrid), a dict where the declared + """The model in the indicators of the undecided switches (sym.switching.Hybrid), a dict where the declared signs decide them all, or None.""" from .errors import InapplicableError from .sym.switching import hybrid_model @@ -830,7 +1032,10 @@ class Reduction: positivity certificate as conditions on the new parameters, and the trafo covers the orbits on which they hold. A face section (``face``) holds ``face_why``, why the model is not shown continuous up to the face (``None`` when it is), and - ``face_level``. + ``face_level``. A block of directions that unknown inputs absorb holds ``inputs``: the + inputs (``absorb``), the ``proof`` (``"inversion"`` with the ``determinant``, or + ``"lift"`` with the components of the lift per direction) and the ``condition`` under + which the section gives the output of a point. removed, remaining : list of str Labels of the directions. dependent : list of str @@ -838,8 +1043,8 @@ class Reduction: alternatives : list of dict The charts of the other valid choices of the fixed coordinates, each with ``trafo``, ``pins``, ``removed``, ``remaining`` and ``rational``; the returned one has the best - level, removes the most directions, and prefers charts without ``sign_conditions`` and - a rational trafo. + level, removes the most directions, and prefers charts without ``sign_conditions``, then + charts that cover the whole domain, then a rational trafo. partial : list of str Removed directions whose chart covers only part of the domain: some positive coordinates have no positive preimage in the new parameters. @@ -862,7 +1067,7 @@ class Reduction: Exceptions that the reduction turned into failed routes, such as an alternative section left out (see the ``DEBUG`` switch). limits : list of str - The work budgets and time limits that stopped a section or invariant search. + The work caps that stopped a section or invariant search. coordinates : list of str The coordinates of the detection. fixed : list of str @@ -875,7 +1080,7 @@ class Reduction: are stated in (the reduced model's for a model with directions). ``injective`` and ``reach`` of a section refer to the orbits of the directions: a discrete symmetry maps a point of the section to another point with the same output, which the fundamental - domain excludes. ``branches`` holds per side of the fixed set of the map its chart (see + domain excludes. ``branches`` holds per side of the fixed set of the map the chart of that side (see :func:`reduce`, ``branch``), ``branch`` the chosen one, and ``why`` the reason where there are none. """ @@ -934,9 +1139,6 @@ def __repr__(self): return str(self) -_GLOBAL_OPTIONS = ("order", "points", "timeout", "budget") - - def _check_detect(model, *, cores, engine, trace, control, gauge, mode="local", global_options=None): """InputError for an argument of detect() that no analysis takes.""" if mode not in ("local", "global"): @@ -962,7 +1164,7 @@ def _check_detect(model, *, cores, engine, trace, control, gauge, mode="local", 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, discrete=None): + engine="modular", trace=False, mode="local", global_options=None): """Structural non-identifiabilities of a model, locally and, with ``mode="global"``, globally. Parameters @@ -1011,22 +1213,14 @@ def detect(model, *, scalings_only=False, equilibrate=None, reduce_cq=None, free ``info["discrete"]``; a model the global analysis does not handle gets the reason in ``info["discrete"]["unsupported"]`` and a warning. global_options : dict, optional - Arguments of the global analysis: ``order``, ``points``, ``timeout`` and ``budget`` of - :meth:`Symmetries.discrete`. - discrete : bool or dict, optional - Deprecated: ``True`` is ``mode="global"``, a dict also sets ``global_options``. + Arguments of the global analysis: ``order``, ``points``, ``memory``, ``experiments`` and the + work limits ``msolve_entries``, ``msolve_terms``, ``search_entries`` and + ``elimination_terms`` of :meth:`Symmetries.discrete`. Returns ------- Symmetries """ - if discrete: - warnings.warn("`discrete` is deprecated; use mode='global' (and global_options)", DeprecationWarning, - stacklevel=2) - mode = "global" - if isinstance(discrete, dict): - global_options = {**discrete, **(global_options or {})} - global_options.pop("cores", None) _check_detect(model, cores=cores, engine=engine, trace=trace, control=control, gauge=gauge, mode=mode, global_options=global_options) if mode == "global": @@ -1048,7 +1242,11 @@ def run(pivots, cq_pivots): reconstruct=reconstruct, positive=positive, verify=verify, cores=cores, control=control or reconst_control(), scalings_only=scalings_only, sym_engine=engine) - res = Symmetries(pivot_choice(run, free_initial, reduce_cq), model) + try: + res = Symmetries(pivot_choice(run, free_initial, reduce_cq), model) + finally: + # the jets the kernel keeps for calls at higher orders belong to this detection + _core.sym_clear_jets() n_open = sum(s.level == "open" for s in res.symmetries) free_moiety = equilibrate and not reduce_cq and bool(model.totals) if free_moiety and n_open: @@ -1072,16 +1270,31 @@ def global_step(res, options=None, cores=1): return res +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()): + return positive + ident = re.compile(r"[A-Za-z_.][A-Za-z0-9_.]*\b(?!\s*\()") + coords = {t for v in (red.get("trafo") or {}).values() for t in ident.findall(str(v))} + out = sorted(c for c in coords if (dom[c] == "positive" if c in dom else names is None or c in names)) + out += [x for x in states if (names is None or x in names) and x not in out] + 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, timeout=600, alternatives=False, allow_open=True, allow_checked=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 invariants are coordinates on the quotient of the parameter space by the orbits, a chart, which is returned only where it is valid on the declared domain. A scaling (``Symmetry.kind``) fixes one - coordinate to one, a translation is replaced by its linear invariants with a coordinate fixed to zero on - a face of the positive orthant, and a curved direction by its invariants. + coordinate to one, a translation is replaced by the linear invariants with a coordinate fixed to zero on + a face of the positive orthant, and a curved direction by the invariants of that direction. Parameters ---------- @@ -1098,10 +1311,6 @@ def reduce(result, *, fixed=None, positive=None, d_poly=3, d_darboux=2, d_exp=2, Solve separable blocks by quadratures. zero_limits : bool Report which coordinates each block can drive to zero. - timeout : float - Wall time of the section search per block in seconds, 600 by default; ``math.inf`` lets - the search run to its end. A block that reaches it is named in ``Reduction.limits``. - Unlike ``work_cap``, it makes the result depend on the load of the machine. work_cap : int Candidate sections the search of one block may try; reaching it is an entry in ``Reduction.limits``. @@ -1121,7 +1330,7 @@ def reduce(result, *, fixed=None, positive=None, d_poly=3, d_darboux=2, d_exp=2, left; needs the model of a :class:`Symmetries` result of a detection without ``scalings_only``. Large models may turn it off. branch : str, optional - With a discrete symmetry of a detection with ``mode="global"``: the side of its fixed set + With a discrete symmetry of a detection with ``mode="global"``: the side of the fixed set as an inequality, such as ``"k01 > k12"``, on which the trafo maps free values in the positive orthant one to one, chained with the section; ``Reduction.discrete["branches"]`` lists the sides. Without it every branch is in ``Reduction.alternatives`` and the trafo is @@ -1148,9 +1357,17 @@ def reduce(result, *, fixed=None, positive=None, d_poly=3, d_darboux=2, d_exp=2, if positive is None: positive = detection_positive(raw) check_levels(raw, allow_open, allow_checked) - red = symmetry_reduction(raw, fixed=fixed, positive=positive, d_poly=d_poly, d_darboux=d_darboux, + absorbed, notes = raw, {} + 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, - timeout=timeout, alternatives=alternatives, work_cap=work_cap) + 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) finish_reduction(raw, red) @@ -1183,7 +1400,7 @@ def _branches(red, d, raw, positive, branch): if d.get("reduced") and section != red.get("trafo"): # the maps are stated in the coordinates of the section that the global analysis took red["discrete"]["branches"] = [] - red["discrete"]["why"] = "the discrete symmetries hold in the chart of reduce() with its default settings" + red["discrete"]["why"] = "the discrete symmetries hold in the chart of reduce() with the default settings" else: bc = branch_charts(red["discrete"], red.get("trafo"), list(raw["info"].get("coordinates") or []), positive) red["discrete"]["branches"] = bc.get("branches") or [] @@ -1248,20 +1465,28 @@ def compose(inner): return {"trafo": trafo, "conditions": conditions, "fixed": fixed, "why": why} +def _reduced_copy(model, red, gauge, equilibrate): + """(model, why): a copy of `model` with the trafo of the reduction `red` applied and the fixed coordinates + added, or (None, why) where the model cannot take the trafo.""" + m = copy.copy(model) + rm = reduced_model(m.odes, m.observables, m.trafo, m.conditions, m.events, red["trafo"], 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"])) + return m, None + + def _closed_loop(result, red): """The detection on the model with the trafo applied: the directions found against the remaining ones.""" if result.model is None or result.method != "observability": return None st = result.info.get("settings") or {} want = len(red.get("remaining") or []) - m = copy.copy(result.model) - rm = reduced_model(m.odes, m.observables, m.trafo, m.conditions, m.events, red["trafo"], - bool(st.get("equilibrate"))) - if rm["why"] is not None: - return {"ok": None, "directions": None, "expected": want, "reason": "not run, " + rm["why"]} - m.trafo, m.conditions = rm["trafo"], rm["conditions"] - m.fixed = list(dict.fromkeys(list(m.fixed or []) + list(result.gauge or []) + list(red.get("fixed") or []) + - rm["fixed"])) + m, why = _reduced_copy(result.model, red, result.gauge, bool(st.get("equilibrate"))) + if why is not None: + 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")), diff --git a/src/symident/detection/bound.py b/src/symident/detection/bound.py index 0755a33..dc684ae 100644 --- a/src/symident/detection/bound.py +++ b/src/symident/detection/bound.py @@ -175,17 +175,6 @@ def no_degree(exprs): return None -def state_degrees(model_lines, obs_lines, states): - """field_degrees() of the right-hand sides and observables in the states, every other symbol a constant.""" - try: - f = [model_sympify(str(l).split("=", 1)[1]) for l in model_lines] - g = [model_sympify(str(l).split("=", 1)[1]) for l in obs_lines] - except SYMPY_FAILS as exc: - sympy_fail(exc) - return None - return field_degrees(f, g, [spy.Symbol(str(x)) for x in states]) - - def total_degrees(model_lines, obs_lines): """field_degrees() of the right-hand sides and observables in all their symbols, None where not rational.""" try: diff --git a/src/symident/detection/classify.py b/src/symident/detection/classify.py index b8ef439..d819038 100644 --- a/src/symident/detection/classify.py +++ b/src/symident/detection/classify.py @@ -136,8 +136,9 @@ def report_physical(result, znames, aux_names, sc, nz, P, aux_field, flag_joint= return result -def peel_scalings(scal_res, znames, nz, zval, P, N, modulo=None): - """Independent scalings of all conditions with tangent in the nullspace (modulo `modulo`), exact per entry.""" +def peel_scalings(scal_res, znames, nz, zval, P, N, modulo=None, shifts=()): + """Independent scalings of all conditions with tangent in the nullspace (modulo `modulo`), exact per entry; a + coordinate in `shifts` is translated by the weight.""" scaling = [] Bmat = np.zeros((nz, 0), dtype=np.int64) env = {z: int(v) for z, v in zip(znames, zval)} @@ -164,7 +165,12 @@ def eval_w(w): v[zi[k]] = w % P if not np.any(v): continue - tangent = (v * (np.asarray(zval, dtype=np.int64) % P)) % P + moved = set(names) & set(shifts) + if moved and not d.get("exact"): + continue + scale = np.asarray(zval, dtype=np.int64) % P + scale[[zi[k] for k in moved]] = 1 + tangent = (v * scale) % P if modulo is not None and N.shape[1]: free, nuis = modulo proj = (N.astype(object) @ tangent[free].astype(object)) % P @@ -177,6 +183,12 @@ def eval_w(w): Bmat = np.concatenate([Bmat, tangent.reshape(nz, 1)], axis=1) order = sorted(range(len(names)), key=lambda i: names[i].encode()) supp = [names[i] for i in order] + 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))}) + 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"], diff --git a/src/symident/detection/closedform.py b/src/symident/detection/closedform.py index f795f45..926fbaf 100644 --- a/src/symident/detection/closedform.py +++ b/src/symident/detection/closedform.py @@ -1,12 +1,11 @@ """Closed-form entries: monomial strings, rational fits from residues, back-substitution.""" import re -import time import numpy as np import sympy as spy -from .. import _core, session +from .. import _core from ..errors import SYMPY_FAILS, sympy_fail from ..gfp import rat_recon from ..sym.charts import recast_backsub_expr @@ -14,15 +13,6 @@ from ..sym.parse import _RPrinter, model_sympify -def expired(ctrl): - """Whether the deadline in `ctrl` has passed; a passed deadline is recorded as a limit.""" - d = ctrl.get("deadline") - if d is None or time.monotonic() <= d: - return False - session.note("limits", f"timeout: the reconstruction stopped after {ctrl.get('timeout')} s") - return True - - def mono_string(expo, vars_): """The monomial with exponents `expo` in `vars_` as a string, "1" for the constant.""" terms = [] @@ -94,10 +84,15 @@ def recast_backsub(vector, recast): return out +_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_.]*") + + def eval_modq(expr, env, q): """Rational expression at the integer point env modulo q; None if the denominator vanishes.""" + # the names the expression holds: a point over many coordinates adds no symbol to the parse + names = [nm for nm in dict.fromkeys(_NAME.findall(str(expr))) if nm in env] try: - v = eval_rational_mod(str(expr), list(env.keys()), [int(x) for x in env.values()], int(q)) + v = eval_rational_mod(str(expr), names, [int(env[nm]) for nm in names], int(q)) except SYMPY_FAILS as exc: sympy_fail(exc) return None diff --git a/src/symident/detection/core.py b/src/symident/detection/core.py index 653cab2..36d4582 100644 --- a/src/symident/detection/core.py +++ b/src/symident/detection/core.py @@ -787,7 +787,7 @@ def _detection(kw): st = res["info"].setdefault("settings", {}) if getattr(ses, "rest_leaves", None): st["rest_leaves"] = ses.rest_leaves - st.update(control={k: v for k, v in ses.control.items() if k != "deadline"}, + 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__) @@ -1235,14 +1235,19 @@ def deliver(raw, method): res["info"]["model_inputs"] = list(forcings) if jets: every = {x for names in jets.values() for x in names} + # a jet under a log chart is a nuisance coordinate in the log coordinate of the chart + charted = {m["L"] for m in (log_arg or {}).get("map") or [] if m["v"] in every} for s in res["symmetries"]: # the input change of a proven field; a kernel vector holds it only at the start 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" else None + if s.get("level") == "exact" and not charted & set(lift) else None if lift: - s["state_components"] = {k: v for k, v in lift.items() if k not in every} or None + # 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 nu = raw.get("nuisance") or {} res["info"]["unknown_inputs"] = { "names": list(jets), "jets": jets, "jet_order": int(jet_order), @@ -1736,10 +1741,14 @@ def zero_one(i): "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 - nm = jet_start.get - _mark_nuisance(multi, {"states": [nm(x, x) for names in jets.values() for x in names], - "kept": [nm(w, w) for w in jets], - "tops": [nm(names[-1], names[-1]) for names in jets.values()], + # a jet state under a log chart is a nuisance coordinate in the log coordinate of the chart + logs = {m["v"]: m["L"] for m in (log_arg or {}).get("map") or []} + + 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)}) elif multi.get("ok") and nuisance: diff --git a/src/symident/detection/cq.py b/src/symident/detection/cq.py index f3def4f..0acbcc0 100644 --- a/src/symident/detection/cq.py +++ b/src/symident/detection/cq.py @@ -10,8 +10,14 @@ from ..rexpr import eval_numeric, get_symbols, replace_symbols from ..sym.parse import _is_rational_expr, _make_local_parse +# the pivot sets that tie with the chosen one by structure, at most this many in all +PIVOT_CHOICES = 6 +# rays of the cone of nonnegative conservation laws past which the order of the species decides the basis +_RAY_CAP = 400 + def _coef_matrix(totals, states, shift=0.0): + """(C, species, sets): the coefficients of the species in the linear totals, other symbols at a generic point.""" stset = set(states) sets = [[s for s in get_symbols(e) if s in stset] for e in totals.values()] species = list(dict.fromkeys(s for st in sets for s in st)) @@ -30,10 +36,6 @@ def _coef_matrix(totals, states, shift=0.0): return C, species, sets -# the pivot sets that tie with the chosen one by structure, at most this many in all -PIVOT_CHOICES = 6 - - def _rank(M): """The numerical rank of a small matrix of coefficients at a generic point.""" M = np.asarray(M, dtype=float) @@ -279,10 +281,6 @@ def check_conserved(totals, f): f"the right-hand sides is {str(d).replace('**', '^')}, not zero") -# rays of the cone of nonnegative conservation laws past which the order of the species decides the basis -_RAY_CAP = 400 - - def _primitive(v): """The integer vector of the direction of the rational vector `v`, coprime entries.""" v = [Fraction(x) for x in v] @@ -437,10 +435,18 @@ def conserved_totals(smatrix, species): from sympy.polys.domains import QQ from sympy.polys.matrices import DomainMatrix n = len(species) - rows = [[QQ(_exact(x).numerator, _exact(x).denominator) for x in r] for r in smatrix] - if not rows: + rows = {} + for i, r in enumerate(smatrix): + nz = {} + for j, x in enumerate(r): + if x: + q = _exact(x) + nz[j] = QQ(q.numerator, q.denominator) + if nz: + rows[i] = nz + if not len(smatrix): return {} - red, piv = DomainMatrix(rows, (len(rows), n), QQ).to_sparse().rref() + red, piv = DomainMatrix(rows, (len(smatrix), n), QQ).rref() R = red.rep laws = [] for free in (c for c in range(n) if c not in set(piv)): @@ -560,35 +566,66 @@ def _sink_cluster(M): return zero, [r for r in drained if len(r) > 1 and not set(r) & set(zero)] +def _one_way(smatrix, rates): + """The reactions with each net rate whose numerator has terms of both signs split into a forward and a backward + reaction, the terms of each sign over the denominator: every rate then runs one way.""" + S = np.nan_to_num(np.asarray(smatrix, dtype=float)) + rows, out = [], [] + for i, r in enumerate(rates): + r = str(r) + parts = None + try: + _, parse = _make_local_parse([r]) + e = parse(r) + if _is_rational_expr(e): + num, den = spy.fraction(spy.together(e)) + terms = spy.Add.make_args(spy.expand(num)) + pos = spy.Add(*[t for t in terms if t.as_coeff_Mul()[0] > 0]) + neg = -spy.Add(*[t for t in terms if t.as_coeff_Mul()[0] < 0]) + if pos != 0 and neg != 0: + parts = [str(pos / den), str(neg / den)] + except SYMPY_FAILS as exc: + sympy_fail(exc) + if parts is None: + rows.append(S[i]) + out.append(r) + continue + rows += [S[i], -S[i]] + out += parts + return np.asarray(rows, dtype=float).reshape(-1, S.shape[1] if S.ndim == 2 else 0), out + + def _zero_states(smatrix, species, rates, forcings): """(zero, branches): the states forced to zero at rest with the forcings at zero, and _sink_cluster() branches.""" S = np.nan_to_num(np.asarray(smatrix, dtype=float)) if S.size == 0: return [], [] - rates = [str(r) for r in rates] + S, rates = _one_way(S, rates) vs = [set(get_symbols(r)) for r in rates] allv = set().union(*vs) if vs else set() dead = [f for f in forcings if f in set(species) | allv] live = [True] * len(rates) check = list(range(len(rates))) branches = [] + col = {sp: j for j, sp in enumerate(species)} while True: for i in check: live[i] = not _expr_is_zero(rates[i], set(dead)) L = np.array(live, dtype=bool) - consumed = [sp for j, sp in enumerate(species) if np.any(S[L, j] < 0)] - alive = [s for s in species if s not in dead] + consumed = {sp for j, sp in enumerate(species) if np.any(S[L, j] < 0)} + alive = [s for s in species if s not in set(dead)] + # the alive reactants of each reaction + reactants = (S[:, [col[a] for a in alive]] < 0).sum(axis=1) newdead = [] for sp in [s for s in alive if s in consumed]: - j = species.index(sp) + j = col[sp] prod = np.nonzero(S[:, j] > 0)[0] # consumed but no longer produced: zero where it is the single reactant of a consuming reaction - single = any(live[i] and S[i, j] < 0 and - all(S[i, species.index(o)] >= 0 for o in alive if o != sp) for i in range(len(rates))) - if len(prod) and not any(live[k] for k in prod) and single: + single = bool(np.any(L & (S[:, j] < 0) & (reactants == 1))) + if len(prod) and not np.any(L[prod]) and single: newdead.append(sp) if not newdead: - cl, br = _sink_cluster(S[L][:, [species.index(a) for a in alive]]) + cl, br = _sink_cluster(S[L][:, [col[a] for a in alive]]) branches = [[alive[k] for k in r] for r in br] newdead = [alive[k] for k in cl if alive[k] in consumed] newdead = [s for s in newdead if s not in dead] @@ -611,3 +648,23 @@ def equil_zero_branches(smatrix, species, rates, forcings): 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]) + + +def reduced_by_totals(odes, observables, events, totals, eliminated): + """The model on the level sets of the conserved `totals`: the species `eliminated` solved through the totals as + parameters, and an event on a species of a total changing that total, which becomes a state without dynamics. + Returns the right-hand sides, the observables (a dict or a list of dicts), the events and the solved species.""" + cq = substitute_cq(totals, dict(odes), list(odes), [], prefer=list(eliminated)) + recon = {ci["elim_state"]: ci["recon_expr"] for ci in cq["cq_info"]} + if set(recon) != set(eliminated): + raise ValueError("the conserved totals do not solve for the eliminated species " + ", ".join(eliminated)) + keys, vals = list(recon), list(recon.values()) + + 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 ([], []) + for t in moved: + f[t] = "0" + return f, obs, events, recon diff --git a/src/symident/detection/discrete.py b/src/symident/detection/discrete.py index 6b6ece3..333d66c 100644 --- a/src/symident/detection/discrete.py +++ b/src/symident/detection/discrete.py @@ -5,20 +5,29 @@ import math import os import re -import subprocess +import sys import tempfile +import time +from concurrent.futures import ThreadPoolExecutor from fractions import Fraction import numpy as np import sympy as spy +from sympy.polys.domains import QQ +from sympy.polys.rings import ring +from sympy.utilities.iterables import strongly_connected_components -from .. import session +from .. import _core, session, state from ..errors import SYMPY_FAILS, sympy_fail from ..gfp import PRIMES, rat_recon, rref_modp +from ..rexpr import get_symbols +from ..sym import msolve +from ..sym.degrees import Atoms, Deg, common from ..sym.domain import declared, is_positive from ..sym.gfpoly import _gf_roots from ..sym.modp import _modp_rational from ..sym.parse import model_sympify +from . import startpow, work # total degree past which a coefficient of a characteristic polynomial is not interpolated _DEG_CAP = 6 @@ -27,19 +36,82 @@ # orders past the fiber at which a reconstructed map is checked on the output, and raises of the order on a failure _DEEPER = 4 _RAISES = 2 -_NO_FINITE_COUNT = ("msolve found no finite count: the equations of the fiber have a component of positive dimension " - "up to order {order}, which the denominators and coordinates do not exclude, or msolve ran out " - "of time") +# the raises of the orders of the count by one past the first, where the count is not yet stable +_ORDER_RAISES = 4 +# the most terms of the equations of the fiber that a count reduces and hands to msolve +_FIBER_TERMS = 400000 +# the most unknowns of the prolonged model, coordinates and jets, that a count takes: each monomial of the sparse ring +# stores one exponent per unknown, so n unknowns take n^2 words before the first equation +_FIBER_UNKNOWNS = 10000 +# the most distinct points of a stage over Q whose rational roots are sought +_STAGE_ROOTS = 16 +# the most points over Q whose projection is counted exactly +_PROJ_POINTS = 64 +# the error bound the verified count aims at, and the least and most bits of a coordinate of the point drawn +_VERIFIED_AIM = 1e-6 +_MIN_BITS = 64 +_VERIFIED_BITS = 4096 +# the most states whose map is solved from the outputs: the solve grows with the number of states +_SOLVE_STATES = 12 + + +def _fiber_terms(): + """The most terms of the equations of the fiber: the switch FIBER_TERMS, else _FIBER_TERMS.""" + n = state.env_value("FIBER_TERMS") + return int(n) if n not in (None, "") else _FIBER_TERMS + + +# why a call of msolve gave no count, by kind, since the last reset +_FAILURES = 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"} +_NO_FINITE_COUNT = "msolve found no finite count: " + _FAILED["dimension"] + + +def _failed(r=None, kind=None): + """Records why a call of msolve gave no count: `kind`, or the kind of the failed process `r`. A process ended by + a signal ran out of the address space: msolve does not check the allocations.""" + if kind is None and getattr(r, "capped", None): + kind = "work" + if kind is None: + err = (r.stderr or "") if isinstance(r.stderr, str) else "" + kind = "memory" if r.returncode < 0 or "alloc" in err.lower() or "memory" in err.lower() else "error" + _FAILURES.add(kind) + + +def no_count_reason(order): + """The limit of a count without result, from the failures recorded since the last reset.""" + if not _FAILURES: + 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] + return f"msolve found no finite count up to order {order}: " + "; ".join(why) + + +class CapError(Exception): + """A stage reached the work cap: the points of the reconstruction of the maps, or the work of the Taylor series of + the outputs.""" -class BudgetError(Exception): - """The reconstruction of the maps ran out of its time budget.""" +# ---- 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.""" -# ---- the equations of the fiber ------------------------------------------------------------ class _Dual: - """A value with its gradient over the coordinates, modulo p.""" + """A value and the gradient over the coordinates, modulo p.""" __slots__ = ("v", "d", "p") def __init__(self, v, d, p): @@ -96,19 +168,65 @@ def __eq__(self, x): __hash__ = None -def _ser_mul(a, b, n, zero): - """The product of two power series truncated after degree n.""" - return [sum((a[i] * b[k - i] for i in range(k + 1)), zero) for k in range(n + 1)] +def _ser_mul(a, b, n, zero, limit=None): + """The product of two power series truncated after degree n. With `limit`, FiberTooLargeError where the + coefficients of the product have more terms; no partial product is formed past the limit.""" + if limit is None: + return [sum((a[i] * b[k - i] for i in range(k + 1)), zero) for k in range(n + 1)] + out, done = [], 0 + for k in range(n + 1): + acc = zero + for i in range(k + 1): + acc = _mul_add(acc, a[i], b[k - i], limit - done) + done += _terms(acc) + out.append(acc) + return out + + +def _mul_add(acc, x, y, room): + """acc + x*y with at most `room` terms, else FiberTooLargeError. A product of sparse polynomials whose term + bound exceeds the room is formed in slices of x.""" + if isinstance(acc, _Eps) or isinstance(x, _Eps) or isinstance(y, _Eps): + L = len(next(v for v in (acc, x, y) if isinstance(v, _Eps)).c) + acc, x, y = (v.c if isinstance(v, _Eps) else [v] + [v * 0] * (L - 1) for v in (acc, x, y)) + c = list(acc) + for k in range(L): + for i in range(k + 1): + c[k] = _mul_add(c[k], x[i], y[k - i], room - sum(_terms(u) for j, u in enumerate(c) if j != k)) + return _Eps(c) + if not isinstance(x, dict) or not isinstance(y, dict) or len(x) * len(y) <= room: + acc = acc + x * y + 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 + if _terms(acc) > room: + raise FiberTooLargeError(room) + if _terms(acc) > room: + raise FiberTooLargeError(room) + return acc + + +def _terms(x): + """The terms of a sparse polynomial, summed over the coefficients of a series in eps.""" + return sum(_terms(c) for c in x.c) if isinstance(x, _Eps) else len(x) if isinstance(x, dict) else 1 -def _ser_poly(P, xs, params, n, one, zero): - """A polynomial {exponents: coefficient} in states and parameters with the states replaced by the series xs.""" +def _ser_poly(P, xs, params, n, one, zero, limit=None): + """A polynomial {exponents: coefficient} in states and parameters with the states replaced by the series xs. + With `limit`, for series of sparse polynomials, FiberTooLargeError where a power, a product or the sum of the + series has more terms.""" out = [zero] * (n + 1) cache = {} + def check(ser): + if limit is not None and sum(_terms(t) for t in ser) > limit: + raise FiberTooLargeError(limit) + return ser + def power(i, e): if (i, e) not in cache: - cache[(i, e)] = xs[i] if e == 1 else _ser_mul(power(i, e - 1), xs[i], n, zero) + 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(): @@ -119,8 +237,8 @@ def power(i, e): ser = [coef] + [zero] * n for i, e in enumerate(m[:ns]): if e: - ser = _ser_mul(ser, power(i, e), n, zero) - out = [u + v for u, v in zip(out, ser)] + ser = _ser_mul(ser, power(i, e), n, zero, limit) + out = check([u + v for u, v in zip(out, ser)]) return out @@ -176,7 +294,7 @@ def _lead(x): def _at_gap(xs, dt, gap, one, zero): - """The state at the end of a gap dt * eps from its Taylor coefficients xs: sum_k xs[k] (dt eps)^k in eps.""" + """The state at the end of a gap dt * eps from the Taylor coefficients xs: sum_k xs[k] (dt eps)^k in eps.""" c = [zero] * (gap + 1) w = one for k in range(min(gap, len(xs) - 1) + 1): @@ -211,10 +329,14 @@ def _coeffs(x): return x.c if isinstance(x, _Eps) else [x] -def _flow(F, xs, params, order, one, zero, skip=()): +def _flow(F, xs, params, order, one, zero, skip=(), meter=None, weight=1): """The Taylor coefficients xs[i][k + 1] from coefficient k of D(x) x' = N(x), with D at the start nonzero; False - at a pole. `skip` holds the states whose series is known.""" + at a pole. `skip` holds the states whose series is known. Coefficient k spends (k + 1)^2 times `weight` times the + terms of F on `meter`; CapError past the cap.""" + size = sum(len(N) + len(D) for N, D in F) * weight for k in range(order): + if meter is not None and meter.spend(size * (k + 1) ** 2): + raise CapError() for i, (N, D) in enumerate(F): if i in skip: continue @@ -233,18 +355,22 @@ def _value(P, xs, params, one, zero): class Series: - """The model in prolonged form, as in SIAN: the derivatives of the states at the start of each segment are - unknowns, tied by the coefficients of D(x) x' = N(x) and E(x) y = M(x) as power series in t. + """The model in prolonged form, as in SIAN: the derivatives of the states at the start of each segment are unknowns, + tied by the coefficients of D(x) x' = N(x) and E(x) y = M(x) as power series in t. + + `parts` holds one entry per condition, the coordinates shared: {"segments": [...]}, the first segment {"f", "g", + "ic", "t", "label"}, each later one {"f", "g", "events", "t", "label"} with the events at the start time t ({"var", + "method", "value"}, values read the states before the events). Past an event every coefficient is a power series in + the formal variable eps, each gap being eps times the given gap (docs/method/conditions.rst, "Conditions and + events"). A segment whose start holds coordinates is expanded at the start of the condition, so that the series + depends on the time of the event.""" - `parts` holds one entry per condition, the coordinates shared: {"segments": [...]}, the first segment - {"f", "g", "ic", "t", "label"}, each later one {"f", "g", "events", "t", "label"} with the events at its start - time t ({"var", "method", "value"}, values read the states before the events). Past an event every - coefficient is a power series in the formal variable eps, each gap being eps times the given gap - (docs/method.rst, "Conditions and events"). A segment whose start holds coordinates is expanded at the start - of the condition, so that its series depends on the time of the event.""" + # the Taylor series of jacobian() spend on `meter`; `capped` holds the order not formed within the cap + meter = capped = None - def __init__(self, parts, coords): + def __init__(self, parts, coords, positive=True): self.coords = list(coords) + self.positive = positive cs = [spy.Symbol(c) for c in self.coords] self.cs = cs segs = [seg for part in parts for seg in part["segments"]] @@ -259,13 +385,52 @@ def __init__(self, parts, coords): rng = session.current().rng("discrete known", tuple(self.coords)) # a symbol that is neither a state nor a coordinate is known: one value in a point and in the solutions self.known = {x: spy.Integer(rng.randint(2, 9)) for x in sorted(allsyms - states - set(cs), key=str)} + # the states whose start is neither given nor a coordinate, taken at a drawn number + self.drawn_starts = [] 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.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"]] + self.input_values = None + self.raw_parts = parts self._kser, self._jac = {}, {} + # functions of the coordinates proven in the field of the outputs: equal at every point of the fiber; the + # exponent of a free power of a state at 0 is equal on the domain + self._pins, self._base_pins = [], [] + for pi, part in enumerate(self.parts): + if part.get("spow") is not None: + self._start_power(pi) + + @property + def pins(self): + return self._base_pins + [P for P in self._pins if P not in self._base_pins] + + @pins.setter + def pins(self, value): + self._pins = list(value) + + @property + def start_powers(self): + """The description of each free power of a state at 0, one per part that has one (docs/method/global.rst).""" + return [part["spow"] for part in self.parts if part.get("spow") is not None] + + def _start_power(self, pi): + part = self.parts[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']}") + sp["v"], sp["vy"] = v, vy + a = self.cs[sp["alpha_index"]] + if not is_positive(a, self.positive): + raise ValueError(f"discrete() needs the exponent {a} of a power of a state at 0 declared positive") + sp["proof"] = startpow.proof(self, pi, self.positive) + self._base_pins.append((_dict(a, self.cs), _dict(spy.Integer(1), self.cs))) def _part(self, part, rng): st = [spy.Symbol(x) for x in part["segments"][0]["f"]] @@ -282,7 +447,7 @@ def poly(text): 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 its start, or, where the start holds coordinates, at the start of the + # 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 anchor = t0 out = {"st": st, "segs": []} @@ -294,11 +459,16 @@ def poly(text): 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 - # and a variable of its own in the fiber - free = seg["ic"] is None or None in seg["ic"].values() + # and a separate variable in the fiber + jets = set(seg.get("inputs") or ()) + free = seg["ic"] is None or None in [v for k, v in seg["ic"].items() if k not in jets] X0 = {k: model_sympify(str(v)) for k, v in (seg["ic"] or {}).items() if v is not None} - s["x0"], s["free"] = [], {} + s["x0"], s["free"], s["inputs"] = [], {}, {} for i, x in enumerate(st): + if str(x) in jets: + s["inputs"][i] = spy.Integer(rng.randint(2, 9)) + s["x0"].append((None, None, None)) + continue if seg["ic"] is None or (str(x) in seg["ic"] and seg["ic"][str(x)] is None): s["free"][i] = spy.Integer(rng.randint(2, 9)) s["x0"].append((None, None, None)) @@ -306,6 +476,7 @@ def poly(text): v = spy.sympify(X0.get(str(x), x)).xreplace(self.known) if x not in cs and v == x: v = spy.Integer(rng.randint(2, 9)) + self.drawn_starts.append(x) num, den = spy.fraction(spy.cancel(v)) s["x0"].append((v, _dict(num, cs), _dict(den, cs))) # a copy switched into a regime starts on the surface it crosses: q(z, theta) = 0, solved at the point @@ -352,6 +523,49 @@ def drop(m, i=i): s["off"] = _dict(spy.expand(tj - at), cs) if tj.free_symbols else None anchor = at out["segs"].append(s) + if part.get("spow") is not None: + out["spow"] = self._spow_part(part, out) + return out + + def _spow_part(self, part, out): + """The free power of a state at 0 of a part as indices: the state N of the normalized power, the base and + the coordinate of the exponent.""" + sp = dict(part["spow"]) + names = [str(x) for x in out["st"]] + if len(out["segs"]) > 1: + raise ValueError("discrete() handles a free power of a state at 0 without events") + sp["N"], sp["base"] = names.index(sp["N"]), names.index(sp["state"]) + a = spy.Symbol(sp["alpha"]) + if a not in self.params: + raise ValueError(f"discrete() needs the exponent {a} of a power of a state at 0 as a coordinate") + if out["segs"][0]["x0"][sp["base"]][0] != 0: + raise ValueError(f"discrete(): {sp['state']} does not start at 0") + sp["alpha_index"] = self.cs.index(a) + out["known"] = out["known"] - {sp["N"]} + return sp + + def _spow_jets(self, pi, order, kser): + """{key: name} of the jets of a part with a free power of a state at 0: per state, index n and layer m >= 1 + those with n - k*m at least the valuation of the state, and the coefficients of Q likewise.""" + part = self.parts[pi] + sp, seg = part["spow"], part["segs"][0] + k, L, need = sp["k"], order // sp["k"] + 1, sp["need"] + out = {} + for i in range(len(part["st"])): + if i in kser or i == sp["N"]: + continue + v = seg["x0"][i][0] + lo = 0 if v is None or (not (v.is_Symbol and v in self.cs) and not v.is_number) else 1 + for n in range(lo, need[i] + 1): + for m in range(L): + if m == 0 or (sp["v"][i] is not None and n >= 1 and n - k * m >= sp["v"][i]): + out[(pi, 0, i, n, m)] = f"si_j{pi}_0_{i}_{n}_{m}" + # a term of Q of layer m >= 1 holds a term of the base of layer m or less over t^k + w = None if sp["v"][sp["base"]] is None else sp["v"][sp["base"]] - k + for q in range(1, need[sp["N"]] - k + 1): + for m in range(L): + if m == 0 or (w is not None and q - k * m >= w): + out[("q", pi, q, m)] = f"si_q{pi}_{q}_{m}" return out def _known_series(self, pi, order): @@ -378,10 +592,10 @@ def start(v): self._kser[key] = {i: xs[i] for i in known} return self._kser[key] - def _outputs(self, cvals, order, gap, one, zero): - """Per observable of each segment of each condition, the Taylor coefficients up to `order`, each as its + def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): + """Per observable of each segment of each condition, the Taylor coefficients up to `order`, each as the coefficients in eps up to `gap` (one for the first segment), the coordinates at `cvals` in the arithmetic - of one and zero; None at a pole.""" + of one and zero; None at a pole, CapError past the cap of `meter` (_flow()).""" val = dict(zip(self.cs, cvals)) params = [val[s] for s in self.params] out = [] @@ -399,6 +613,11 @@ def _outputs(self, cvals, order, gap, one, zero): v = seg["free"][i] xs.append([one * Fraction(int(v.p), int(v.q))] + [zero] * order) 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) + continue d = _eval(den, cvals, zero) if d == 0: return None @@ -411,7 +630,16 @@ def _outputs(self, cvals, order, gap, one, zero): return None xs[i][0] = -_value(B, start, params, one, zero) / a o, z = one, zero + sp = part.get("spow") + if sp is not None: + # 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"]]]): + return None else: + sp = None o, z = _Eps([one] + [zero] * gap), _Eps([zero] * (gap + 1)) dt = _eval(seg["dt"], cvals, zero) pre = [_at_gap(x, dt, gap, one, zero) for x in xs] @@ -426,14 +654,18 @@ def _outputs(self, cvals, order, gap, one, zero): # the series at the event, one coefficient in eps longer per order, then at the anchor n = order + gap xs = [[w] + [z] * n for w in w0] - if not _flow(seg["F"], xs, params, n, o, z): + if not _flow(seg["F"], xs, params, n, o, z, meter=meter, weight=weight): return None off = _eval(seg["off"], cvals, zero) xs = [_shift(x, -off, order, gap, one, zero) for x in xs] else: xs = [[w] + [z] * order for w in w0] - if (j == 0 or seg["off"] is None) and not _flow(seg["F"], xs, params, order, o, z, kser): + 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 + self.states0 = xs for M, E in seg["G"]: mser = _ser_poly(M, xs, params, order, o, z) eser = _ser_poly(E, xs, params, order, o, z) @@ -457,37 +689,115 @@ def numeric(self, point, order, gap=0, p=0): return None return None if out is None else [[[x.v for x in ym] for ym in y] for y in out] - def output_orders(self, cap, p, gap=0): + def output_orders(self, cap, p, gap=0, seed=()): """Per observable the least order whose next Taylor coefficient adds no rank to the Jacobian in the coordinates, as in SIAN, at a random point modulo p; None where the rank stays below the number of - coordinates up to `cap`.""" + coordinates up to `cap`. The gradients `seed` enter the basis first.""" # the coefficients up to an order depend on none above it: the series grows by doubling up to `cap` n = min(cap, 8) while True: - out = self._output_orders(n, p, gap) + out = self._output_orders(n, p, gap, seed) if out != "short" or n >= cap: return None if out == "short" else out n = min(cap, 2 * n) def jacobian(self, order, p, gap=0): """The output coefficients up to `order` at the random point of output_orders modulo p, as duals with the - gradient over the coordinates; None at a pole.""" + gradient over the coordinates; None at a pole, or where the series reaches the cap of `meter`, which + `capped` then records.""" 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]] - rng = session.current().rng("discrete orders", tuple(self.coords)) m = len(self.cs) - cv = [_Dual(rng.randint(2, p - 1), [int(i == j) for j in range(m)], p) for i in range(m)] + cv = self._jac_point(p) one, zero = _Dual(1, [0] * m, p), _Dual(0, [0] * m, p) try: - ys = self._outputs(cv, order, gap, one, zero) + ys = self._outputs(cv, order, gap, one, zero, self.meter, m + 1) except ZeroDivisionError: ys = None + except CapError: + # the series past the cap: no rows at this order, and none cached + self.capped = order + return None self._jac[key] = (order, ys) return ys - def _output_orders(self, cap, p, gap): + def _jac_point(self, p): + """The random point of jacobian() modulo p, each coordinate a dual with a unit gradient.""" + rng = session.current().rng("discrete orders", tuple(self.coords)) + m = len(self.cs) + return [_Dual(rng.randint(2, p - 1), [int(i == j) for j in range(m)], p) for i in range(m)] + + def pin_values(self, p): + """The pins num/den at the random point of jacobian() modulo p, as duals with the gradient over the + coordinates; None at a pole.""" + cv = self._jac_point(p) + zero = _Dual(0, [0] * len(self.cs), p) + out = [] + for num, den in self.pins: + d = _eval(den, cv, zero) + if not d.v: + return None + out.append(_eval(num, cv, zero) / d) + return out + + def rank_rows(self, cap, p, skip=(), pins=False): + """(observable, order) of the Taylor coefficients whose gradients in the coordinates are independent at the + random point of output_orders modulo the columns `skip`, as many as the other coordinates, lowest order first; + None where fewer exist up to `cap`. With `pins`, the gradients of the pins come first, each row of a pin + ("pin", i).""" + # the rows up to an order are the first rows up to any higher one: the series grows by doubling up to `cap` + n = min(cap, 8) + while True: + out = self._rank_rows(n, p, skip, pins) + if out is not None or n >= cap or self.jacobian(n, p, 0) is None: + return out + n = min(cap, 2 * n) + + def _rank_rows(self, cap, p, skip, pins): + ys = self.jacobian(cap, p, 0) + if ys is None: + return None + m = len(self.cs) + basis = [[int(i == c) for i in range(m)] for c in skip] + piv, out = list(skip), [] + if len(piv) == m: + return out + rows = [] + if pins: + pv = self.pin_values(p) + if pv is None: + return None + # 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])] + for key, row in rows: + for b, c in zip(basis, piv): + if row[c]: + f = row[c] + row = [(x - f * y) % p for x, y in zip(row, b)] + c = next((i for i, x in enumerate(row) if x), None) + if c is None: + continue + inv = pow(row[c], -1, p) + basis.append([x * inv % p for x in row]) + piv.append(c) + out.append(key) + if len(out) + len(skip) == m: + return out + return None + + def pinned_orders(self, cap, p): + """Per observable the least order at which the gradients of the pins and of the Taylor coefficients up to the + orders reach the number of coordinates, as output_orders() with the pins in the basis first; None where they do + not up to `cap` or a pin has a pole at the point.""" + pv = self.pin_values(p) + return None if pv is None else self.output_orders(cap, p, 0, [v.d for v in pv]) + + def _output_orders(self, cap, p, gap, seed=()): m = len(self.cs) ys = self.jacobian(cap, p, gap) if ys is None: @@ -507,6 +817,8 @@ 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) active = list(range(len(ys))) for k in range(cap + 1): @@ -523,6 +835,8 @@ def adds(row): # last order that adds rank, until the rank is full basis.clear() piv.clear() + for row in seed: + adds(row) orders = [0] * len(ys) for k in range(cap + 1): for j in range(len(ys)): @@ -532,18 +846,20 @@ def adds(row): return orders return "short" - def prolonged(self, orders, gap=0): - """(names, equations, outputs, sat) up to the order of each observable in `orders` and `gap`: the jet - variables after the coordinates, the equations of the model, the starts and the events as {exponents: - Fraction} over coordinates and jets, the series (E, M) of each observable as E[l][a] and M[k][m] (Taylor - coefficient, then coefficient in eps), and the factors that must not vanish.""" - order = max(orders) - from sympy.polys.domains import QQ - from sympy.polys.rings import ring - names = [str(c) for c in self.cs] + def _jet_names(self, orders, order, gap): + """{key: name} of the jet variables of the prolonged model; sets the orders `need` of a free power of a state + at 0.""" jets = {} for pi, part in enumerate(self.parts): kser = self._known_series(pi, order) + sp = part.get("spow") + 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"]) + jets.update(self._spow_jets(pi, order, kser)) + continue for j, seg in enumerate(part["segs"]): for i in range(len(part["st"])): if j == 0: @@ -554,13 +870,31 @@ def prolonged(self, orders, gap=0): for k in range(lo, order + 1): jets[(pi, j, i, k, 0)] = f"si_j{pi}_{j}_{i}_{k}" else: - # the start after an event is a jet of its own where the event divides by the states, and + # the start after an event is a separate jet where the event divides by the states, and # at an anchor before the event ev = seg["event"].get(i) lo = 0 if seg["off"] is not None or (ev is not None and any(any(m) for m in ev[1])) else 1 for k in range(lo, order + 1): for m in range(gap + 1): jets[(pi, j, i, k, m)] = f"si_j{pi}_{j}_{i}_{k}_{m}" + return jets + + def prolonged(self, orders, gap=0): + """(names, equations, outputs, sat) up to the order of each observable in `orders` and `gap`: the jet + variables after the coordinates, the equations of the model, the starts and the events as {exponents: + Fraction} over coordinates and jets, the series (E, M) of each observable as E[l][a] and M[k][m] (Taylor + coefficient, then coefficient in eps), and the factors that must not vanish.""" + order = max(orders) + names = [str(c) for c in self.cs] + jets = self._jet_names(orders, order, gap) + # the jets of unknown inputs above those the outputs read at these orders start at zero + 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: + raise FiberTooLargeError(len(names) + len(jets), "unknowns") R, *gens = ring(",".join(names + list(jets.values())), QQ) g = dict(zip(names + list(jets.values()), gens)) cof = {str(c): g[str(c)] for c in self.cs} @@ -572,8 +906,15 @@ def in_ring(P): eqs, outs = [], [] sat = [cof[str(c)] for c in self.cs] + size = [0] + def add_eq(e): - eqs.extend(_coeffs(e)) + cs = _coeffs(e) + eqs.extend(cs) + # the equations past the limit of a count are not built further + size[0] += sum(_terms(c) for c in cs) + if size[0] > _fiber_terms(): + raise FiberTooLargeError(size[0]) def add_sat(e): e = _lead(e) @@ -583,6 +924,7 @@ def add_sat(e): for pi, part in enumerate(self.parts): kser = self._known_series(pi, order) xs = None + sp = part.get("spow") for j, seg in enumerate(part["segs"]): if j == 0: xs = [] @@ -591,7 +933,12 @@ def add_sat(e): if i in kser: xs.append([R(spy.Rational(c.numerator, c.denominator)) for c in kser[i]]) continue - if v is None: + if sp is not None and i == sp["N"]: + xs.append(None) + continue + if (pi, i) in zero_in: + a0 = R.zero + elif v is None: # a free start: a variable without an equation a0 = g[jets[(pi, 0, i, 0, 0)]] elif (pi, 0, i, 0, 0) in jets: @@ -602,6 +949,9 @@ def add_sat(e): a0 = R(spy.Rational(v)) else: a0 = cof[str(v)] + if sp is not None: + xs.append([a0] + [None] * order) + continue xs.append([a0] + [g[jets[(pi, 0, i, k, 0)]] for k in range(1, order + 1)]) if seg["on"] is not None: N, D = seg["on"][3:] @@ -635,19 +985,37 @@ def jet(k, i=i): elif seg["off"] is not None: add_eq(at - pre[i]) xs.append([w0] + ws) + if sp is not None: + # the layers of each index: jets where a term can be other than 0 + L = order // sp["k"] + 1 + o, z = _Eps([R.one] + [R.zero] * (L - 1)), _Eps([R.zero] * L) + + 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) + elif i in kser: + xs[i] = [o * c for c in xs[i]] + 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()) for i, (N, D) in enumerate(seg["F"]): - if j == 0 and i in kser: + if (j == 0 and i in kser) or sp is not None: continue - nser = _ser_poly(N, xs, params, order - 1, o, z) if order else [] - dser = _ser_poly(D, xs, params, order - 1, o, z) if order else [] + nser = _ser_poly(N, xs, params, order - 1, o, z, _fiber_terms()) if order else [] + dser = _ser_poly(D, xs, params, order - 1, o, z, _fiber_terms()) if order else [] for k in range(order): add_eq(sum((dser[l] * (k + 1 - l) * xs[i][k + 1 - l] for l in range(0, k + 1)), z) - nser[k]) - add_sat(_ser_poly(D, xs, params, 0, o, z)[0]) + add_sat(_ser_poly(D, xs, params, 0, o, z, _fiber_terms())[0]) for M, E in seg["G"]: n = orders[row] row += 1 - mser = _ser_poly(M, xs, params, n, o, z) - eser = _ser_poly(E, xs, params, n, o, z) + 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])) @@ -655,12 +1023,26 @@ def jet(k, i=i): def _dict(e, syms): - """A polynomial in `syms` as {exponents: Fraction}.""" - P = spy.Poly(spy.expand(e), *syms) - return {m: Fraction(int(spy.Rational(c).p), int(spy.Rational(c).q)) for m, c in P.terms()} + """A polynomial in `syms` as {exponents: Fraction}, in the sparse ring: the dense form recurses once per + symbol, past the recursion limit with the jets of known inputs.""" + if not syms: + c = spy.Rational(spy.expand(e)) + return {(): Fraction(int(c.p), int(c.q))} if c else {} + return _rdict(_sparse_ring(tuple(syms)).from_expr(e)) + + +_RINGS = {} + + +def _sparse_ring(syms): + """The sparse polynomial ring over Q in `syms`, cached.""" + if syms not in _RINGS: + _RINGS[syms] = spy.polys.rings.ring(syms, spy.QQ)[0] + return _RINGS[syms] def _rdict(P): + """A ring element as {exponents: Fraction}.""" return {m: Fraction(int(c.numerator), int(c.denominator)) for m, c in P.terms()} @@ -676,19 +1058,29 @@ def _clear(P, p=0): class Fiber: """The points of the prolonged model whose observables have the Taylor coefficients of a given point.""" - def __init__(self, series, orders, positive=True, gap=0): + def __init__(self, series, orders, positive=True, gap=0, proj=None): self.series = series self.coords = list(series.coords) self.syms = [spy.Symbol(c) for c in self.coords] + # the count modulo p is that of the distinct values of the first `proj` coordinates (all by default) + self.proj = len(self.coords) if proj is None else int(proj) # one order per observable of each segment; a number is the same order for all self.orders = [int(orders)] * len(series.labels) if isinstance(orders, int) else [int(n) for n in orders] self.order = max(self.orders) - # the coefficients in eps after an event; the state at the end of a gap needs its jets up to `gap` + # the coefficients in eps after an event; the state at the end of a gap needs the jets up to `gap` self.gap = min(int(gap), self.order) if series.has_events else 0 self.positive = positive self.known = series.known self.names = [f"x{i}" for i in range(len(self.syms))] - jets, static, outs, sat = series.prolonged(self.orders, self.gap) + try: + 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.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] @@ -701,17 +1093,39 @@ def __init__(self, series, orders, positive=True, gap=0): # per characteristic, whether msolve gets the separating form (decided at the first call) self.sep_mode = {} + def pin_polys(self, point, p=0): + """num(x) den(point) - den(x) num(point) per pin num/den of the series, in the sparse form of the system.""" + out = [] + for num, den in self.series.pins: + x = [Fraction(str(point[s])) for s in self.syms] + a, b = _eval(num, x), _eval(den, x) + if p and (a.denominator % p == 0 or b.denominator % p == 0): + continue + P = {} + for mm, c in num.items(): + P[mm] = P.get(mm, 0) + c * b + for mm, c in den.items(): + P[mm] = P.get(mm, 0) - c * a + P = {mm: Fraction(c) for mm, c in P.items() if c} + out.append(_sparse(P)) + return out + def values(self, point, p=0): """The Taylor coefficients of the observables at `point` ({symbol: Rational}), modulo p with p, None at a pole.""" return self.series.numeric(point, self.order, self.gap, p) - def system(self, point, p=0): + def system(self, point, p=0, eliminate=False, extra=()): """{"blocks", "fixed"}: the msolve input of the points with the coefficients of `point`, over Q (p = 0) or GF(p). The variables that a linear equation in one of them fixes to a number are substituted, `fixed` - holds the coordinates among those. The rest splits into blocks without a shared variable in an equation - or a factor of the saturation, each {"names", "sep", "eqs"} with `sep` its coordinates; the fiber is the - product of the fibers of the blocks. None where the point has a pole or the system has no solution.""" + holds the coordinates among those; the sparse polynomials `extra` join the equations. With `eliminate`, for + a count only, so are the variables that an + equation a*v + b*m sets to a monomial m (_monomial_eliminate()). The rest splits into blocks without a + shared variable in an equation or a factor of the saturation, each {"names", "sep", "eqs"} with `sep` the + coordinates of the block; the fiber is the product of the fibers of the blocks. None where the point has a + pole or the system has no solution.""" + if getattr(self, "too_large", None): + raise FiberTooLargeError(self.too_large) vals = self.values(point, p) if vals is None: return None @@ -726,13 +1140,32 @@ def system(self, point, p=0): for mm, c in E[l][a].items(): P[mm] = P.get(mm, 0) + c * b[k - l][m - a] polys.append(_clear({mm: c for mm, c in P.items() if c}, p)) + polys += [_clear(P, p) for P in self.pin_polys(point, p)] + [dict(P) for P in extra] polys = [P for P in polys if P] + terms = sum(len(P) for P in polys) + if eliminate and terms > _fiber_terms(): + self.too_large = max(terms, getattr(self, "too_large", 0)) + raise FiberTooLargeError(terms) sat = [{m: c % p if p else c for m, c in f.items()} for f in self.sat] red = _reduce(polys, sat, len(self.allnames), len(self.names), p) if red is None: return None polys, sat, fixed, gone = red + if eliminate: + # a coordinate outside the projection may leave for any monomial, as a jet does + polys, sat, elim = _monomial_eliminate(polys, sat, getattr(self, "proj", len(self.names)), p) + if any(list(P) == [()] for P in polys) or any(not f for f in sat): + return None + if elim: + red = _reduce(polys, sat, len(self.allnames), len(self.names), p) + if red is None: + return None + polys, sat, fixed2, gone2 = red + fixed, gone = {**fixed, **fixed2}, gone | gone2 | elim keep = [i for i in range(len(self.allnames)) if i not in fixed and i not in gone] + # an unknown that is no coordinate and in no equation is free and leaves the count of the coordinates + used = {v for P in polys + sat for mm in P for v, _ in mm} + keep = [i for i in keep if i < len(self.names) or i in used] # blocks: the components of the variables joined by an equation or a factor of the saturation parent = {i: i for i in keep} @@ -752,18 +1185,73 @@ def find(i): blocks = [] for idx in comp.values(): loc = set(idx) - names = [self.allnames[i] for i in idx] - eqs = [_ms_sparse(_clear(P, p), self.allnames) for P in polys if {v for mm in P for v, _ in mm} & loc] - fac = {(): 1} - for f in sat: - if {v for mm in f for v, _ in mm} & loc: - fac = _smul(fac, _clear(f, p), p) - # points where a coordinate or a denominator at the start vanishes do not count; msolve reads no - # brackets, so si_w multiplies each term - eqs.append(_ms_sparse(fac, self.allnames, "si_w") + "-1") - blocks.append({"names": names, "sep": [self.names[i] for i in idx if i < m], "eqs": eqs}) + bp = [P for P in polys if {v for mm in P for v, _ in mm} & loc] + bs = [f for f in sat if {v for mm in f for v, _ in mm} & loc] + block = self._ms_block(idx, bp, bs, p) + block.update({"idx": list(idx), "polys": bp, "sat": bs}) + blocks.append(block) return {"blocks": blocks, "fixed": {self.names[i]: v for i, v in fixed.items() if i < m}} + def _ms_block(self, idx, polys, sat, p): + """{"names", "sep", "eqs"}: the msolve input of the sparse equations `polys` in the variables `idx`, with the + product of the factors `sat` inverted by si_w.""" + m = len(self.names) + eqs = [_ms_sparse(_clear(P, p), self.allnames) for P in polys] + fac = {(): 1} + for f in sat: + fac = _smul(fac, _clear(f, p), p) + # points where a coordinate or a denominator at the start vanishes do not count; msolve reads no + # 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} + + +def _monomial_eliminate(polys, sat, m, p=0): + """(polys, sat, gone): the sparse system after substituting v = -b/a m for each equation a*v + b*m with a + monomial m free of v, in turn, over Q (p = 0) or GF(p). A coordinate (index below `m`) leaves only for a + monomial in coordinates: the coordinates of a point then fix the eliminated one, and distinct points stay + distinct in the coordinates left. The substitution maps monomials to monomials, so no equation grows.""" + polys, sat, gone = [dict(P) for P in polys], [dict(f) for f in sat], set() + + def div(a, b): + return a * pow(b, -1, p) % p if p else Fraction(a) / b + + def subst(P, v, c, mono): + out = {} + for mm, k in P.items(): + e = dict(mm).get(v) + if e: + k = k * pow(c, e, p) % p if p else k * Fraction(c) ** e + d = {w: f for w, f in mm if w != v} + for w, f in mono: + d[w] = d.get(w, 0) + e * f + mm = tuple(sorted(d.items())) + out[mm] = (out.get(mm, 0) + k) % p if p else out.get(mm, 0) + k + return {mm: k for mm, k in out.items() if k} + + def target(P): + if len(P) != 2: + return None + for (mv, a), (mo, b) in (tuple(P.items()), tuple(P.items())[::-1]): + if len(mv) == 1 and mv[0][1] == 1: + v = mv[0][0] + 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: + break + v, c, mono = hit + gone.add(v) + polys = [Q for Q in (subst(P, v, c, mono) for P in polys) if Q] + sat = [subst(f, v, c, mono) for f in sat] + polys = [_clear(P, p) if not p else P for P in polys] + sat = [_clear(f, p) if not p else f for f in sat] + return polys, sat, gone + def _sparse(P): """A polynomial {exponents: coefficient} with each monomial as (variable, exponent) pairs.""" @@ -829,7 +1317,6 @@ def _decode(d): def _reduce_mod(polys, sat, nv, m0, p): - from .. import _core out = _core.sym_fiber_reduce(_encode(polys), _encode(sat), nv, m0, float(p)) if not out["ok"]: return None @@ -942,11 +1429,11 @@ 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) -def _msolve(names, p, eqs, flags, timeout, sep=()): - """The parsed output of msolve on `eqs` in `names` + si_w over GF(p) (p = 0: Q), or None on failure. With - `sep`, a last variable si_t is a linear form in these names with fixed coefficients: it separates distinct - points, where si_w need not, so msolve parametrizes by it without trying other forms.""" - from ..sym import msolve +def _msolve(names, p, eqs, flags, sep=()): + """The parsed output of msolve on `eqs` in `names` + si_w over GF(p) (p = 0: Q), or None on failure or a system + past the caps of work.msolve_too_large(). With `sep`, a last variable si_t is a linear form in these names with + fixed coefficients: it separates distinct points, where si_w need not, so msolve parametrizes by it without + trying other forms.""" flags = list(flags) + ["-t", str(msolve._MSOLVE_THREADS)] if p: # the probabilistic sparse linear algebra of msolve over GF(p): the counts are at random points anyway @@ -956,41 +1443,54 @@ def _msolve(names, p, eqs, flags, timeout, sep=()): if sep: eqs.append("si_t" + "".join(f"-{3 + 2 * i}*{n}" for i, n in enumerate(sep))) names.append("si_t") + if work.msolve_too_large(names, eqs): + _failed(kind="size") + return None 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: fh.write(",".join(names) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") - try: - r = subprocess.run([msolve._msolve_binary(), "-f", fi, "-o", fo] + flags, capture_output=True, text=True, - timeout=timeout) - except subprocess.TimeoutExpired: - return None + r = work.run_msolve([msolve._msolve_binary(), "-f", fi, "-o", fo] + flags) txt = "" if os.path.exists(fo): with open(fo) as fh: txt = fh.read() if r.returncode != 0 or not txt.strip(): + _failed(r) return None txt = txt.strip().rstrip(":") - if p == 0: - # dyadic interval ends a / 2^k as exact fractions - txt = re.sub(r"(-?\d+)\s*/\s*2\^(\d+)", r"Fraction(\1, 2**\2)", txt) + out = parse_rational(txt) if p == 0 else ast.literal_eval(txt) + if out and out[0] == 1: + _failed(kind="dimension") + return out + + +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] + if len(roots) != sq.degree(): + return None + + def ev(coeffs, x): + acc = Fraction(0) + 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)) + dv = ev(par[1][1][1], t) + if dv == 0: + return None + vals = {vnames[j]: -ev(q[0][1], t) / (int(q[1]) * dv) for j, q in enumerate(par[1][2])} + last = len(vnames) - 1 + vals[vnames[last]] = (t - sum(int(lin[j]) * vals[vnames[j]] for j in range(last))) / int(lin[last]) + out.append({at[n]: v for n, v in vals.items() if n in at}) + return out + + +def _staged_count(fib, idx, polys, sat, p): + """The count of a block modulo p (p = 0: over Q), as _block_count(), stage by stage: the points of a closed + stage (_first_stage()) are found, each substituted into the other equations, and the counts of the rest add up + over the points. The block is first counted at once within an eighth of the cap msolve_entries of + work.CAPS; without a stage, or where a stage fails, it is counted at once within the whole cap.""" + m = len(fib.names) + A = _first_stage(polys, idx) + cap = work.cap("msolve_entries") + if A is not None: + # the block at once first: what is left after a stage is often small + with work.local_caps(msolve_entries=cap / 8): + k = _block_count(fib, idx, polys, sat, p) + if k is not None: + return k + inA = [P for P in polys if _vars(P) <= A] + satA = [f for f in sat if _vars(f) <= A] + # over Q a stage first runs modulo a prime: rational points reduce to points in GF(p), so where the stage + # has a point outside GF(p), the stage over Q is skipped + if not p: + with work.local_caps(msolve_entries=cap / 16): + if _stage_points(fib, A, inA, satA, PRIMES[0]) is None: + A = None + if A is not None: + pts = _stage_points(fib, A, inA, satA, p) + if A is None or pts is None: + return _block_count(fib, idx, polys, sat, p) + rest = [P for P in polys if not _vars(P) <= A] + srest = [f for f in sat if not _vars(f) <= A] + others = [i for i in idx if i not in A] + total = 0 + for pt in pts: + lin = [{((v, 1),): 1, (): (-x) % p if p else -x} for v, x in pt.items()] + red = _reduce(lin + rest, srest, len(fib.allnames), m, p) + if red is None: + continue + rp, rs, fixed, gone = red + keep = [i for i in others if i not in fixed and i not in gone] + if not keep: + total += 1 + continue + used = set().union(*[_vars(P) for P in rp]) if rp else set() + if set(keep) - used: + # a variable left without an equation: no finite count + 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) + if k is None: + return None + n *= k + total += n + return total + + +def _block_count(fib, idx, polys, sat, p): + """The count of a block at once: _gb_count() modulo p, over Q (p = 0) the degree of the rational + parametrization of msolve, at least the number of distinct points.""" + b = fib._ms_block(idx, polys, sat, p) + if p: + return _gb_count(b["names"], p, b["eqs"], b["proj"]) + data = _solve(fib, 0, b, ["-P", "1"]) + if data is None or data[0] not in (0, -1): + return None + 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: + # 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 + return deg + + +def _projected_count(data, proj): + """The number of distinct values of the variables `proj` on the points of a rational parametrization of msolve + over Q: the dimension of the subalgebra they generate in Q[t]/(w), w the square-free eliminating polynomial, an + algebra of the functions on the points. None where the parametrization has another form.""" + _, _, deg, vnames, lin, par = data[1] + if deg <= 0 or par[0] != 1: + return None + if not proj: + return 1 + T = spy.Symbol("t") + + 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: + dinv = poly(par[1][1][1]).invert(w) + except (spy.polys.polyerrors.NotInvertible, ZeroDivisionError): + return None + vals = {vnames[j]: (-poly(q[0][1]) * dinv * spy.Rational(1, int(q[1]))).rem(w) for j, q in enumerate(par[1][2])} + last = len(vnames) - 1 + if vnames[last] in proj: + rest = spy.Poly(T, T, domain="QQ") + for j in range(last): + rest = rest - vals[vnames[j]] * int(lin[j]) + vals[vnames[last]] = (rest * spy.Rational(1, int(lin[last]))).rem(w) + gens = [vals[v] for v in proj if v in vals] + + 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 = {} + + def add(P): + v = vec(P) + for piv, r in rows.items(): + if v[piv]: + f = v[piv] + v = [a - f * b for a, b in zip(v, r)] + piv = next((i for i, a in enumerate(v) if a), None) + if piv is None: + return False + v = [a / v[piv] for a in v] + for q, r in rows.items(): + if r[piv]: + f = r[piv] + 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 + while k < len(basis): + for g in gens: + P = (basis[k] * g).rem(w) + if add(P): + basis.append(P) + k += 1 + return len(basis) + + +def _components(keep, polys, sat): + """The variables `keep` split into the parts that no equation or factor joins.""" + parent = {i: i for i in keep} + + def find(i): + while parent[i] != 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:]): + parent[find(a)] = find(b) + out = {} + for i in keep: + out.setdefault(find(i), []).append(i) + return list(out.values()) + + +def _gb_count(names, p, eqs, sep=(), cap=5000, exact=False, dims=None): """The number of points of the ideal of `eqs` in `names` + si_w over the algebraic closure of GF(p) with distinct values of the coordinates `sep`; None where it is not finite, the quotient above `cap`, or on failure. From the reduced Gröbner basis of msolve: the standard monomials span the quotient, the multiplication by a random linear form in `sep` acts on it, and the distinct eigenvalues of that matrix are the distinct values of - the form on the points. A block without coordinates counts one point where it has any.""" - from ..sym import msolve + the form on the points. A block without coordinates counts one point where it has any. With `exact`, msolve + uses exact linear algebra, and `dims` receives the dimension of the quotient.""" names = list(names) + ["si_w"] + if work.msolve_too_large(names, eqs): + _failed(kind="size") + return None 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: fh.write(",".join(names) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") - try: - r = subprocess.run([msolve._msolve_binary(), "-f", fi, "-o", fo, "-g", "2", "-l", "44", - "-t", str(msolve._MSOLVE_THREADS)], capture_output=True, text=True, timeout=timeout) - except subprocess.TimeoutExpired: - return None + 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: txt = fh.read() if r.returncode != 0: + _failed(r) return None at = {n: i for i, n in enumerate(names)} body = "".join(line for line in txt.splitlines() if not line.startswith("#")).strip().rstrip(":").strip("[]") @@ -1095,7 +1899,11 @@ def _gb_count(names, p, eqs, timeout, sep=(), cap=5000): 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") return None + if dims is not None: + dims.append(len(basis)) if not any(n in at for n in sep): return 1 if basis else 0 rng = session.current().rng("discrete form", tuple(names)) @@ -1210,9 +2018,9 @@ def trim(x): return [x * inv % p for x in a] -def _standard_monomials(lead, nv, cap): +def _standard_monomials(lead, nv, cap, finite=False): """The monomials in nv variables that no monomial of `lead` ({variable: exponent}) divides, sparse; None where - there are infinitely many or more than `cap`.""" + there are infinitely many or more than `cap`. With `finite`, [] where there are finitely many.""" pure = {} for e in lead: if len(e) == 1: @@ -1220,6 +2028,8 @@ def _standard_monomials(lead, nv, cap): pure[v] = min(pure.get(v, k), k) if len(pure) < nv: return None + if finite: + return [] free = [v for v in range(nv) if pure[v] > 1] lead = [e for e in lead if all(v in free for v in e)] seen, todo = {()}, [()] @@ -1241,7 +2051,7 @@ def _standard_monomials(lead, nv, cap): def _boxes_of_maps(fib, pt, maps, check=True): - """The points of the fiber at `pt` as exact boxes, the point and its images under `maps`, or None where an image + """The points of the fiber at `pt` as exact boxes, the point and the images under `maps`, or None where an image is not distinct or, with `check`, the coefficients there differ from those at the point.""" try: imgs = [dict(pt)] + [{s: spy.Rational(sig.get(s, s).xreplace(pt)) for s in fib.syms} for sig in maps] @@ -1268,7 +2078,7 @@ def domain_point(fib, rng): # ---- the rational univariate representation over GF(p) ------------------------------------- -def _rur(fib, point, p, timeout): +def _rur(fib, point, p): """{"deg", "elim", "den", "par", "lin", "vnames"} of the fiber of `point` (integers mod p), None on failure.""" try: pt = {s: spy.Integer(_modp_rational(spy.Rational(v), p)) for s, v in point.items()} @@ -1276,13 +2086,13 @@ def _rur(fib, point, p, timeout): return None try: sysd = fib.system(pt, p) - except ZeroDivisionError: + except (ZeroDivisionError, FiberTooLargeError): return None if sysd is None: return None blocks = [] for block in sysd["blocks"]: - data = _solve(fib, p, block, ["-P", "1"], timeout) + data = _solve(fib, p, block, ["-P", "1"]) if data is None or data[0] != 0: return None _, _, deg, vnames, lin, par = data[1] @@ -1313,13 +2123,19 @@ def _pmod(a, f, p): return a + [0] * (n - len(a)) -def _pmul(a, b, f, p): +def _plain_mul(a, b, p): + """The product of two polynomials over GF(p), lowest degree first.""" out = [0] * (len(a) + len(b) - 1) for i, x in enumerate(a): if x: for j, y in enumerate(b): out[i + j] = (out[i + j] + x * y) % p - return _pmod(out, f, p) + return out + + +def _pmul(a, b, f, p): + """a * b mod f over GF(p), lowest degree first.""" + return _pmod(_plain_mul(a, b, p), f, p) def _pinv(a, f, p): @@ -1344,7 +2160,7 @@ def _pinv(a, f, p): def charpolys(rur, p, names=None): """{variable: coefficients c_0..c_{K-1} of the monic characteristic polynomial} over the fiber, the product of - the fibers of the blocks: a variable of a block of k points has its polynomial over the block to the power + the fibers of the blocks: a variable of a block of k points has the polynomial over the block to the power K/k; a fixed coordinate c has (Z - c)^K. None on failure.""" K = rur["deg"] out = {} @@ -1363,14 +2179,6 @@ def charpolys(rur, p, names=None): return out -def _plain_mul(a, b, p): - out = [0] * (len(a) + len(b) - 1) - for i, x in enumerate(a): - for j, y in enumerate(b): - out[i + j] = (out[i + j] + x * y) % p - return out - - def _charpolys_block(rur, p, names=None): """{variable: coefficients c_0..c_{k-1} of the monic characteristic polynomial} over the points of a block.""" f, k = rur["elim"], rur["deg"] @@ -1456,13 +2264,13 @@ def ev(coeffs, x): class _Sampler: """Characteristic polynomials of the fiber at integer points, memoized per point and prime.""" - def __init__(self, fib, timeout, budget=math.inf): - import time - self.fib, self.timeout, self.memo = fib, timeout, {} - self.deadline = time.monotonic() + budget + def __init__(self, fib, meter=None): + self.fib, self.memo = fib, {} + self.meter = meter or work.unlimited() self.rng = session.current().rng("discrete points", tuple(fib.coords)) self.k = None self.pool, self.moved = [], {} + self.checks = None def point(self): return tuple(self.rng.randint(2, 10 ** 6) for _ in self.fib.syms) @@ -1483,13 +2291,12 @@ def moved_point(self, base, i): def rur(self, pt, p): """The representation of the fiber at `pt` modulo p, None at a point of another size.""" - import time key = (pt, p) if key not in self.memo: - if time.monotonic() > self.deadline: - raise BudgetError() + if self.meter.spend(): + raise CapError() point = dict(zip(self.fib.syms, [spy.Integer(v) for v in pt])) - rur = _rur(self.fib, point, p, self.timeout) + rur = _rur(self.fib, point, p) if rur is not None and self.k is not None and rur["deg"] != self.k: rur = None self.memo[key] = [rur, None, None] @@ -1513,10 +2320,12 @@ def points_of(self, pt, p): def _monomials(nv, d): + """The exponent tuples in `nv` variables of total degree at most d.""" return [m for t in range(d + 1) for m in _exps(nv, t)] def _exps(nv, t): + """The exponent tuples in `nv` variables of total degree t.""" if nv == 0: return [()] if t == 0 else [] return [(a,) + r for a in range(t, -1, -1) for r in _exps(nv - 1, t - a)] @@ -1580,7 +2389,7 @@ def interpolate(oracle, sam, base, primes, cap=_DEG_CAP): def _recon(sols, primes, mons, syms): - """The rational function from its coefficient vectors modulo the first primes, None where none is bounded.""" + """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)]) if any(dd == "0" for dd in rec["den"]): return None @@ -1594,7 +2403,7 @@ def _recon(sols, primes, mons, syms): def _holds(oracle, sam, r, p): """Whether `r` matches `oracle` at two check points modulo p, apart from the pool.""" - if not hasattr(sam, "checks"): + if sam.checks is None: sam.checks = [sam.point() for _ in range(2)] for pt in sam.checks: c = oracle(pt, p) @@ -1625,7 +2434,7 @@ def _rational_roots(coeffs, Z): def _labels(sam, roots, pt, p): - """{label: fiber point} at `pt`: the label holds, per separating coordinate, the index of the root its value + """{label: fiber point} at `pt`: the label holds, per separating coordinate, the index of the root the value matches; a point off every root lies on an irrational branch and has none. None where two roots meet.""" point = dict(zip(sam.fib.syms, [spy.Integer(v) for v in pt])) try: @@ -1645,21 +2454,21 @@ def _labels(sam, roots, pt, p): return out -def rational_maps(fib, timeout, budget=math.inf): - """(count, maps) of _rational_maps(), maps None where the budget of seconds runs out.""" +def rational_maps(fib, meter=None): + """(count, maps) of _rational_maps(), maps None where the points of the fiber reach the cap of `meter`.""" try: - return _rational_maps(fib, timeout, budget) - except BudgetError: + return _rational_maps(fib, meter) + except CapError: return None, None -def _rational_maps(fib, timeout, budget): +def _rational_maps(fib, meter): """(count, maps): the size of the fiber and the rational maps sigma onto other points of it, None if unknown. Coordinates with the fewest arguments come first: their characteristic polynomials over the fiber are interpolated and factored until the rational roots separate the points; the other coordinates are then interpolated on each branch.""" - sam = _Sampler(fib, timeout, budget) + sam = _Sampler(fib, meter) primes = list(PRIMES) base = sam.point() cp = sam.at(base, primes[0]) @@ -1695,7 +2504,7 @@ def oracle(pt, p): continue roots[fib.syms[fib.names.index(nm)]] = rs lab = _labels(sam, roots, sam.points(1)[0], primes[1]) - # separated: no point of a rational branch shares its label + # 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])): labels = lab @@ -1728,7 +2537,7 @@ def oracle(pt, p): def _on_roots(sam, roots, fp, pt, p): - """Whether every separating coordinate of the fiber point `fp` takes the value of one of its roots.""" + """Whether every separating coordinate of the fiber point `fp` takes one of the root values of that coordinate.""" point = dict(zip(sam.fib.syms, [spy.Integer(v) for v in pt])) for s, rs in roots.items(): x = fp[sam.fib.names[sam.fib.syms.index(s)]] @@ -1747,7 +2556,7 @@ def output_preserved(fib, sig, points=3, deeper=0): img = {s: e.xreplace(pt) for s, e in sig.items()} a, b = fib.series.numeric(pt, order, gap), fib.series.numeric(img, order, gap) if a is not None and b is not None: - # a copy with a free start keeps the output only from the image of its start, which is no coordinate + # a copy with a free start keeps the output only from the image of the free start, which is no coordinate a = [r for k, r in enumerate(a) if k not in fib.series.free_rows] b = [r for k, r in enumerate(b) if k not in fib.series.free_rows] if a is None or b is None or any(x != y for x, y in zip(a, b)): @@ -1774,11 +2583,12 @@ def patterns(series, order, gap, p): return [frozenset(x) for x in out] -def candidates(series, order, gap, p, deadline): +def candidates(series, order, gap, p, meter=None): """The permutations of the coordinates that keep the output coefficients up to `order` (and `gap` in eps) at a random point modulo p: the transpositions within a class of equal patterns, then the products of two - transpositions that fail alone. Each as {symbol: image} over all coordinates; the search stops at `deadline`.""" - import time + transpositions that fail alone. Each as {symbol: image} over all coordinates; each permutation tested spends one + unit of `meter`, and the search stops at the cap.""" + meter = meter or work.unlimited() pats = patterns(series, order, gap, p) if pats is None: return [] @@ -1804,16 +2614,21 @@ def swapped(pairs): found, failed = [], [] for idx in groups.values(): for i, j in itertools.combinations(idx, 2): - if time.monotonic() > deadline: - return found + if meter.spend(): + return _as_maps(series, found) (found if vals(swapped([(i, j)])) == base else failed).append([(i, j)]) for a, b in itertools.combinations(failed, 2): - if time.monotonic() > deadline: - break if {*a[0]} & {*b[0]} or any(pats[a[0][0]] == pats[x] for x in b[0]): continue + if meter.spend(): + break if vals(swapped(a + b)) == base: found.append(a + b) + return _as_maps(series, found) + + +def _as_maps(series, found): + """The transpositions `found` as {symbol: image} over all coordinates.""" out = [] for pairs in found: sig = {s: s for s in series.cs} @@ -1872,10 +2687,10 @@ def coeffs(e): def _state_map(f, g, ic, sig, states): """A map phi of the states that takes the model at theta onto the model at sigma(theta), over Q(x, theta), or - None. With the initial values `ic`, a state whose initial value is a coordinate of its own, the state itself - or a parameter found nowhere else, takes the image of that coordinate with every such coordinate read as its + None. With the initial values `ic`, a state whose initial value is a separate coordinate, the state itself + or a parameter found nowhere else, takes the image of that coordinate with every such coordinate read as the state. Another state is mapped to itself, or, where that fails, to the solution of h(phi, sigma) = h(x, theta) - for the output h and its Lie derivatives when these equations are linear in phi; with `ic`, phi must map the + for the output h and the Lie derivatives of h when these equations are linear in phi; with `ic`, phi must map the initial value at theta to the initial value at sigma(theta).""" F = {spy.Symbol(k): model_sympify(v) for k, v in f.items()} X = [spy.Symbol(x) for x in states] @@ -1912,18 +2727,39 @@ def holds(phi): try: if holds(phi): return phi + # a state that starts at 1 with a rate x*R(x, theta) maps to x^c where R(sigma) = c R for a rational c + alt = dict(phi) + for x in given: + R = spy.cancel(F[x] / x) + if x0.get(x) != 1 or R.has(x) or R == 0: + continue + c = spy.cancel(R.xreplace({**th, **phi}) / R) + if c.is_Rational and c not in (0, 1): + alt[x] = x ** c + if alt != phi and holds(alt): + return alt blk = _block_map(F, H, X, x0, th) if blk is not None and holds(blk): return blk - # the solve from the outputs grows with the number of states - if not given or len(given) > 12: + if not given or len(given) > _SOLVE_STATES: return None P = {x: spy.Dummy(str(x)) for x in given} img = {**th, **{x: phi[x] for x in X if x not in P}, **P} - eqs, rows = [], list(H) + eqs, rows, cap = [], list(H), work.CAPS["state_map_terms"] for _ in range(len(given) + 1): + # 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:,}") + 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:,}") + 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): return None @@ -1937,7 +2773,36 @@ def holds(phi): return None +def _term_bound(e, memo=None): + """An upper bound on the terms of the expansion of `e`, from the expression tree without expanding: sums add, + products multiply, a power to an integer n takes the bound to the |n|-th power, as a denominator enters the + numerator over one denominator, anything else is one term.""" + memo = {} if memo is None else memo + if e in memo: + return memo[e] + if e.is_Add: + out = sum(_term_bound(a, memo) for a in e.args) + elif e.is_Mul: + out = math.prod(_term_bound(a, memo) for a in e.args) + elif e.is_Pow and e.exp.is_Integer: + out = _term_bound(e.base, memo) ** abs(int(e.exp)) + else: + out = 1 + memo[e] = out + return out + + def state_map_proof(parts, sig, states, positive=True): + """_state_map_proof(), and for a model with unknown inputs, where that fails, a map of the states and the inputs + (uinputs.input_state_map).""" + 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 + + +def _state_map_proof(parts, sig, states, positive=True): """The maps of the states, one per segment of each condition, that prove sigma a symmetry over Q(x, theta), or None: in each segment a map phi of the states (_state_map, with the initial values in the first segment), and at each event the image of the event at theta @@ -1955,10 +2820,15 @@ def state_map_proof(parts, sig, states, positive=True): qs = [model_sympify(str(q)) for q in part.get("surfaces") or ()] prev = None for j, seg in enumerate(part["segments"]): - ic = seg["ic"] if j == 0 and None not in (seg["ic"] or {None: None}).values() else None + jets = set(seg.get("inputs") or ()) + given = [v for k, v in (seg.get("ic") or {None: None}).items() if k not in jets] + ic = seg["ic"] if j == 0 and None not in given else None phi = _state_map(seg["f"], seg["g"], ic, sig, states) if phi is None: return None + # the identities take the jets of unknown inputs as constants: phi must not read them + if jets and any({str(v) for v in e.free_symbols} & jets for e in phi.values()): + return None for q in qs: c = spy.cancel(q.xreplace({**th, **phi}) / q) if c.free_symbols & set(X) or not is_positive(c, positive): @@ -1991,6 +2861,9 @@ def domain_conditions(fib, sig): pos = {s: spy.Symbol(str(s), positive=True) for s in fib.syms if names is None or str(s) in names} conds = [] for s, e in sig.items(): + if e.has(spy.I) and spy.im(e.xreplace(fib.known).xreplace(pos)) != 0: + # a map over Q(i) whose image is not real at a real point never meets the domain + return False, [f"{e} is not real"] if s not in pos: continue if is_positive(e.xreplace(fib.known), fib.positive): @@ -2023,7 +2896,7 @@ def fixed_set(sig): 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 its orbit in that order.""" + 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)))) @@ -2034,47 +2907,150 @@ def fundamental_domain(coords, states, maps): return list(dict.fromkeys(out)) -def choose_order(series, positive, start, cap, timeout, budget=math.inf, floor=1): +def choose_order(series, positive, start, cap, floor=1, proj=None, lowest=False, raises=None): """(fiber, stable, count): the fiber at the orders of the observables that SIAN's rank criterion gives (else `start` for each), raised together by one until the count over the algebraic closure equals the count one step - higher, at most to `cap`. While raising, one count may take a quarter of `budget`, since a fiber with a component - of positive dimension costs msolve much more than the finite fiber one order higher. The search stops after - `budget` seconds once a finite count is found, else after three times the budget; without any finite count the - last fiber gets one count with the full `timeout`. A count equal to `floor`, the size of an orbit of proven - maps, ends the search: a higher order only removes points, and the orbit stays; the first count then gets the - full `timeout`.""" - import time - t0 = time.monotonic() - step = min(timeout, max(30.0, budget / 4)) + higher, at most to `cap` and at most `raises` times (_ORDER_RAISES by default). A fiber past the caps of msolve + ends the search: a higher order has more terms. A count equal to `floor`, the size of an orbit of proven maps, + ends it as well: a higher order only removes points, and the orbit stays. With `proj`, the counts are those of + the values of the first `proj` coordinates; with `lowest`, each observable starts one order above the order of + that observable in the rank criterion.""" + raises = _ORDER_RAISES if raises is None else raises crit = series.output_orders(cap, PRIMES[0]) # 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 = [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} prev = found = None - for t in range(cap + 1): + for t in range(min(cap, raises) + 1): orders = [n + t for n in base] - spent = time.monotonic() - t0 - if max(orders) > cap or (prev is not None and spent > (budget if found else 3 * budget)): + if max(orders) > cap: break # the gap order rises with the Lie order, from zero gaps on fib = Fiber(series, orders, positive, gap=t) - cc = complex_count(fib, point, PRIMES[0], timeout if floor > 1 and prev is None else step) + if proj is not None: + fib.proj = proj + cc, sized = _sized_count(fib, point) if prev is not None and cc is not None and cc == prev[1]: return prev[0], True, cc if cc == floor: # a higher order adds equations, so the fiber there lies in this one and holds the orbit of the point return fib, True, cc + if cc is None and (getattr(fib, "too_large", None) or sized): + # a higher order has more terms + return (found[0], False, found[1]) if found is not None else (fib, False, None) prev = (fib, cc) if cc is not None: found = prev if found is not None: return found[0], False, found[1] if prev is None: - return Fiber(series, base, positive), False, None - return prev[0], False, complex_count(prev[0], point, PRIMES[0], timeout) + fib = Fiber(series, base, positive) + if proj is not None: + fib.proj = proj + return fib, False, None + return prev[0], False, None + + +def _sized_count(fib, point): + """(count, sized): complex_count() modulo the first prime, and whether a system of it was past the caps of + msolve.""" + before = set(_FAILURES) + _FAILURES.discard("size") + cc = complex_count(fib, point, PRIMES[0]) + sized = "size" in _FAILURES + _FAILURES.update(before) + return cc, sized + + +def pinned_count(series, positive, floor, names=None): + """{"why", "orders", "count", "cert", "fiber", "functions"}: the count of the fiber of pins of the series, functions + proven in the field of the output coefficients (`names` their texts), and of the output coefficients up to the + orders at which their gradients reach the number of coordinates, raised by one at a time until the count modulo a + prime at a random point is below twice `floor`, the orbit of the proven maps; then over Q at a random integer point + with the bound of count_certificate(), which holds where that count is below twice `floor` (docs/method/global.rst, + "The exact count"). The pins of least degree that raise the rank and as many more come first, then all of them. + `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"]): + 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]) + if crit is None: + out["why"] = "the output coefficients do not reach the rank of the coordinates" + return out + every = list(series.pins) + try: + for use in _pin_sets(series, PRIMES[0]): + series.pins = [every[i] for i in use] + out = _pinned_once(series, positive, floor, crit, cap) + out["functions"] = [names[i] for i in use] if names else None + if (out["cert"] or {}).get("bound") is not None: + break + finally: + series.pins = every + return out + + +def _pin_sets(series, p): + """Index lists of the pins to count: those of least degree whose gradients raise the rank at the random point of + Series.jacobian() modulo p with as many more of least degree, then all; all where a pin has a pole there.""" + every = list(range(len(series.pins))) + pv = series.pin_values(p) + if pv is None: + return [every] + order = sorted(every, key=lambda i: (_pin_degree(series.pins[i]), sum(len(P) for P in series.pins[i]))) + basis, piv, first = [], [], [] + for i in order: + row = list(pv[i].d) + for b, c in zip(basis, piv): + if row[c]: + row = [(x - row[c] * y) % p for x, y in zip(row, b)] + c = next((j for j, x in enumerate(row) if x), None) + if c is not None: + inv = pow(row[c], -1, 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)] + return [sorted(first), every] if len(first) < len(every) else [every] + + +def _pinned_once(series, positive, floor, crit, cap): + """pinned_count() with the pins of the series as they are.""" + out = {"why": None, "orders": None, "count": None, "cert": None, "fiber": None} + base = series.pinned_orders(cap, PRIMES[0]) + if base is None: + out["why"] = "the proven functions and the output coefficients do not reach the rank of the coordinates" + return out + if max(base) >= max(crit): + 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} + 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 + for t in range(1, max(crit) + 1 - max(base)): + fib = Fiber(series, [n + t for n in base], positive) + cc, sized = _sized_count(fib, point) + # a higher order has more terms + if cc is not None and cc < 2 * floor or getattr(fib, "too_large", None) or sized: + 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") + return out + out["cert"] = count_certificate(fib, floor, base, within=(floor, 2 * floor)) + if out["cert"]["bound"] is None: + out["why"] = out["cert"]["why"] + return out def _same_map(a, b): @@ -2097,64 +3073,151 @@ def group(maps, syms, cap=64): return group -def _candidate_stage(series, parts, states, positive, deadline): +def _candidate_stage(series, parts, states, positive, meter): """(maps, info) of the candidates: permutations of coordinates with equal patterns that keep the output modulo a prime, each with the state maps that prove it or None.""" - import time t0 = time.monotonic() crit = series.output_orders(2 * len(series.coords), PRIMES[0]) if crit is None: return [], {"seconds": round(time.monotonic() - t0, 2), "tested": False} order = max(crit) + 1 + _DEEPER gap = _DEEPER if series.has_events else 0 - found = candidates(series, order, gap, PRIMES[0], deadline) - out = [(sig, state_map_proof(parts, sig, states, positive)) for sig in found] + 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), "complete_search": time.monotonic() <= deadline} + "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, timeout=600, budget=300): +def analyze(parts, coords, positive, states, order=None, start=None, points=_POINTS, inputs=(), experiments=None): """The discrete symmetries of a locally identifiable model, as a dict; `parts` as in Series, one per condition. First the candidates: permutations of coordinates whose output coefficients have the same pattern, kept modulo a prime and proven by a map of the states. Then the count: without `order`, the order rises from `start` (the Lie order of the rank) until the count over the algebraic closure is stable; after an event the gap order rises with - it from zero. The maps of the fiber are reconstructed within `budget` seconds.""" - import time - t0 = time.monotonic() - series = Series(parts, coords) + it from zero. Where the short count finds none, the count of several experiments comes first + (multiexp.count()); `experiments` True or a number of experiments takes it before the exact count, False never. + Every stage ends at the work caps of work.CAPS; a stage that reaches one names it in the limits.""" + series = Series(parts, coords, positive) syms = [spy.Symbol(c) for c in coords] + # a free power of a state at 0 has no state maps and no exact count through the Taylor coefficients alone + spow = series.start_powers timing = {} limits = [] - cand, cinfo = _candidate_stage(series, parts, states, positive, t0 + budget / 3) + _FAILURES.clear() + _CAPPED.clear() + caps = work.CAPS + series.meter = work.Meter("the Taylor series of the outputs", caps["series_products"], "term products") + cmeter = work.Meter("the search of candidates", caps["candidates"], "permutations") + cand, cinfo = _candidate_stage(series, parts, states, positive, cmeter) timing["candidates"] = cinfo["seconds"] if cinfo.get("complete_search") is False: - limits.append(f"the candidates were tested for {budget / 3:g} s, not all of them") - t1 = time.monotonic() - left = max(30.0, budget - (t1 - t0)) + limits.append(f"the candidates were not all tested: {cmeter.reason()}") cc = None proven = [sig for sig, pf in cand if pf is not None] cgrp = group(proven, syms) if proven else None - if order: + # 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) + ex = Series(parts, coords + consts, positive) if consts and not spow else series + ex_syms = syms + [spy.Symbol(c) for c in consts] + floor = len(cgrp) if cgrp else 1 + quick, me = None, None + forced = experiments is not None and experiments is not False and not order + if forced: + me = _experiments(parts, coords, series, positive, floor, experiments, timing) + if _final(me, floor, proven, cand): + pass + elif not order and len(proven) == len(cand): + crit = series.output_orders(2 * len(coords), PRIMES[0]) + # a short count first: a count above the orbit of the candidates shows maps the exact count needs + t2 = time.monotonic() + with work.quick_msolve(): + quick = choose_order(series, positive, int(start or 1), 2 * len(coords), floor=floor, raises=1) + timing["count"] = round(time.monotonic() - t2, 2) + if crit is not None and not spow and (quick[2] is None or quick[2] == floor) and not series.inputs: + t3 = time.monotonic() + tried = cgrp or [{s: s for s in syms}] + proof = exact_fiber(ex, [max(crit) + 3] * len(crit), tried, ex_syms, inputs, consts) + timing["exact"] = round(time.monotonic() - t3, 2) + pinned = verified = None + if proof is not None and not proof["exact"]: + extra = [] + if proof.get("large") and len(proven) == len(cand): + # a projection past the terms the exact search interpolates: a few of the coefficients, verified + t3 = time.monotonic() + verified = _verified(ex, ex_syms, proof["large"]) + extra = verified["functions"] + timing["relation"] = round(time.monotonic() - t3, 2) + # the functions proven in the field of the outputs take their value at every point of the fiber + series.pins, texts = _pins(list(proof.get("proven") or []) + extra, series, names=True) + if series.pins and len(proven) == len(cand): + # where the search stops short of the coordinates: the count of the fiber of the proven functions + t3 = time.monotonic() + pinned = pinned_count(series, positive, floor, texts) + timing["pinned"] = round(time.monotonic() - t3, 2) + _add_relation_bound(pinned, verified) + certified = pinned is not None and pinned["cert"] is not None and pinned["cert"]["bound"] is not None + if proof is not None and proof["exact"]: + fib, stable = Fiber(series, [max(crit) + 1] * len(crit), positive), None + elif certified: + fib, stable, cc = pinned["fiber"], None, floor + elif order: fib, stable = Fiber(series, int(order), positive, gap=int(order)), None + elif quick is not None and quick[2] is not None: + fib, stable, cc = quick else: - fib, stable, cc = choose_order(series, positive, int(start or 1), 2 * len(coords), timeout, left, - floor=len(cgrp) if cgrp else 1) - timing["count"] = round(time.monotonic() - t1, 2) + if me is None and experiments is not False: + # one experiment gave no short count: several experiments come first + me = _experiments(parts, coords, series, positive, floor, None, timing) + if _final(me, floor, proven, cand): + # the count is below twice the orbit of the proven maps, which divides the size of the fiber + crit1 = series.output_orders(2 * len(coords), PRIMES[0]) + fib = Fiber(series, [max(crit1) + 1] * len(crit1) if crit1 else int(start or 1), positive) + stable, cc, me["final"] = me["stable"], floor, True + else: + t2 = time.monotonic() + # the limit of a count without result names the failures of this count + _FAILURES.clear() + fib, stable, cc = choose_order(series, positive, int(start or 1), 2 * len(coords), floor=floor) + timing["count"] = round(timing.get("count", 0.0) + time.monotonic() - t2, 2) + if cc is None and me is not None and me.get("count") is not None: + # the count of the experiments stands for that of one, with no maps to reconstruct + cc, me["used"] = me["count"], True k, maps, false = None, None, [] - if cc is not None and cgrp is not None and len(cgrp) == cc and len(proven) == len(cand): + if proof is not None and proof["exact"]: + k, maps = len(tried), [] + timing["maps"] = 0.0 + elif certified: + # below twice the orbit of the proven candidates, which divides the size of the fiber + k, maps = floor, [] + timing["maps"] = 0.0 + 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") + 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, [] timing["maps"] = 0.0 elif order or cc is not None: t2 = time.monotonic() + mmeter = work.Meter("the reconstruction of the maps", caps["map_points"], "points of the fiber") # a map of the fiber that does not keep the coefficients further up shows a fiber too large at this order: # the orders rise and the count is taken again for _ in range(_RAISES + 1): # a count of one has no maps to find - k, maps = (1, []) if cc == 1 else rational_maps(fib, timeout, left) + k, maps = (1, []) if cc == 1 else rational_maps(fib, mmeter) k = cc if k is None else k - false = [sig for sig in maps or [] if not output_preserved(fib, sig, deeper=_DEEPER)] - if not false or order or time.monotonic() - t1 > left: + if series.inputs: + from .uinputs import preserved + else: + preserved = output_preserved + false = [sig for sig in maps or [] if not preserved(fib, sig, deeper=_DEEPER)] + if not false or order or mmeter.over: break 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) @@ -2163,64 +3226,277 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI 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 time.monotonic() - t1 > left: - limits.append(f"the closed forms of the maps were not found within the budget of {budget:g} s") + 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") + 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)") else: - limits.append(_NO_FINITE_COUNT.format(order=fib.order)) + limits.append(no_count_reason(fib.order)) # the candidates join the maps of the fiber proofs = {} 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: + timing["monodromy"] = round(time.monotonic() - t2, 2) + if "cap" in str(mono.get("why") or ""): + limits.append(f"the monodromy stopped: {mono['why']}") + every += mono_maps for sig, pf in cand: same = next((m for m in every if _same_map(sig, m)), None) if same is None: every.append(sig) same = sig proofs[id(same)] = pf - out = [] - for sig in every: - 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 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 []))) if hit] - entry["state_maps"] = pf - entry["preserves_domain"], entry["domain_conditions"] = domain_conditions(fib, sig) - entry["fixed_set"] = fixed_set(sig) - out.append(entry) + out = [_entry(sig, proofs, maps, mono_maps, fib, syms, parts, states, positive, spow) for sig in every] exact = [sig for sig, e in zip(every, out) if e["level"] == "exact"] grp = group(exact, syms) orbit = None if grp is None else len(grp) # the proven maps account for every point counted: the reconstruction of the fiber adds nothing complete = k is not None and not false and orbit == k and all(e["level"] == "exact" for e in out) + # the count of several experiments: below twice the orbit of the exact maps, which divides the size of the + # fiber, it leaves the orbit; `single` is a count of one experiment equal to the orbit + 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): + 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: + t3 = time.monotonic() + # the functions the first search proved in the field of the outputs hold for any group + pre = (proof or {}).get("proven", []) + proof = exact_fiber(ex, fib.orders, grp, ex_syms, inputs, consts, pre) + timing["exact"] = round(timing.get("exact", 0.0) + time.monotonic() - t3, 2) + if not proof["exact"]: + series.pins = _pins(list(pre) + list(proof.get("proven") or []), series) + if proof is not None and proof["exact"] and grp is not None: + complete = True + k = orbit counts = [] - if k is not None: - # the counts in the domain end with the time of the count: budget and one call of msolve - counts, skipped = _domain_counts(fib, maps, k, points, timeout, coords, grp[1:] if complete else None, - deadline=t0 + budget + timeout) - if skipped: - limits.append(f"the counts in the domain stopped after {budget + timeout:g} s: {skipped} of " - f"{len(counts)} points without a count") + if k is not None and not (me or {}).get("used"): + counts = _domain_counts(fib, maps, k, points, coords, grp[1:] if complete else None) if k is None: k = next((c["complex"] for c in counts if c.get("complex")), None) + cb = None + if certified: + cb = pinned["cert"] + elif k is not None and not (proof and proof["exact"]): + 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) + 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])) + if one["bound"] is not None: + route, cb = None, one + else: + cb = count_certificate(fib, k, series.output_orders(2 * len(coords), PRIMES[0])) + 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") 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 + count_domain = None + if complete and grp is not None and orbit == k: + keeps = [domain_conditions(fib, g)[0] for g in grp[1:]] + if all(x is not None for x in keeps): + 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, + "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, - "certificate": certificate(out, orbit, k, counts, complete)} + "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: + _start_power_info(info, spow) return {"symmetries": out, "info": info} -def _domain_counts(fib, maps, k, points, timeout, coords, proven=None, deadline=math.inf): - """(counts, skipped): per point of the domain the count over the algebraic closure and the real points in the - domain, and the number of points left without a count at `deadline`. With the elements `proven` of a group of - proven maps whose orbit has `k` points, the fiber at a point is the orbit of the point.""" - import time +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]} + 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["state_maps"] = pf + entry["preserves_domain"], entry["domain_conditions"] = domain_conditions(fib, sig) + entry["fixed_set"] = fixed_set(sig) + return entry + + +def _start_power_info(info, spow): + """The free powers of states at 0 in the info and the certificate: the exponent of the point holds at every point + of the fiber in the domain, proven or under the premises named.""" + cert = info["certificate"] + info["start_powers"] = [] + premises = [] + 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"])}) + 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']}") + 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'])") + if premises: + cert["premise"] = "; ".join(premises) + if cert.get("complete") in ("exact", "verified"): + cert["complete"] = "axiom" + cert["axiom"] = cert["premise"] + + +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) + return me + + +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 + + +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)) + try: + out = fewcoef.verified_functions(series, syms, large, work.CAPS["verified_entries"], rng, log) + finally: + ioproj.THREADS[0] = threads + out["log"] = log + return out + + +def _add_relation_bound(pinned, verified): + """Adds to the bound of the count the probabilities of the verified relation, where the functions of the + relation are counted: that no relation exists on the support, and per function counted that it is not the + 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")} + 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: + return + extra = verified["exist"] + sum(verified["checks"][f] for f in used) + pinned["relation_bound"] = extra + cb["count_bound"] = cb["bound"] + cb["bound"] = cb["bound"] + extra + + +def _pinned_info(pinned): + """The part of the result of pinned_count() that the certificate reports, None where it did not run.""" + if pinned is None: + 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"]} + 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"))) + return out + + +def _route_info(me): + """The part of the result of multiexp.count() that info["discrete"]["experiments"] reports.""" + keys = ("why", "experiments", "orders", "count", "failed", "stable", "seconds", "first_integrals") + return {k: me[k] for k in keys if k in me} + + +def _monic(P): + """The polynomial {exponents: Fraction} over the coefficient of the largest exponent vector.""" + c = P[max(P)] + return {m: v / c for m, v in P.items()} + + +def _pins(proven, series, names=False): + """(num, den) in the coordinates of each proven function that reads coordinates, the known constants at the values + of the series; with `names`, also the text of the function of each.""" + out, texts = [], [] + for f in dict.fromkeys(proven): + e = spy.cancel(model_sympify(str(f)).xreplace(series.known)) + if not e.free_symbols or e.free_symbols - set(series.cs): + continue + num, den = spy.fraction(e) + # f and a constant multiple of f are one equation + P = tuple(_monic(_dict(x, series.cs)) for x in (num, den)) + if P not in out: + out.append(P) + texts.append(str(f)) + return (out, texts) if names else out + + +def power_coordinates(series): + """{parameter: g}: the parameters that every right-hand side, observable and start reads only through powers + with exponents divisible by g > 2; g = 2 is the sign map, a rational map.""" + out = {} + for pi, p in enumerate(series.params): + exps = [] + for part in series.parts: + ns = len(part["st"]) + for seg in part["segs"]: + for N, D in list(seg["F"]) + list(seg["G"]): + exps += [m[ns + pi] for P in (N, D) for m in P] + if "x0" in seg: + k = series.cs.index(p) + exps += [m[k] for v in seg["x0"] if v[1] is not None for P in v[1:] for m in P] + g = math.gcd(*[e for e in exps if e]) if any(exps) else 0 + if g > 2: + out[str(p)] = g + return out + + +def _domain_counts(fib, maps, k, points, coords, proven=None): + """Per point of the domain the count over the algebraic closure and the real points in the domain. With the + 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] @@ -2230,29 +3506,20 @@ def count_at(pt): boxes = _boxes_of_maps(fib, pt, proven, check=False) if boxes is not None: return None, boxes - left = deadline - time.monotonic() - if left <= 0: - return "skipped", None - cc = complex_count(fib, {s: v for s, v in pt.items()}, PRIMES[0], min(timeout, left)) \ + 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 its images are the fiber, exactly + # 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 - left = deadline - time.monotonic() - if boxes is None and left <= 0: - return cc, None - return cc, boxes if boxes is not None else real_points(fib, pt, min(timeout, left)) - from ..sym import msolve + 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): if workers > 1: - from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(workers) as ex: done = list(ex.map(count_at, pts)) else: done = [count_at(pt) for pt in pts] - counts, skipped = [], sum(cc == "skipped" for cc, _ in done) - done = [(None if cc == "skipped" else cc, boxes) for cc, boxes in done] + 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, @@ -2262,31 +3529,294 @@ def count_at(pt): 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, skipped + return counts + + +def _sparse_deg(P): + return max((sum(e for _, e in mm) for mm in P), default=0) + + +def _fiber_degrees(fib): + """The total degrees in (theta, u) of the fiber equations of docs/method/global.rst, "The verified count": the + equations of the model, the saturation, and the output equations with the Taylor coefficients over one denominator, + 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)) + except ZeroDivisionError: + outs = None + if outs is None: + return None + # per Taylor coefficient the coefficients in eps or in the layers of a free power of a state at 0 + vals = [[list(y[k]) for k in range(n + 1)] for y, n in zip(outs, fib.orders)] + dq, nums = common([v for row in vals for ks in row for v in ks]) + it = iter(nums) + bnum = [[[next(it) for _ in ks] for ks in row] for row in vals] + degs = [_sparse_deg(P) for P in fib.static] + [1 + sum(_sparse_deg(f) for f in fib.sat)] + # a pin num(x) den(theta) - den(x) num(theta) + degs += [2 * max(_sparse_deg(_sparse(n)), _sparse_deg(_sparse(d))) for n, d in fib.series.pins] + 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] + if M[k][m]: + terms.append(_sparse_deg(M[k][m]) + dq) + if terms: + degs.append(max(terms)) + return degs + + +class _AllDigits: + """Integers of any length convert to text: the points of the verified count reach thousands of digits.""" + + def __enter__(self): + self.limit = sys.get_int_max_str_digits() + sys.set_int_max_str_digits(0) + + def __exit__(self, *exc): + sys.set_int_max_str_digits(self.limit) + + +def _x_bezout(fib): + """The Bezout number of n output equations c(x) = c(theta), cleared, whose gradients in x are independent, + and of w s(x) = 1, s the product of the coordinates and of the denominators at the start; None where the rows + are not found (docs/method/global.rst, "The verified count").""" + series = fib.series + if series.start_powers: + # 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}] + # 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: + got.append(_row_degrees(series, series.rank_rows(2 * len(series.cs), PRIMES[0], pins=True))) + got = [d for d in got if d is not None] + if not got: + return None + degs = min(got, key=math.prod) + # the saturation in x alone: the starts substituted into the denominators of the right-hand sides and the + # observables + sat = spy.prod(spy.Symbol(c) for c in series.coords) + for part in series.parts: + seg = part["segs"][0] + start = [spy.sympify(v[0]) if v[0] is not None else spy.Symbol(str(x)) for x, v in zip(part["st"], seg["x0"])] + gens = list(part["st"]) + list(series.params) + 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"]] + 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] + try: + ds = spy.Poly(spy.expand(sat), *syms).total_degree() + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + return (1 + ds) * math.prod(degs) + + +def _pin_degree(pin): + """The degree of num(x) den(theta) - num(theta) den(x) in (theta, x) for a pin (num, den).""" + return sum(max((sum(m) for m in P), default=0) for P in pin) + + +def _row_degrees(series, rows): + """The degrees in (theta, x) of the equations of the rows of rank_rows(): num(x) den(theta) - num(theta) den(x) + of an output coefficient or a pin; None without rows.""" + if rows is None: + return None + A = Atoms() + top = max((k for j, k in rows if j != "pin"), default=0) + try: + outs = series._outputs([Deg(A, 1) for _ in series.cs], top, 0, Deg.const(A, 1), Deg.const(A, 0)) + except ZeroDivisionError: + return None + if outs is None: + return None + degs = [] + for j, k in rows: + if j == "pin": + degs.append(max(1, _pin_degree(series.pins[k]))) + continue + v = outs[j][k][0] + degs.append(max(1, v.dn + A.of(v.den))) + return degs + + +def q_count(fib, point): + with _AllDigits(): + return _q_count(fib, point) + + +def _q_count(fib, point): + """The number of points of the fiber over the complex numbers at the rational `point`, from the rational + parametrization of msolve over Q per block; None on failure or a block of positive dimension.""" + try: + sysd = fib.system(point, eliminate=True) + except FiberTooLargeError: + return None + if sysd is None: + return 0 + n = 1 + for block in sysd["blocks"]: + k = _staged_count(fib, block["idx"], block["polys"], block["sat"], 0) + if k is None: + return None + n *= k + return n + + +def count_certificate(fib, k, crit, within=None): + """{"bound", "why", "bits", "count", "bezout"}: the count taken again over Q at a random integer point, and the + probability that the fiber at a generic point has more than `k` points (docs/method/global.rst, "The verified + count"); bound None where it does not apply, with the reason. With `within` = (lo, hi), the bound holds for the + count over Q where lo <= count < hi, and `count` is that count.""" + out = {"bound": None, "why": None, "bits": None, "count": None, "bezout": None} + series = fib.series + if series.has_events or fib.gap: + out["why"] = "the bound covers models without events" + return out + if any(seg.get("free") or seg.get("on") is not None for part in series.parts for seg in part["segs"]): + out["why"] = "the bound covers models without switches and free starts" + 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" + return out + degs = _fiber_degrees(fib) + if degs is None: + out["why"] = "the Taylor coefficients have a pole" + return out + D = math.prod(max(1, int(d)) for d in degs) + nu = len(fib.allnames) + 1 + # the variety in the coordinates and w alone, where the Bezout number is smaller + Dx = _x_bezout(fib) + if Dx is not None and (len(fib.names) + 1 + 2 * Dx) * Dx < (nu + 2 * D) * D: + D, nu = Dx, len(fib.names) + 1 + out["bezout"] = D + deg = (nu + 2 * D) * D + # logarithms of integers: the Bezout number can pass the range of a float + bits = max(_MIN_BITS, math.ceil(math.log2(deg) - math.log2(_VERIFIED_AIM))) + if bits > _VERIFIED_BITS: + out["why"] = f"the point would need coordinates of {bits} bits for a bound below {_VERIFIED_AIM:g}" + 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} + # 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 "") + 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}" + return out + if within is not None and not within[0] <= k2 < within[1]: + out["why"] = f"the count over Q at a random integer point is {k2}, not from {within[0]} to {within[1] - 1}" + return out + out["bound"] = 2.0 ** (math.log2(deg) - bits) + return out -def certificate(entries, orbit, k, counts, complete): - """What the result rests on: the invariance proven per map, the size of the orbit, and the count.""" +def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route=None, pinned=None): + """What the result rests on: the invariance proven per map, the size of the orbit, and the count: exact by the + field of the outputs (`exact`, of fieldproof.exact_fiber), verified with the error bound `cb` of + count_certificate(), or under the axiom of the count. With `route`, of multiexp.count(), the count is that of + several experiments, which bounds the fiber of one where no rational first integral exists. With `pinned`, of + _pinned_info(), the count is that of the fiber of the functions proven in the field of the outputs and the output + coefficients at low orders.""" # a point of the domain whose fiber is read from the orbit has no count over the algebraic closure agree = [c["complex"] for c in counts if c.get("complex") is not None] - return { + cb = cb or {"bound": None, "why": None} + 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], "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, checked by cancellation", + "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"], - "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", - "complete": "axiom" if complete else ("no" if k is not None and orbit is not None and orbit < k else "open")} + "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["complete"] = "exact" + return out + if pinned is not None: + out["pinned"] = pinned + used = pinned is not None and pinned["count_bound"] is not None and route is None + if used: + 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 "") + + "), 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") + 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") + 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["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") + 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") + 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") + 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") + 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 "")) + 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}") + 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") + return out def observed_states(f, g, events=()): """The states the observables depend on through the right-hand sides and the event values, in the order of `f`: a state outside never changes the output.""" - from ..rexpr import get_symbols reads = {x: set(get_symbols([str(e)])) for x, e in f.items()} for e in events: reads.setdefault(e["var"], set()).update(get_symbols([str(e["value"])])) @@ -2299,11 +3829,11 @@ def observed_states(f, g, events=()): def resting_start(f, ic, inputs, coords): - """{state: resting value} of a condition at rest, the inputs at zero: a state that is a coordinate holds its free - resting value, a state without dynamics rests at its initial value, and the others solve the balances over + """{state: resting value} of a condition at rest, the inputs at zero: a state that is a coordinate holds a free + resting value, a state without dynamics rests at the initial value, and the others solve the balances over Q(theta), where they have one rational solution with the most states away from zero. A ValueError where they - have none.""" - from ..sym.parse import model_sympify + have none, or where the Bezout number of the balances in the states is past the cap rest_bezout of + work.CAPS, which SymPy is not given.""" zero = {spy.Symbol(u): spy.Integer(0) for u in inputs} rhs = {x: model_sympify(str(e)).xreplace(zero) for x, e in f.items()} out = {x: "0" for x in f if x in inputs} @@ -2319,23 +3849,53 @@ def resting_start(f, ic, inputs, coords): if not U: return out bal = [spy.fraction(spy.together(rhs[str(x)].xreplace(held)))[0] for x in U] - try: - sols = spy.solve(bal, U, dict=True) - except (NotImplementedError,) + SYMPY_FAILS as exc: - sympy_fail(exc) - sols = [] + # a transcendental balance in the states has no rational closed form for sympy to find, only a long search + 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") + 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}") + 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}") + 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())] 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] - if len(sols) != 1 or not all(_rational(sols[0][x]) for x in U): + # 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") out.update({str(x): str(spy.cancel(sols[0][x])) for x in U}) return out +def _largest_block(bal, U): + """The states of the largest strongly connected block of the balances `bal`, each read as the balance of the + state at the same place in `U`, an edge to every state it holds.""" + edges = [(x, y) for x, e in zip(U, bal) for y in e.free_symbols & set(U) if y != x] + return max(len(c) for c in strongly_connected_components((U, edges))) + + +def _solve_balances(bal, U): + """The solutions of the balances `bal` in the states `U` by SymPy; none where SymPy fails.""" + try: + return spy.solve(bal, U, dict=True) + except (NotImplementedError,) + SYMPY_FAILS as exc: + sympy_fail(exc) + return [] + + def _rational(e): """Whether `e` is a rational function, no root or other function.""" return all(p.exp.is_Integer for p in e.atoms(spy.Pow)) and not e.atoms(spy.Function) diff --git a/src/symident/detection/elim.py b/src/symident/detection/elim.py new file mode 100644 index 0000000..0fba91b --- /dev/null +++ b/src/symident/detection/elim.py @@ -0,0 +1,510 @@ +"""Input-output relations by elimination (docs/method/global.rst, "The exact count"): the states eliminated by +resultants over Z[theta] in the order of StructuralIdentifiability.jl (find_ioequations), each resultant factored, and +a factor dropped where it is nonzero at a point of a trajectory modulo a prime. The product of the factors kept +vanishes along every trajectory, so the relation is exact.""" + +import math +import types + +import flint + +from ..gfp import all_primes +from . import ioproj + +# test points of the refutation of a factor +_POINTS = 3 + + +class _Ring: + """The polynomials over Z in the coordinates, the unknown states and their derivatives, the known states and the + derivatives of the observables up to `order`.""" + + def __init__(self, rel, order): + self.rel = rel + states = [j for j in range(rel.ns) if rel.X[j] is not None] + self.unknown = [j for j in states if j not in rel.known] + self.known = [j for j in states if j in rel.known] + 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.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() + # the generators of the ring of the relations in this ring + self.map = {i: self.at[n] for i, n in enumerate(rel.names) if n in self.at} + for j in states: + g = rel.names.index(str(rel.X[j])) + self.map[g] = self.at[f"si_x{j}" if j in self.unknown else f"si_u{j}"] + + def x(self, j): + return self.gens[self.at[f"si_x{j}"]] + + def d(self, j): + return self.gens[self.at[f"si_d{j}"]] + + def y(self, r, k): + return self.gens[self.at[f"si_y{r}_{k}"]] + + def poly(self, P): + """A polynomial of the ring of the relations, over Q, as a primitive polynomial over Z, and the factor.""" + terms = list(P.terms()) + den = math.lcm(*[int(c.denominator) for _, c in terms]) if terms else 1 + n = len(self.names) + d = {} + for m, c in terms: + e = [0] * n + for i, k in enumerate(m): + if k: + e[self.map[i]] += k + d[tuple(e)] = int(c.numerator) * (den // int(c.denominator)) + return self.ctx.from_dict(d) + + def parts(self, q): + """(numerator, denominator) over Z of a function of the ring of the relations.""" + if hasattr(q, "numer"): + N, D = self.poly(q.numer), self.poly(q.denom) + # the rational factors of numerator and denominator cleared apart + fn = math.lcm(*[int(c.denominator) for _, c in q.numer.terms()]) if q.numer.terms() else 1 + fd = math.lcm(*[int(c.denominator) for _, c in q.denom.terms()]) if q.denom.terms() else 1 + return N * fd, D * fn + return self.poly(q), self.ctx.from_dict({(0,) * len(self.names): 1}) + + +def _deg(P, v): + return P.degrees()[v] if not P.is_zero() else -1 + + +def _coeff(P, v, k): + """The coefficient of variable v to the power k, a polynomial in the others.""" + out = {} + for m, c in P.to_dict().items(): + if m[v] == k: + mm = list(m) + mm[v] = 0 + out[tuple(mm)] = c + return P.context().from_dict(out) + + +class Eliminator: + """The elimination for one model: the equations, the derivation and the test points of the refutation.""" + + def __init__(self, rel, rng, terms=math.inf): + self.rel, self.rng, self.terms = rel, rng, terms + ns = sum(1 for j in range(rel.ns) if rel.X[j] is not None and j not in rel.known) + self.R = R = _Ring(rel, ns + 1) + self.p = all_primes()[0] + self.points = self._points() + # x_j' den_j = num_j for the unknown states; the derivatives of the known states as polynomials + self.x_eqs = {} + for j in R.unknown: + N, D = R.parts(rel.f[j]) + self.x_eqs[j] = D * R.d(j) - N + self.known_d = {} + for j in R.known: + N, D = R.parts(rel.f[j]) + if not D.is_constant(): + raise ValueError("a known state with a rational right-hand side") + self.known_d[j] = (N, D) + self.y_eqs = {} + for r, q in enumerate(rel.y): + M, E = R.parts(q) + self.y_eqs[r] = E * R.y(r, 0) - M + self.steps = [] + # per state eliminated, (A, B) with A x + B = 0 along every trajectory, or None + self.states = {} + + def _points(self): + """Values of every variable at the start of trajectories at random coordinates modulo p.""" + R, rel, p = self.R, self.rel, self.p + out = [] + tries = 0 + while len(out) < _POINTS: + tries += 1 + if tries > 20: + raise ValueError("no trajectory without a pole at random coordinates") + vals = {s: self.rng.randrange(1, p) for s in rel.syms} + got = ioproj.trajectory(rel, vals, p, R.order + 2) + if got is None: + continue + obs, states = got + pt = [0] * len(R.names) + byname = {str(s): v for s, v in vals.items()} + for n in R.params: + pt[R.at[n]] = byname.get(n, self.rng.randrange(1, p)) % p + for j in R.unknown: + pt[R.at[f"si_x{j}"]] = int(states[j][0]) % p + pt[R.at[f"si_d{j}"]] = int(states[j][1]) % p + for j in R.known: + pt[R.at[f"si_u{j}"]] = int(states[j][0]) % p + for r in range(len(rel.y)): + for k in range(R.order + 1): + pt[R.at[f"si_y{r}_{k}"]] = int(obs[r][k]) * math.factorial(k) % p + out.append(pt) + return out + + def value(self, P, pt): + return int(P(*pt)) % self.p + + def derive(self, P): + """The derivative along the flow: x_j -> d_j, u -> the right-hand side of u, y_r,k -> y_r,k+1.""" + R = self.R + out = P.context().from_dict({}) + for j in R.unknown: + v = R.at[f"si_x{j}"] + if _deg(P, v) > 0: + out += P.derivative(R.names[v]) * R.d(j) + for j, (N, D) in self.known_d.items(): + v = R.at[f"si_u{j}"] + if _deg(P, v) > 0: + if j in getattr(self.rel, "cut", ()): + raise ValueError("the derivative of the last jet of a known input that the relations keep") + c = int(D.coeffs()[0]) + if c != 1: + raise ValueError("a known state whose derivative has a rational coefficient") + out += P.derivative(R.names[v]) * N + for r in range(len(self.rel.y)): + for k in range(R.order + 1): + v = R.at[f"si_y{r}_{k}"] + if _deg(P, v) > 0: + if k == R.order: + raise ValueError("the derivatives of an observable past the order of the ring") + out += P.derivative(R.names[v]) * R.y(r, k + 1) + if any(_deg(P, R.at[f"si_d{j}"]) > 0 for j in R.unknown): + raise ValueError("a derivative of a state in a polynomial to differentiate") + return out + + def eliminate(self, f, g, v): + """A polynomial free of variable v from f and g, both vanishing along every trajectory: their resultant in v + after the reductions of the leading coefficients, factored, with the factors nonzero at a test point + dropped.""" + self._within(f, g) + while not f.is_zero() and not g.is_zero(): + if _deg(f, v) > _deg(g, v): + f, g = g, f + df, dg = _deg(f, v), _deg(g, v) + lf, lg = _coeff(f, v, df), _coeff(g, v, dg) + q, r = divmod(lg, lf) + if r.is_zero(): + g = g - q * f * self.R.gens[v] ** (dg - df) + continue + if df == dg: + q, r = divmod(lf, lg) + if r.is_zero(): + f = f - q * g + continue + break + if f.is_zero() or g.is_zero(): + return f + g + if _deg(f, v) == 0: + res = f + elif _deg(g, v) == 0: + res = g + else: + # polynomials in v^d: the resultant in v^d + exps = {m[v] for P in (f, g) for m in P.monoms()} + d = math.gcd(*exps) + if d > 1: + f, g = (_deflate(P, v, d) for P in (f, g)) + res, extra = _resultant(f, g, v) + return self.keep(res, extra) + return self.keep(res) + + def keep(self, P, extra=()): + """The product of the irreducible factors of P and of the polynomials `extra`, whose product vanishes along + every trajectory, that vanish at every test point: one of the factors vanishes along every trajectory, and a + factor nonzero at a point of a trajectory is not it.""" + if P.is_zero(): + return P + self._within(P, *extra) + facs = [] + for Q in [P] + list(extra): + for F, _ in Q.factor()[1]: + if not F.is_constant() and all(F != G and F != -G for G in facs): + facs.append(F) + kept = [F for F in facs if all(self.value(F, pt) == 0 for pt in self.points)] + self.steps.append((len(P), [len(F) for F in facs], len(kept))) + if not kept: + raise ValueError("every factor of a resultant is nonzero at a point of a trajectory") + out = kept[0] + for F in kept[1:]: + out = out * F + return out + + def _within(self, *polys): + """A ValueError where a polynomial has more terms than the cap.""" + n = max(len(P) for P in polys) + if n > self.terms: + raise ValueError(f"a polynomial of {n:,} terms, past the cap elimination_terms of {int(self.terms):,}") + + def run(self): + """{observable: relation} in the derivatives of the observables, the known states and the coordinates.""" + R = self.R + y_orders = {r: 0 for r in self.y_eqs} + while True: + degs = [] + for r, eq in self.y_eqs.items(): + ds = [_deg(eq, R.at[f"si_x{j}"]) for j in self.x_eqs if _deg(eq, R.at[f"si_x{j}"]) > 0] + if ds: + degs.append((min(ds) * len(eq), min(ds), -ds.count(min(ds)) + len(eq) / 30, len(eq), r)) + if not degs: + break + r = sorted(degs)[0][-1] + y_orders[r] += 1 + nxt = self.derive(self.y_eqs[r]) + for j, eq in self.x_eqs.items(): + nxt = self.eliminate(eq, nxt, R.at[f"si_d{j}"]) + 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) + v = cand[0][2] + vi = R.at[f"si_x{v}"] + del self.x_eqs[v] + for j in list(self.x_eqs): + self.x_eqs[j] = self.eliminate(self.x_eqs[j], self.y_eqs[r], vi) + for r2 in self.y_eqs: + if r2 != r: + self.y_eqs[r2] = self.eliminate(self.y_eqs[r2], self.y_eqs[r], vi) + self.states[v] = self.linear(self.y_eqs[r], nxt, vi) + self.y_eqs[r] = self.eliminate(self.y_eqs[r], nxt, vi) + return self.y_eqs, y_orders + + def linear(self, f, g, v): + """(A, B) with A v + B in the ideal of f and g, A nonzero at a test point: one of them where it has degree one + in v, else their first subresultant in v; None where A vanishes at the test points.""" + self._within(f, g) + pair = None + for P in (f, g): + if _deg(P, v) == 1: + c = _coeffs(P, v) + pair = (c[1], c[0]) + break + if pair is None and min(_deg(f, v), _deg(g, v)) >= 2: + pair = _subresultant1(f, g, v) + if pair is None or pair[0].is_zero() or all(self.value(pair[0], pt) == 0 for pt in self.points): + return None + return pair + + +def _deflate(P, v, d): + """P(v^(1/d)) for a polynomial in v^d.""" + out = {} + for m, c in P.to_dict().items(): + mm = list(m) + mm[v] //= d + out[tuple(mm)] = c + return P.context().from_dict(out) + + +def _coeffs(P, v): + """The coefficients of P in variable v, lowest degree first.""" + ctx = P.context() + out = [{} for _ in range(_deg(P, v) + 1)] + for m, c in P.to_dict().items(): + mm = list(m) + k = mm[v] + mm[v] = 0 + out[k][tuple(mm)] = c + return [ctx.from_dict(d) for d in out] + + +def _resultant(f, g, v): + """(D, factors): the determinant D of the Bezout matrix of f and g in v (the Sylvester matrix where the lower + degree is one), the greatest common divisors of the rows and columns divided out first, and these divisors: D + times their product is the resultant times a power of a leading coefficient, as in StructuralIdentifiability.jl.""" + if _deg(f, v) > _deg(g, v): + f, g = g, f + df, dg = _deg(f, v), _deg(g, v) + zero = f.context().from_dict({}) + cf, cg = _coeffs(f, v), _coeffs(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)] + else: + n = df + dg + M = [[zero] * n for _ in range(n)] + for i in range(df): + for j in range(dg + 1): + M[i][i + j] = cg[j] + for i in range(dg): + for j in range(df + 1): + M[df + i][i + j] = cf[j] + removed = [] + for cells in [[(i, j) for j in range(n)] for i in range(n)] + [[(i, j) for i in range(n)] for j in range(n)]: + nz = [(i, j) for i, j in cells if not M[i][j].is_zero()] + if not nz: + continue + h = M[nz[0][0]][nz[0][1]] + for i, j in nz[1:]: + h = h.gcd(M[i][j]) + if not h.is_constant(): + for i, j in nz: + M[i][j] = M[i][j] // h + removed.append(h) + return _det(M), removed + + +def _subresultant1(f, g, v): + """(A, B): the first subresultant A v + B of f and g in v, of degrees at least two, a combination U f + V g.""" + m, n = _deg(f, v), _deg(g, v) + cf, cg = _coeffs(f, v), _coeffs(g, v) + zero = f.context().from_dict({}) + size = m + n - 2 + # the rows v^k f for k < n - 1 and v^k g for k < m - 1, the columns of the powers size .. 2 and then one power + rows = [(k, cf) for k in range(n - 1)] + [(k, cg) for k in range(m - 1)] + + 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] + out.append(_det([[entry(row, q) for q in powers] for row in rows])) + return out[0], out[1] + + +def _det(M): + """The determinant by expansion along the rows, the minors cached.""" + n = len(M) + cache = {} + one = M[0][0].context().from_dict({(0,) * M[0][0].context().nvars(): 1}) + + def minor(row, cols): + if row == n: + return one + key = (row, cols) + if key in cache: + return cache[key] + out, sign = None, 1 + for j in range(n): + if cols >> j & 1: + continue + if not M[row][j].is_zero(): + t = M[row][j] * minor(row + 1, cols | 1 << j) + t = t if sign > 0 else -t + out = t if out is None else out + t + sign = -sign + out = out if out is not None else one - one + cache[key] = out + return out + return minor(0, 0) + + +def split(P, R): + """{(monomial in the derivatives of the observables and the known states): {monomial in the coordinates: integer}} + of a relation.""" + npar = len(R.params) + out = {} + for m, c in P.to_dict().items(): + out.setdefault(tuple(m[npar:]), {})[tuple(m[:npar])] = int(c) + return out + + +def relation_projection(rel, R, P): + """(base, support, coefficients) of the relation P on the base functions of a projection of ioproj, the + derivatives y_r^(k), k <= ms[r], and the known states read: the orders and the number of the base functions as + ioproj.series_rank() reads them, the support in the exponents of that base and per monomial {monomial in the + parameters: integer}; None where P reads a known state outside the base.""" + terms = split(P, R) + ny = len(rel.y) + ms = [-1] * ny + for m in terms: + for r in range(ny): + for k in range(R.order + 1): + if m[2 * len(R.unknown) + len(R.known) + r * (R.order + 1) + k]: + ms[r] = max(ms[r], k) + inputs = rel.inputs(max(ms)) + # what ioproj.series_rank() reads of a projection: the orders and the number of base functions, no symbolic + # derivatives + pr = types.SimpleNamespace(ms=ms, nb=sum(k + 1 for k in ms if k >= 0) + len(inputs), mons=None) + off_known = 2 * len(R.unknown) + support, coefs = [], [] + for m, co in terms.items(): + if any(m[:off_known]): + return None + e = [] + 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)])) + 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] + support.append(tuple(e)) + coefs.append(co) + pr.mons = support + return pr, support, coefs + + +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)) + return ref, order + + +def gradient_select(coefs, ref, order, nparams, p, rng): + """The coefficients over the reference whose gradients in the parameters raise the rank at a random point modulo p, + fewest terms first, then as many more that are no constant multiple of the reference.""" + theta = [rng.randrange(1, p) for _ in range(nparams)] + + def val(co, th): + s = 0 + for m, c in co.items(): + t = c % p + for x, k in zip(th, m): + if k: + t = t * pow(x, k, p) % p + s += t + return s % p + + def grad(co): + out = [] + for v in range(nparams): + d = {} + for m, c in co.items(): + if m[v]: + mm = list(m) + mm[v] -= 1 + 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 [], [] + inv = pow(r0, -1, p) + basis, piv, first, rest = [], [], [], [] + for j in order: + cj, dj = val(coefs[j], theta), grad(coefs[j]) + # the gradient of c_j / c_ref + row = [(a * r0 - cj * b) * inv * inv % p for a, b in zip(dj, dr)] + if not any(row): + continue + for b, c in zip(basis, piv): + if row[c]: + row = [(x - row[c] * y) % p for x, y in zip(row, b)] + c = next((i for i, x in enumerate(row) if x), None) + if c is not None: + ic = pow(row[c], -1, p) + basis.append([x * ic % p for x in row]) + piv.append(c) + first.append(j) + else: + rest.append(j) + return first, first + rest[:len(first)] + + +def eliminate_relations(rel, rng, terms=math.inf): + """The relations of the observables by elimination, {"relations": {observable: flint polynomial}, "orders", + "ring", "steps", "states"}; a ValueError where a polynomial of the elimination has more than `terms` terms.""" + el = Eliminator(rel, rng, terms) + eqs, orders = el.run() + return {"relations": eqs, "orders": orders, "ring": el.R, "steps": el.steps, "states": el.states} diff --git a/src/symident/detection/fewcoef.py b/src/symident/detection/fewcoef.py new file mode 100644 index 0000000..da54643 --- /dev/null +++ b/src/symident/detection/fewcoef.py @@ -0,0 +1,449 @@ +"""A few coefficients of a projection past ioproj.TERMS, verified (docs/method/global.rst, "The exact count"): the +relation is shown to exist by kernels at random points modulo random primes, the coefficients over a coefficient that is +a monomial in the parameters are Laurent polynomials, interpolated by Ben-Or and Tiwari and checked at the same random +points, each step with the error bound of the Schwartz-Zippel lemma.""" + +import itertools +import math + +import numpy as np +import sympy as spy + +from .. import _core +from ..gfp import PRIMES, all_primes, rref_modp, sieve +from . import ioproj, work + +# the primes of the trials: uniform among the primes from _LOW to the largest prime of the engine arithmetic +_LOW = 1 << 29 +# trials at random points, points per axis line at the start and at most, candidates per parameter +_TRIALS = 5 +_AXIS = 24 +_AXIS_MAX = 96 +_CANDIDATES = 3 +# the most terms of an interpolated coefficient and candidate exponent vectors of one +_TERMS = 40 +_BOX = 200000 + + +def _is_prime(n): + """Miller-Rabin with the first twelve prime bases, deterministic below 3.3e24.""" + if n < 2: + return False + small = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] + if n in small: + return True + if any(n % b == 0 for b in small): + return False + d, s = n - 1, 0 + while not d % 2: + d, s = d // 2, s + 1 + for b in small: + x = pow(b, d, n) + if x in (1, n - 1): + continue + for _ in range(s - 1): + x = x * x % n + if x == n - 1: + break + else: + return False + return True + + +def random_prime(rng, hi): + """A prime uniform among those from _LOW to `hi`: uniform integers until one is prime.""" + while True: + n = rng.randrange(_LOW, hi + 1) + if _is_prime(n): + return n + + +def primes_at_least(lo, hi): + """A lower bound on the number of primes from lo to hi: pi(x) > x / ln x for x >= 17 and pi(x) < 1.25506 x / ln x + for x > 1 (Rosser and Schoenfeld 1962).""" + return hi / math.log(hi) - 1.25506 * (lo - 1) / math.log(lo - 1) + + +class _Oracle: + """The kernel vector of the projection at a parameter point modulo p, normalized at the last monomial of the + support, cached per point; None where the kernel is not one vector with that entry free.""" + + def __init__(self, pr): + self.pr, self.cache, self.calls = pr, {}, 0 + + def __call__(self, theta, p): + key = (tuple(int(x) % p for x in theta), p) + if key not in self.cache: + self.calls += 1 + self.cache[key] = self.pr.vector(list(key[0]), p) + return self.cache[key] + + +def _pure(poly): + """The exponent of a polynomial (coefficients lowest first) with one term, None otherwise.""" + nz = [i for i, c in enumerate(poly) if c] + return nz[0] if len(nz) == 1 else None + + +def _axis(orc, beta, p, npts, end): + """Per parameter v the points t and the kernel vectors on the line beta with theta_v = t; None past the work + count `end` (work.ticks()) or where the kernel is missing too often.""" + lines = [] + for v in range(len(beta)): + ts, vals, t = [], [], 0 + while len(ts) < npts: + t += 1 + if t > 3 * npts + 10 or work.ticks() > end: + return None + x = list(beta) + x[v] = t + vec = orc(x, p) + if vec is not None: + ts.append(t) + vals.append(vec) + lines.append((ts, np.array(vals, dtype=np.int64))) + return lines + + +def _ranges(lines, p, r0, entries, beta=None): + """{entry: per parameter (lowest, highest) exponent} of the entries over entry r0 that are Laurent polynomials on + every axis line; with the number of entries found on every line that are not, and with `beta`, the point of the + lines, {entry: gradient there}.""" + out, other, grads = {}, 0, {} + for e in entries: + rg, gr = [], [] + for ts, vals in lines: + den = vals[:, r0] + if not den.all(): + break + w = [int(a) * pow(int(b), -1, p) % p for a, b in zip(vals[:, e], den)] + got = ioproj.ratrec1(ts, w, p) + if got is None: + break + a = _pure(got[1]) + nz = [i for i, c in enumerate(got[0]) if c] + if a is None: + other += 1 + break + if not nz: + break + rg.append((nz[0] - a, nz[-1] - a)) + if beta is not None: + # d/dt N(t) t^-a at t = beta_v + t0 = beta[len(rg) - 1] + N = sum(c * pow(t0, i, p) for i, c in enumerate(got[0])) % p + dN = sum(i * c * pow(t0, i - 1, p) for i, c in enumerate(got[0]) if i) % p + gr.append((dN * t0 - a * N) * pow(pow(t0, a + 1, p), -1, p) % p) + else: + out[e] = rg + grads[e] = gr + return (out, other, grads) if beta is not None else (out, other) + + +def _monomial_ref(lines, p, r): + """The entries whose coefficient is a monomial in the parameters, least degree first: on every axis line the + quotient by the normalizing entry has a numerator with one term, and every other entry over it is a Laurent + polynomial there.""" + cands = [] + for e in range(r): + tot = 0 + for ts, vals in lines: + got = ioproj.ratrec1(ts, [int(x) for x in vals[:, e]], p) + a = None if got is None else _pure(got[0]) + if a is None: + break + tot += a + else: + cands.append((tot, e)) + out = [] + for _, e in sorted(cands)[:8]: + found, other = _ranges(lines, p, e, range(r)) + if not other and len(found) > 1: + out.append((e, found)) + return out + + +class _BT: + """The kernel vectors at the points c b^k modulo q of Ben-Or and Tiwari, b the first primes, kept for every + entry.""" + + def __init__(self, orc, n, q, rng): + self.orc, self.q, self.rng, self.n = orc, q, rng, n + self.bases = sieve(n) + self._start() + + def _start(self): + self.c = [self.rng.randrange(1, self.q) for _ in range(self.n)] + self.pts, self.vecs = [], [] + + def extend(self, m, end): + """At least m points; False past the work count `end` or where the kernel is missing three times.""" + restarts = 0 + while len(self.vecs) < m: + if work.ticks() > end: + return False + k = len(self.vecs) + x = [ci * pow(b, k, self.q) % self.q for ci, b in zip(self.c, self.bases)] + v = self.orc(x, self.q) + if v is None: + restarts += 1 + if restarts > 2: + return False + self._start() + continue + self.pts.append(x) + self.vecs.append(v) + return True + + def sequence(self, e, r0, low): + """The values of entry e over entry r0 at the points, times theta^-low; None where entry r0 is zero.""" + q = self.q + out = [] + for x, v in zip(self.pts, self.vecs): + if not v[r0]: + return None + s = int(v[e]) * pow(int(v[r0]), -1, q) % q + for xi, L in zip(x, low): + if L: + s = s * pow(xi, -L, q) % q + out.append(s) + return out + + def solve(self, e, r0, rg): + """{exponents: residue} of the Laurent polynomial of entry e over entry r0 with the exponent ranges rg; None + where the terms are not found.""" + q = self.q + low = [L for L, _ in rg] + seq = self.sequence(e, r0, low) + if seq is None or 2 * int(_core.sym_b_morder(seq, q)) >= len(seq): + return None + cand = np.array(list(itertools.product(*[range(H - L + 1) for L, H in rg])), dtype=np.int64).reshape(-1, self.n) + res = _core.sym_mono_residues(cand, self.bases, q) + got = _core.sym_sparse_poly(seq, cand, res, q) + if got.get("status") != "ok": + return None + exps = np.asarray(got["exps"], dtype=np.int64).reshape(-1, self.n) + out = {} + for m, a in zip(exps, np.atleast_1d(got["coeffs"])): + m = tuple(int(x) for x in m) + shift = math.prod(pow(ci, k, q) for ci, k in zip(self.c, m)) % q + out[tuple(k + L for k, L in zip(m, low))] = int(a) * pow(shift, -1, q) % q + return out + + +def _lift(per_prime, primes): + """{exponents: Fraction} from the residues per prime, None where the supports differ or a coefficient has no + bounded rational.""" + keys = sorted(per_prime[0]) + if any(sorted(d) != keys for d in per_prime[1:]): + return None + got = ioproj._ratrec([[d[k] for k in keys] for d in per_prime], primes) + return None if got is None else dict(zip(keys, got)) + + +def _value(co, theta, q): + """The Laurent polynomial {exponents: Fraction} at theta modulo q; None where a denominator is zero there.""" + s = 0 + for m, c in co.items(): + if not c.denominator % q: + return None + t = c.numerator % q * pow(c.denominator, -1, q) % q + for x, k in zip(theta, m): + if k: + t = t * pow(int(x), k, q) % q + s += t + return s % q + + +def _gradient(co, theta, q): + """The gradient of the Laurent polynomial {exponents: Fraction} at theta modulo q; None entries as _value().""" + out = [] + for v in range(len(theta)): + d = {} + for m, c in co.items(): + if m[v]: + mm = list(m) + mm[v] -= 1 + d[tuple(mm)] = d.get(tuple(mm), 0) + c * m[v] + out.append(_value(d, theta, q) if d else 0) + return out + + +def _rank_select(found, order, n, q, rng): + """The entries of `order` whose gradients raise the rank at a random point modulo q, then as many more.""" + theta = [rng.randrange(1, q) for _ in range(n)] + basis, piv, first = [], [], [] + for e in order: + row = _gradient(found[e], theta, q) + if any(x is None for x in row): + continue + for b, c in zip(basis, piv): + if row[c]: + row = [(x - row[c] * y) % q for x, y in zip(row, b)] + c = next((j for j, x in enumerate(row) if x), None) + if c is not None: + inv = pow(row[c], -1, q) + 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)] + + +class _Bounds: + """Degree and height bounds of the maximal minors of the matrix of the monomials of the projection at r random + states, the denominators of each row cleared (docs/method/global.rst, "The exact count").""" + + def __init__(self, pr): + J = pr.base.J + funcs = pr.base.funcs + + def deg(P): + return max((sum(m) for m in P.itermonoms()), default=0) + + def height(P): + # log2 of the 1-norm of P times the least common multiple of the denominators of the coefficients + dens = [int(c.denominator) for c in P.itercoeffs()] + L = math.lcm(*dens) if dens else 1 + return math.log2(max(1, sum(abs(int(c.numerator) * (L // int(c.denominator))) for c in P.itercoeffs()))) + + dN = [deg(f.numer) for f in funcs] + hN = [height(f.numer) for f in funcs] + used = sorted({k for f in funcs for k, _ in f.exps}) + dF = {k: deg(J.fac[k]) for k in used} + hF = {k: height(J.fac[k]) for k in used} + 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.rows_degree = sum(dF.values()) + + def trial(self, extra_degree=0, extra_height=0.0, hi=None): + """The probability that one trial passes where the claim is false: a maximal minor, or a minor times the + candidate less another, is zero at the random point modulo a random prime from _LOW to hi.""" + hi = hi or max(PRIMES) + q = _LOW + accept = 1 - (self.r + 6) * self.rows_degree / (q - 1) + bad = math.ceil((self.height + extra_height + 1) / math.log2(_LOW)) + return (self.degree + extra_degree) / ((q - 1) * accept) + bad / primes_at_least(_LOW, hi) + + +def verified_functions(series, syms, large, cap, rng, log): + """{"functions", "exist", "checks", "why", ...}: for the first projection of `large` ({"profile", "observable", + "support"} from fieldproof), the coefficients over one that is a monomial in the parameters, interpolated as Laurent + polynomials and verified, as many as raise the rank of their gradients and as many more, within `cap` entries of + 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) + 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] + params = [syms[k] for k in idx] + n = len(idx) + big = sorted(large, key=lambda g: len(g["support"]))[0] + pr = ioproj.Projection.output(rel, big["profile"], big["observable"], pos, rng) + if pr is None: + out["why"] = "the projection is not rebuilt" + return out + pr.mons = [tuple(m) for m in big["support"]] + r = len(pr.mons) + out["terms"] = r + orc = _Oracle(pr) + p = all_primes()[0] + + def stop(why): + out["why"] = why + out["kernels"] = orc.calls + log.append(f"projection of {r} terms: {why}") + return out + + # the trajectory has the one relation: rank r - 1 of the Taylor coefficients at one point, exact + rk = ioproj.series_rank(rel, pr, pr.mons, syms, rng, p) + if rk != r - 1: + return stop(f"rank {rk} of {r} terms along the trajectory") + # the axis lines through one point: a coefficient that is a monomial, and the exponent ranges of the others + beta = [rng.randrange(1, p) for _ in range(n)] + npts, ref = _AXIS, [] + while not ref: + lines = _axis(orc, beta, p, npts, end) + if lines is None: + return stop(f"the axis lines reached the cap of {cap:,} matrix entries") + ref = _monomial_ref(lines, p, r) + if not ref and npts >= _AXIS_MAX: + return stop(f"no coefficient is a monomial in the parameters on axis lines of {npts} points") + npts *= 2 + r0, _ = ref[0] + ranges, _, grads = _ranges(lines, p, r0, range(r), beta) + # 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)) + # 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] + if not batch: + return stop(f"the coefficients found raise the rank to {len(first)} of {target}") + tried += len(batch) + while True: + if not all(bt.extend(need, end) for bt in bts.values()): + return stop(f"the points of the interpolation reached the cap of {cap:,} matrix entries") + per = {e: [bt.solve(e, r0, ranges[e]) for bt in bts.values()] for e in batch} + done = [e for e in batch if all(g is not None for g in per[e])] + if len(done) == len(batch) or need >= 2 * _TERMS + 2: + break + need = min(2 * need, 2 * _TERMS + 2) + for e in done: + got = _lift(per[e], list(bts)) + if got is None and len(bts) < 3: + q = all_primes()[2] + bts[q] = _BT(orc, n, q, rng) + if not bts[q].extend(need, end): + return stop(f"the points of the interpolation reached the cap of {cap:,} matrix entries") + if got is None and len(bts) == 3: + more = bts[all_primes()[2]].solve(e, r0, ranges[e]) + got = None if more is None else _lift(per[e][:2] + [more], list(bts)) + if got: + found[e] = got + first, pins = _rank_select(found, [e for e in order if e in found], n, p, rng) + # the trials: the kernel at a random point modulo a random prime is one vector, and each function is the + # coefficient there + bounds = _Bounds(pr) + hi = max(PRIMES) + for _ in range(_TRIALS): + q = random_prime(rng, hi) + theta = [rng.randrange(1, q) for _ in range(n)] + if work.ticks() > end: + return stop(f"the trials reached the cap of {cap:,} matrix entries") + v = pr.vector(theta, q) + if v is None or not v[r0]: + return stop("the kernel at a random point modulo a random prime is not one vector") + inv = pow(int(v[r0]), -1, q) + for e in pins: + if _value(found[e], theta, q) != int(v[e]) * inv % q: + return stop(f"coefficient {e} differs from the kernel at a random point") + 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)) + # 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)] + extra_d = max(max(sum(k + b for k, b in zip(m, a)) for m in co), sum(a), 1) + extra_h = math.log2(sum(abs(c.numerator * (L // c.denominator)) for c in co.values()) + L) + 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) + 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 95ddfbe..fc6b5d4 100644 --- a/src/symident/detection/fiber.py +++ b/src/symident/detection/fiber.py @@ -1,7 +1,6 @@ """The number of parameter values with the output of a generic one: a count of discrete symmetries.""" import os -import subprocess import tempfile import sympy as spy @@ -29,20 +28,20 @@ def output_coefficients(f, g, ic, order): return out -def _msolve_degree(eqs, names, p, timeout): - """(dimension, degree) of the ideal of `eqs` over GF(p) from msolve, or None on failure.""" +def _msolve_degree(eqs, names, p): + """(dimension, degree) of the ideal of `eqs` over GF(p) from msolve, or None on failure or a system past the caps + of msolve.""" import ast from ..sym.msolve import _msolve_binary + from . import work + if work.msolve_too_large(names, eqs): + return None 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: fh.write(", ".join(names) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") - try: - r = subprocess.run([_msolve_binary(), "-f", fi, "-o", fo, "-P", "1"], capture_output=True, - text=True, timeout=timeout) - except subprocess.TimeoutExpired: - return None + r = work.run_msolve([_msolve_binary(), "-f", fi, "-o", fo, "-P", "1"]) txt = "" if os.path.exists(fo): with open(fo) as fh: @@ -55,7 +54,7 @@ def _msolve_degree(eqs, names, p, timeout): return (0, int(data[1][2])) -def solution_count(f, g, ic, coords, order, p=1000003, timeout=600): +def solution_count(f, g, ic, coords, order, p=1000003): """{"count", "order", "prime"} of points over GF(p) sharing the output coefficients of a random one, or None.""" try: eqs, names = _fiber_equations(f, g, ic, coords, order, p) @@ -64,7 +63,7 @@ def solution_count(f, g, ic, coords, order, p=1000003, timeout=600): return None if eqs is None: return None - out = _msolve_degree(eqs, names, p, timeout) + out = _msolve_degree(eqs, names, p) if out is None or out[1] is None: return None return {"count": out[1], "order": int(order), "prime": int(p)} @@ -102,4 +101,3 @@ def _fiber_equations(f, g, ic, coords, order, p): # msolve reads no brackets: the saturation as an expanded polynomial eqs.append(str(spy.expand(spy.Symbol(w) * sat - 1)).replace("**", "^").replace(" ", "")) return eqs, names + [w] - diff --git a/src/symident/detection/fieldproof.py b/src/symident/detection/fieldproof.py new file mode 100644 index 0000000..8c43d7f --- /dev/null +++ b/src/symident/detection/fieldproof.py @@ -0,0 +1,1880 @@ +"""The exact fiber of discrete(): L = Q(c)(alpha) with prod_g (Z - g(alpha)) over Q(c), Q(c) the field of the output +coefficients, proven by identities of rational functions (docs/method/global.rst, "The exact count").""" + +import itertools +import math +import pickle +import random +import re +import sys +import time +from fractions import Fraction + +import numpy as np +import sympy as spy + +from .. import _core, session +from ..gfp import all_primes, rref_modp +from . import ioproj, work + +# the largest number of unknown coefficients of a rational expression in the output coefficients +_UNKNOWNS = 1000 +# the terms of a function evaluated in Python, more in C++ +_SMALL_TERMS = 24 +# the largest number of monomials of an input-output relation, and of unknowns of a rational function interpolated +_RELATION = 300 +_INTERP = 3600 +# the monomials of the state relations tried before the input-output relations +_SMALL = 40 +# the share of the cap of the search left where the model has no polynomial input-output relations +_WITHOUT_RELATIONS = 1 / 15 +# the monomials of the dense relations tried before the projections, and the share of the cap of all relations +_FIRST = 120 +_SHARE = 0.75 +# the largest number of proven functions in a small system +_SUBSYSTEM = 8 +# the share of the cap of the small dense relations of a state or of the observables +_DENSE = 0.1 +# the steps along a chain of known states that the relations keep +_CHAIN = 8 +# the largest group whose generators are expanded +_GROUP = 8 + +# the _Var of each target function, and the _Relations of each series, built once +_TARGETS = {} +_REL = {} + + +class _Factored: + """Quotients (N, {k: e}) = N / prod_k F_k^e of polynomials in the coordinates over a shared list F of monic + factors, without gcds: a sum takes the largest power of each factor, so that the denominators grow linearly + along a recursion.""" + + def __init__(self, R, cs, params): + self.R, self.fac, self.at, self._pw = R, [], {}, {} + self.gens = R.gens + self.pidx = [cs.index(s_) for s_ in params] + + def const(self, c): + c = Fraction(c) + return (self.R.ground_new(self.R.domain.convert(c.numerator) / self.R.domain.convert(c.denominator)), {}) + + def zero(self): + return (self.R.zero, {}) + + def _poly(self, terms, idx): + out = self.R.zero + for m, c in terms: + t = self.const(c)[0] + for j, e in zip(idx, m): + if e: + t = t * self.gens[j] ** e + out = out + t + return out + + def coef(self, terms): + """A polynomial in the parameters, [(exponents, Fraction)].""" + return (self._poly(terms, self.pidx), {}) + + def start(self, num, den): + """num / den for polynomials {exponents: Fraction} in the coordinates; None where den is zero.""" + idx = range(len(self.gens)) + d = self._poly(den.items(), idx) + return None if not d else self.quo(self._poly(num.items(), idx), d) + + def factor(self, P): + P = P.monic() + if P not in self.at: + self.at[P] = len(self.fac) + self.fac.append(P) + return self.at[P] + + def power(self, k, e): + if (k, e) not in self._pw: + self._pw[(k, e)] = self.fac[k] ** e + return self._pw[(k, e)] + + def quo(self, n, d): + """n / d for polynomials, d nonzero.""" + c = self.R.domain.quo(self.R.domain.one, d.LC) + return (n * c, {}) if d.is_ground else (n * c, {self.factor(d): 1}) + + def mul(self, a, b): + if not a[0] or not b[0]: + return self.zero() + e = dict(a[1]) + for k, x in b[1].items(): + e[k] = e.get(k, 0) + x + return (a[0] * b[0], e) + + def scale(self, a, c): + return (a[0] * self.const(c)[0], a[1]) + + def total(self, terms): + """The sum of the quotients over the largest power of each factor.""" + terms = [t for t in terms if t[0]] + T = {} + for _, e in terms: + for k, x in e.items(): + T[k] = max(T.get(k, 0), x) + out = self.R.zero + for n, e in terms: + for k, x in T.items(): + if x - e.get(k, 0): + n = n * self.power(k, x - e.get(k, 0)) + out = out + n + return (out, T) if out else self.zero() + + def pole(self, b): + return not b[0] + + def div(self, a, b): + """a / b for b with a nonzero numerator: the numerator of b joins the factors.""" + num, ea = self.quo(a[0], b[0]) + for k, x in a[1].items(): + ea[k] = ea.get(k, 0) + x + for k, x in b[1].items(): + if ea.get(k, 0) >= x: + ea[k] -= x + else: + num = num * self.power(k, x - ea.get(k, 0)) + ea[k] = 0 + return (num, {k: x for k, x in ea.items() if x}) + + +class _Modular: + """The arithmetic of _Taylor modulo a prime p below 2^31 at many points of the coordinates at once, as int64 + arrays; `bad` marks the points at a pole.""" + + def __init__(self, pts, p, cs, params): + self.X, self.p = np.asarray(pts, dtype=np.int64) % p, p + self.n = len(self.X) + self.pidx = [cs.index(s_) for s_ in params] + self.bad = np.zeros(self.n, dtype=bool) + self._pw = {} + + def const(self, c): + c = Fraction(c) + return np.full(self.n, c.numerator % self.p * pow(c.denominator, -1, self.p) % self.p, dtype=np.int64) + + def zero(self): + return np.zeros(self.n, dtype=np.int64) + + def _xpow(self, j, e): + if (j, e) not in self._pw: + self._pw[(j, e)] = ioproj._pow(self.X[:, j], e, self.p) + return self._pw[(j, e)] + + def _poly(self, terms, idx): + out = self.zero() + for m, c in terms: + t = self.const(c) + for j, e in zip(idx, m): + if e: + t = t * self._xpow(j, e) % self.p + out = (out + t) % self.p + return out + + def coef(self, terms): + return self._poly(terms, self.pidx) + + def start(self, num, den): + idx = range(self.X.shape[1]) + d = self._poly(den.items(), idx) + self.bad |= d == 0 + d[d == 0] = 1 + return self._poly(num.items(), idx) * ioproj._inv(d, self.p) % self.p + + def mul(self, a, b): + return a * b % self.p + + def scale(self, a, c): + return a * self.const(c) % self.p + + def total(self, terms): + out = self.zero() + for t in terms: + out = (out + t) % self.p + return out + + def pole(self, b): + self.bad |= b == 0 + return bool(self.bad.all()) + + def div(self, a, b): + b = b.copy() + b[b == 0] = 1 + return a * ioproj._inv(b, self.p) % self.p + + +class _Taylor: + """The Taylor coefficients of the observables at the start of the first segment of a condition, in the + arithmetic `ar` (_Factored or _Modular), by the recursion D(x) x' = N(x) order by order, each monomial in the + states from one of lower degree: no symbolic derivative and no gcd.""" + + def __init__(self, series, ar, pi, order): + self.ok, self.ar = False, ar + part = series.parts[pi] + seg = part["segs"][0] + ns = len(part["st"]) + kser = series._known_series(pi, order) + + def split(P): + # {state exponents: coefficient, a polynomial in the parameters} + out = {} + 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] + + 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:] + add(low) + at[m] = len(mons) + mons.append(m) + parent.append((at[low], v)) + for P in polys: + for m in P: + add(m) + self.polys, self.at = polys, at + X = [] + for i in range(ns): + if i in kser: + X.append([ar.const(c) for c in kser[i]]) + continue + x0 = ar.start(seg["x0"][i][1], seg["x0"][i][2]) + if x0 is None: + return + X.append([x0] + [ar.zero() for _ in range(order)]) + ser = [[ar.const(1)] + [ar.zero() for _ in range(order)]] + [[] for _ in mons[1:]] + Dser = {i: [] for i in range(ns) if i not in kser} + for k in range(order + 1): + for j in range(1, len(mons)): + pj, v = parent[j] + ser[j].append(ar.total([ar.mul(ser[pj][l], X[v][k - l]) for l in range(k + 1)])) + if k == order: + break + for i in Dser: + Nk = self.value(2 * i, ser, k) + Dser[i].append(self.value(2 * i + 1, ser, k)) + if k == 0 and ar.pole(Dser[i][0]): + return + rest = ar.total([ar.scale(ar.mul(Dser[i][l], X[i][k + 1 - l]), -(k + 1 - l)) for l in range(1, k + 1)]) + X[i][k + 1] = ar.div(ar.total([Nk, rest]), ar.scale(Dser[i][0], k + 1)) + self.y = [] + for r in range(len(seg["G"])): + M = [self.value(2 * ns + 2 * r, ser, k) for k in range(order + 1)] + E = [self.value(2 * ns + 2 * r + 1, ser, k) for k in range(order + 1)] + if ar.pole(E[0]): + return + y = [] + for k in range(order + 1): + rest = ar.total([ar.scale(ar.mul(E[l], y[k - l]), -1) for l in range(1, k + 1)]) + y.append(ar.div(ar.total([M[k], rest]), E[0])) + self.y.append(y) + self.ok = True + + def value(self, q, ser, k): + return self.ar.total([self.ar.mul(c, ser[self.at[m]][k]) for m, c in self.polys[q].items()]) + + +def output_rows(series): + """The indices of the rows of Series._outputs that are Taylor coefficients of an observable at the start of an + experiment: the first segment of each condition, without the copies that start free.""" + rows, i = [], 0 + for part in series.parts: + for j, seg in enumerate(part["segs"]): + for _ in seg["labels"]: + if j == 0 and not seg.get("free") and seg.get("on") is None: + rows.append(i) + i += 1 + return rows + + +def _rat_recon(a, m): + """The rational number n/d with |n|, d <= sqrt(m/2) and n = a d mod m, None where there is none.""" + a %= m + bound = math.isqrt(m // 2) + r0, r1, s0, s1 = m, a, 0, 1 + while r1 > bound: + q = r0 // r1 + r0, r1 = r1, r0 - q * r1 + s0, s1 = s1, s0 - q * s1 + if s1 == 0 or abs(s1) > bound or math.gcd(r1, abs(s1)) != 1: + return None + return Fraction(r1, s1) + + +def _poly_terms(e, syms): + """The terms (exponents, numerator, denominator) of a polynomial in `syms` with rational coefficients.""" + P = spy.Poly(e, *syms, domain="QQ") + return [(m, int(c.numerator), int(c.denominator)) for m, c in P.terms()] + + +def _eval_terms(terms, x, p): + out = 0 + for m, a, b in terms: + v = a * pow(b, -1, p) % p + for xi, e in zip(x, m): + if e: + v = v * pow(xi, e, p) % p + out += v + return out % p + + +class _Outputs: + """The output coefficients used: values modulo p at points, and exact values as quotients in the coordinates.""" + + def __init__(self, series, orders): + self.series = series + self.rows = output_rows(series) + self.orders = orders + self.order = max(orders[i] for i in self.rows) if self.rows else 0 + self.index = [(i, k) for i in self.rows for k in range(orders[i] + 1)] + self._exact = {} + self.where, i = {}, 0 + for pi, part in enumerate(series.parts): + for seg in part["segs"]: + for r in range(len(seg["labels"])): + self.where[i] = (pi, r) + i += 1 + + def _taylor(self, ar, order): + """{index: value} of the coefficients up to `order` in the arithmetic `ar`; None at a pole.""" + taylor, out = {}, {} + for j, (i, k) in enumerate(self.index): + if k > order: + continue + pi, r = self.where[i] + if pi not in taylor: + taylor[pi] = _Taylor(self.series, ar, pi, order) + if not taylor[pi].ok: + return None + out[j] = taylor[pi].y[r][k] + return out + + def mod_many(self, pts, p): + """The coefficients at the points modulo p, one row each, and the rows at no pole.""" + ar = _Modular(pts, p, self.series.cs, self.series.params) + got = self._taylor(ar, self.order) + if got is None: + return None, np.zeros(len(pts), dtype=bool) + return np.array([got[j] for j in range(len(self.index))], dtype=np.int64).T.reshape(len(pts), -1), ~ar.bad + + def mod(self, x, p): + vals, ok = self.mod_many([x], p) + return None if not ok[0] else [int(v) for v in vals[0]] + + def exact(self, order): + """(ring, factors, {index: quotient}) of the coefficients up to `order` as _Factored quotients in the + coordinates; None at a pole.""" + if order not in self._exact: + R = spy.ring(",".join(f"t{i}" for i in range(len(self.series.cs))), spy.QQ)[0] + F = _Factored(R, self.series.cs, self.series.params) + out = self._taylor(F, order) + self._exact[order] = None if out is None else (R, F, out) + return self._exact[order] + + +def generators(grp, syms): + """(alpha, F, traces, others): a function alpha of the coordinates with |G| distinct images under the group + `grp` (maps {symbol: expr}, the identity first), the functions F to prove in the field of the outputs, the + coordinates the group fixes and the coefficients of prod_g (Z - g(alpha)), the traces sum_g g(theta_i) of the + moved coordinates, which may help, and the other coordinates, to prove in F(alpha); None without alpha.""" + k = len(grp) + imgs = {s: [spy.cancel(g.get(s, s)) for g in grp] for s in syms} + fixed = [s for s in syms if all(spy.cancel(v - s) == 0 for v in imgs[s])] + if k == 1: + return None, list(syms), [], [] + moved = [s for s in syms if s not in fixed] + + def images(a): + return [spy.cancel(a.xreplace({s: g.get(s, s) for s in syms})) for g in grp] + + 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)] + 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 + aims = images(alpha) if not isinstance(alpha, spy.Symbol) else imgs[alpha] + # prod_g (Z - g(alpha)) over the rational function field of the coordinates, constant term first; maps over + # Q(i) give coefficients over Q(i), which must lie in Q(theta) + K = spy.polys.fields.field(",".join(str(s) for s in syms), spy.QQ)[0] + gauss = any(v.has(spy.I) for vs in imgs.values() for v in vs) + Kg = spy.polys.fields.field(",".join(str(s) for s in syms), spy.QQ_I)[0] if gauss else K + + 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)] + P = [over_q(c) for c in P] + if any(c is None for c in P): + return None + # the traces sum_g g(theta_i) of the moved coordinates, which F(alpha) needs besides the coefficients + traces = [over_q(sum((Kg.from_expr(v) for v in imgs[s]), Kg.zero)) for s in moved] + 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_]] + return alpha, [f.as_expr() for f in F], [t.as_expr() for t in traces], [s for s in moved if s != alpha] + + +def _monomials(R, d): + return [m for t in range(d + 1) for m in _exps(R, t)] + + +def _parents(mons): + """For each monomial but the first (the constant), the index of a monomial of one degree less and the variable + that multiplies it.""" + at = {m: i for i, m in enumerate(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)) + return out + + +def _mono_values(vals, parents, p): + out = [1] + for par in parents[1:]: + out.append(out[par[0]] * vals[par[1]] % p) + return out + + +def _exps(R, t): + if R == 0: + return [()] if t == 0 else [] + return [(a,) + rest for a in range(t, -1, -1) for rest in _exps(R - 1, t - a)] + + +class _Pool: + """Random points modulo each prime with the output coefficients there, drawn once and shared.""" + + def __init__(self, outs, n, rng): + self.outs, self.n, self.rng, self.pts = outs, n, rng, {} + + def get(self, p, m): + pts = self.pts.setdefault(p, []) + while len(pts) < m: + xs = [[self.rng.randrange(1, p) for _ in range(self.n)] for _ in range(m - len(pts) + 4)] + vals, ok = self.outs.mod_many(xs, p) + if not ok.any(): + continue + pts += [(x, [int(v) for v in vals[k]]) for k, x in enumerate(xs) if ok[k]] + return pts[:m] + + +class _Var: + """A function known to lie in the field of the output coefficients: an output coefficient (index `c`) or a + function of the coordinates proven to lie there (`expr`).""" + + def __init__(self, name, c=None, expr=None, syms=()): + self.name, self.c, self.expr = name, c, expr + if expr is not None: + num, den = spy.fraction(spy.cancel(spy.together(expr))) + self.tn, self.td = _poly_terms(num, syms), _poly_terms(den, syms) + self.num, self.den = num, den + self.free = expr.free_symbols + + def value(self, x, c, p): + if self.c is not None: + return c[self.c] + key = (p, id(x)) + memo = self.__dict__.setdefault("memo", {}) + if key not in memo: + if len(self.tn) + len(self.td) > _SMALL_TERMS: + nv, dv = self._large_value(x, p) + else: + dv = _eval_terms(self.td, x, p) + nv = _eval_terms(self.tn, x, p) if dv else 0 + memo[key] = None if not dv else nv * pow(dv, -1, p) % p + return memo[key] + + 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)) + E, co, off = self._arr + res = self.__dict__.setdefault("_res", {}) + if p not in res: + res[p] = np.array([a % p * pow(b, -1, p) % p for a, b in co], dtype=np.int64) + nv, dv = _core.io_poly_eval(E, res[p], off, np.array([x], dtype=np.int64) % p, p, 1)[0] + 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.""" + target = _TARGETS.setdefault((f, tuple(syms)), _Var("f", expr=f, syms=syms)) + mons = mons or _monomials(len(W), d) + U = 2 * len(mons) + E = np.array(mons, dtype=np.int32).reshape(len(mons), len(W)) + primes = all_primes()[:3] + pts, basis, test = {}, None, {} + for p in primes: + fvs, vals = [], [] + for x, c in pool.get(p, U + 12): + fv = target.value(x, c, p) + v = [w.value(x, c, p) for w in W] + if fv is None or any(a is None for a in v): + continue + fvs.append(fv) + vals.append(v) + 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()) + 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) + ker = _core.io_kernel(np.ascontiguousarray(rows), p, ioproj._threads()) + piv, free = list(ker["pivots"]), list(ker["free"]) + if not free: + return None + key = (tuple(piv), tuple(free)) + basis = basis or key + if key != basis: + continue + pts[p] = [[int(x) for x in v] for v in ker["basis"]] + if len(pts) < len(primes): + return None + M = math.prod(pts) + p0, n = primes[0], len(mons) + for vi in range(len(basis[1])): + # a vector with B zero at a point is a relation among the variables, not an expression of f + if not sum(b_ * t for b_, t in zip(pts[p0][vi][n:], test[p0])) % p0: + continue + vec = [] + for j in range(U): + r = sum(pts[p][vi][j] * (M // p) * pow(M // p, -1, p) for p in pts) + q = _rat_recon(r % M, M) + if q is None: + break + vec.append(q) + if len(vec) == U: + got = _check(vec, mons, W, target, syms, outs) + if got is not None: + return got + return None + + +def _check(vec, mons, W, target, syms, outs): + """(A, B) of `vec` where A(W) den_f = num_f B(W) and B(W) != 0 hold as polynomials in the coordinates, over + shared factors of the denominators and without gcds; None otherwise.""" + n = len(mons) + terms = [m for m, q in zip(mons + mons, vec) if q] + used = sorted({i for m in terms for i, e in enumerate(m) if e}) + order = max([outs.index[W[i].c][1] for i in used if W[i].c is not None], default=0) + got = outs.exact(order) + if got is None: + return None + R, F, cs = got + tsym = dict(zip(syms, [spy.Symbol(f"t{i}") for i in range(len(syms))])) + + 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 = {} + + def power(i, e): + if (i, e) not in pw: + pw[(i, e)] = fr[i] if e == 1 else F.mul(power(i, e - 1), fr[i]) + return pw[(i, e)] + + def value(coefs): + out = [] + for m, q in zip(mons, coefs): + if not q: + continue + t = F.const(q) + for i in used: + if m[i]: + 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 + A = value(vec[:n]) + diff = F.total([F.mul(A, (ring(target.den), {})), F.scale(F.mul(B, (ring(target.num), {})), Fraction(-1))]) + if diff[0]: + return None + 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 text(vec[:n]), text(vec[n:]) + + +def _reynolds(grp, syms, degree): + """The sums over the group of the monomials of `degree` in the coordinates the group moves, one at a time.""" + moved = [s for s in syms if any(spy.cancel(g.get(s, s) - s) != 0 for g in grp)] + for m in itertools.combinations_with_replacement(moved, degree): + e = spy.prod(m) + h = spy.cancel(sum((e.xreplace({s: g.get(s, s) for s in syms}) for g in grp), spy.Integer(0))) + if not h.has(spy.I): + yield h + + +class _Relations: + """The linear relations over Q(theta) among the monomials phi_i in the derivatives of the observables and the + known inputs along the trajectory of the first condition (docs/method/global.rst, "The exact count"): the kernel of + the matrix of the Taylor coefficients of the phi_i, whose entries are polynomials in output coefficients.""" + + def __init__(self, series, syms): + self.ok = False + part = series.parts[0] + seg = part["segs"][0] + if seg.get("free") or seg.get("on") is not None: + return + st = list(part["st"]) + ns = len(st) + params = list(series.params) + known = set(part["known"]) + + 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} + obs = {i for M, E in seg["G"] for P in (M, E) for m in P for i in range(ns) if m[i]} + front = (set().union(*[reads(j) for j in keep]) | obs) & known if keep else obs & known + last = set() + for _ in range(_CHAIN): + new = front - keep + keep |= new + front = set().union(*[reads(j) for j in new]) & known if new else set() + last = new + cut = {j for j in last if reads(j) - keep} + kept = sorted(keep) + names = [str(st[j]) for j in kept] + [str(p) for p in params] + 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"]) + 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)] + + def poly(Pd): + out = self.R.zero + for m, c in Pd.items(): + t = self.R(spy.Rational(c.numerator, c.denominator)) + for g, e in zip(X + list(P), m): + if e: + t = t * g ** e + out = out + t + return out + + def quo(N, D): + if polynomial: + (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 + self.y = [quo(M, E) for M, E in seg["G"]] + self.X = X + self.read = sorted({i for j in range(ns) if j not in known and j in keep for i in known & reads(j)}) + self.known = sorted(known & keep) + self.series, self.part, self.ns = series, part, ns + self.syms = syms + self.ny = len(self.y) + self.observed = [] + self.ok = True + + def observe(self, i): + """State i joins the observables: the series of the state lies in the field of the outputs.""" + if i not in self.observed: + self.observed.append(i) + self.y.append(self.X[i]) + if hasattr(self, "_lie"): + self._lie.append([self.X[i]]) + + def lie(self, q): + return sum((q.diff(x) * fx for x, fx in zip(self.X, self.f) if x is not None), self.R.zero) + + def jets(self, ms): + """The symbolic derivatives of each observable r up to order ms[r], none for ms[r] < 0.""" + if not hasattr(self, "_lie"): + self._lie = [[y] for y in self.y] + ys = [] + for r, m in enumerate(ms): + d = self._lie[r] + while len(d) <= m: + d.append(self.lie(d[-1])) + ys.append(d[:m + 1]) + return ys + + def inputs(self, m): + """The known states read by the others and their derivatives along the known chain, up to order m.""" + out = list(self.read) + for i in self.read: + j = i + for _ in range(m): + nxt = [k for k in self.known if self.f[j] == self.X[k]] + if not nxt: + break + j = nxt[0] + if j not in out: + out.append(j) + return out + + +def _relations(series, syms): + """The _Relations of a series, built once: the derivatives and their compiled functions are shared.""" + key = (id(series), tuple(str(s_) for s_ in syms)) + if key not in _REL: + _REL[key] = (series, _Relations(series, syms)) + return _REL[key][1] + + +def _relation_matrix(rel, x, p, ms, degree, K): + S = ioproj.taylor_rows(rel, ms, dict(zip(rel.series.cs, x)), p, 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()) + return ser.T.tolist(), mons + + +def _kernel_canonical(M, p): + """(pivots, free, basis) of the kernel of M over GF(p), each basis vector the identity on the free columns.""" + M = np.array(M, dtype=np.int64) + work.tick(M.shape) + ker = _core.io_kernel(M, p, ioproj._threads()) + return tuple(ker["pivots"]), tuple(ker["free"]), [[int(x) for x in v] for v in ker["basis"]] + + +def _crt_rational(vals): + """{prime: residue} as a rational number by the Chinese remainder theorem, None without a bounded one.""" + M = math.prod(vals) + r = sum(v * (M // p) * pow(M // p, -1, p) for p, v in vals.items()) + return _rat_recon(r % M, M) + + +class _Samples: + """Points modulo each prime with the values of a vector function there, kept for every degree.""" + + def __init__(self, values, n, rng, primes): + self.values, self.n, self.rng, self.pts = values, n, rng, {p: [] for p in primes} + + def get(self, p, m, stop): + pts = self.pts[p] + while len(pts) < m: + if work.ticks() > stop: + return None + x = [self.rng.randrange(1, p) for _ in range(self.n)] + v = self.values(x, p) + if v is not None: + pts.append((x, v)) + return pts[:m] + + +def _polys_at_once(S, entries, scale, primes, stop, degrees=range(0, 12), box=None): + """{entry: (monomials, coefficients)}: polynomials of the least degree in `degrees` with the values of + `entries` (times scale(x, p) where given), one linear system per prime and degree for all of them; with `box`, + only the monomials whose exponent of variable i is at most box[i].""" + out = {} + for d in degrees: + todo = [e for e in entries if e not in out] + if not todo: + break + mons = _monomials(S.n, d) + if box is not None: + mons = [m for m in mons if all(e <= b for e, b in zip(m, box))] + U = len(mons) + if U > _INTERP: + break + par = _parents(mons) if box is None else None + sols = {} + for p in primes: + pts = S.get(p, U + 8, stop) + if pts is None: + return out + 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] + 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"]]] + if piv[:U] != list(range(U)): + break + for k, e in enumerate(todo): + if U + k in piv: + continue + sols.setdefault(e, {})[p] = [int(rr["R"][i, U + k]) for i in range(U)] + for e, by in sols.items(): + if len(by) < len(primes): + continue + coef = [_crt_rational({p: by[p][i] for p in primes}) for i in range(U)] + if all(c_ is not None for c_ in coef): + out[e] = (mons, coef) + return out + + +def _line_degrees(S, width, p, stop, top=24): + """Per entry the degrees (numerator, denominator) of the restriction to a random line, the least sum first and + a polynomial first; the total degrees of the entries at a generic line. None where not found.""" + rng = S.rng + b = [rng.randrange(1, p) for _ in range(S.n)] + d = [rng.randrange(1, p) for _ in range(S.n)] + pts = [] + t = 0 + while len(pts) < 2 * top + 6: + t += 1 + if work.ticks() > stop or t > 6 * top: + return None + v = S.values([(bi + t * di) % p for bi, di in zip(b, d)], p) + if v is not None: + pts.append((t, v)) + out = [] + for e in range(width): + got = None + 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] + if _kernel_canonical(rows, p)[2]: + got = (dn, dd) + break + if got: + break + out.append(got) + return out + + +def _variable_degrees(S, entries, p, stop, top): + """Per variable the highest degree of the entries in it alone, the others at random values: a box of + monomials that holds every term, at a generic point. None where not found.""" + rng = S.rng + out = [] + for i in range(S.n): + base = [rng.randrange(1, p) for _ in range(S.n)] + pts, t = [], 0 + while len(pts) < top + 6: + t += 1 + if work.ticks() > stop or t > 4 * top + 20: + return None + x = list(base) + x[i] = t + v = S.values(x, p) + if v is not None: + pts.append((t, v)) + deg = 0 + for e in entries: + for dn in range(0, top + 1): + rows = [[pow(t, k, p) for k in range(dn + 1)] + [(-v[e]) % p] for t, v in pts] + if _kernel_canonical(rows, p)[2]: + deg = max(deg, dn) + break + else: + return None + out.append(deg) + return out + + +def _rational_one(S, e, dn, dd, primes, stop): + """(numerator monomials and coefficients, denominator monomials and coefficients) of entry e with total degrees + at most dn and dd, None where the kernel is not one vector.""" + mn, md = _monomials(S.n, dn), _monomials(S.n, dd) + pn, pd = _parents(mn), _parents(md) + U = len(mn) + len(md) + if U > _INTERP: + return None + vecs = {} + for p in primes: + 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] + piv, free, basis = _kernel_canonical(rows, p) + if len(basis) != 1: + return None + vecs[p] = (piv, free, basis[0]) + if len({(a, b) for a, b, _ in vecs.values()}) != 1: + return None + 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)]) + + +def _interpolate(values, n, rng, stop): + """Rational functions of the n variables, one per entry of the vector function `values(x, p)` (None at a bad + point), rebuilt over Q: the degrees from a random line, the polynomials of all entries at once, the rational + entries over the denominator of one of them; candidates only.""" + primes = all_primes()[:2] + S = _Samples(values, n, rng, primes) + first = S.get(primes[0], 1, stop) + if not first: + return None + width = len(first[0][1]) + degs = _line_degrees(S, width, primes[0], 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]} + 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) + # most coefficients of relations are sparse: the monomials within the degrees in each variable + box = _variable_degrees(S, polys, primes[0], stop, top) if top > 2 else None + got = _polys_at_once(S, polys, None, primes, stop, [top], box) + if len(got) < len(polys): + return None + for e, (m_, c_) in got.items(): + out[e] = (m_, c_, [Fraction(1)] + [Fraction(0)] * (len(m_) - 1)) + rest = [e for e in range(width) if e not in out] + if not rest: + return [out[e] for e in range(width)] + # the denominator of the entry with the highest one, then the numerators over it at once + e0 = max(rest, key=lambda e: degs[e][1]) + one = _rational_one(S, e0, degs[e0][0], degs[e0][1], primes, stop) + if one is None: + return None + den = one[1] + dterms = [(m_, int(c_.numerator), int(c_.denominator)) for m_, c_ in zip(*den) if c_] + + 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): + return None + for e, (m_, c_) in nums.items(): + # numerator and denominator over one list of monomials + allm = sorted(set(m_) | set(den[0]), key=lambda t: (sum(t), t)) + nn = dict(zip(m_, c_)) + dd = dict(zip(*den)) + out[e] = (allm, [nn.get(t, Fraction(0)) for t in allm], [dd.get(t, Fraction(0)) for t in allm]) + return [out[e] for e in range(width)] + + +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))] + + +def _configs(ny, ni, cap, floor=0): + """(orders per observable, degree) of the relations tried with more than `floor` and at most `cap` monomials, + fewest monomials first; an order -1 leaves the observable out.""" + out = [] + # every combination of orders for a few observables; for many, each one alone and all at one order + 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)] + for ms in vectors: + if max(ms) < 0: + continue + nvar = sum(m + 1 for m in ms) + ni(max(ms)) + for degree in range(1, 7): + nmon = math.comb(nvar + degree, degree) + if nmon > cap: + break + if nmon > floor: + out.append((nmon, ms, degree)) + return [(ms, degree) for _, ms, degree in sorted(out)] + + +def _covers(a, b): + """Whether config a = (orders, degree) holds every monomial of config b.""" + return a[1] >= b[1] and all(x >= y for x, y in zip(a[0], b[0])) + + +def _compiled(rel, ms, degree): + """((base, parents), monomials): the derivatives of the observables and the input states, evaluated together, and + the exponent vectors of the monomials phi in them.""" + base = ioproj.Base(rel, _base(rel, ms)) + mons = _monomials(len(base.funcs), degree) + return (base, _parents(mons)), mons + + +def _eval_monomials(compiled, pt, p): + """The monomials phi at the point modulo p; None where a denominator vanishes there.""" + (base, parents), _ = compiled + ok, vals = base.values(np.array([pt], dtype=np.int64) % p, p) + if not ok[0]: + return None + return _mono_values([int(v) for v in vals[0]], parents, p) + + +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)) + if Dn == 0: + return None + out.append(spy.cancel(N / Dn)) + return out + + +def _ring_coeffs(rel, syms, lam): + """The coefficients lam, rational functions of the coordinates, times their common denominator, as polynomials + of the ring of the jets.""" + J = ioproj.jets_of(rel) + den = spy.Integer(1) + for v in lam.values(): + den = spy.lcm(den, spy.fraction(spy.cancel(v))[1]) + names = {s_: spy.Symbol(str(s_)) for s_ in syms} + return {j: J.R.from_expr(spy.cancel(v * den).xreplace(names)) for j, v in lam.items() if v != 0} + + +def _identity(rel, syms, lam, phis): + """Whether sum_j lam[j] phis[j] is zero, over the common denominator of the phis and of the coefficients.""" + J = ioproj.jets_of(rel) + co = _ring_coeffs(rel, syms, lam) + return ioproj.combine(J, list(co.values()), [phis[j] for j in co])[0] == 0 + + +def _phis(rel, ms, degree, extra=()): + """The monomials phi in the base functions as ioproj.Quo, then each state of `extra` times those of one degree + less.""" + 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)] + return phis + [ioproj.Quo(q.numer * J.X[e], q.exps) for e in extra for q in low] + + +def _kernel_at(rel, jets, xp, p, pos, rng, rows_needed, extra=None): + rows = [] + while len(rows) < rows_needed: + pt = [rng.randrange(1, p) for _ in rel.names] + for i_, v in zip(pos, xp): + pt[i_] = v + r = _eval_monomials(jets, pt, p) + if r is None: + continue + if extra is not None: + # the columns x_i psi_k: the state times the monomials of one degree less + r = r + [pt[extra[0]] * r[k] % p for k in range(extra[1])] + rows.append(r) + return _kernel_canonical(rows, p) + + +def state_relation(series, syms, coord, rng, stop, cap=None): + """For a coordinate that is the start of a state x_i: a relation sum_j lambda_j phi_j(y, u) + x_i sum_k mu_k + psi_k(y, u) = 0 along every trajectory, checked as an identity of rational functions, with mu_k psi_k nonzero, + so that x_i(0) = -sum_j lambda_j phi_j / sum_k mu_k psi_k at the start; {"reads": the coordinates the + coefficients read} or None.""" + rel = _relations(series, syms) + if not rel.ok: + return None + seg = rel.part["segs"][0] + i = next((k for k, v in enumerate(seg["x0"]) if v[0] is not None and v[0] == coord), None) + if i is None or i in rel.known: + return None + 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] + xi = rel.names.index(str(rel.X[i])) + p0 = all_primes()[0] + for ms, degree in _configs(len(rel.y), lambda m: len(rel.inputs(m)), cap or _RELATION): + if work.ticks() > stop: + return None + if not ioproj.jets_of(rel).within(ms): + continue + jets = _compiled(rel, ms, degree) + 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) + # 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: + continue + col = free.index(cols[0]) + + def values(xp, p, piv=piv, free=free, jets=jets, col=col, ext=ext, nmon=nmon, nlow=nlow): + pv, fr, b = _kernel_at(rel, jets, xp, p, pos, rng, nmon + nlow + 7, ext) + 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 + exprs = _rebuild(inter, [syms[k] for k in idx]) + if exprs is None: + continue + lam = {free[col]: spy.Integer(1)} + lam.update(zip(piv, exprs)) + J = ioproj.jets_of(rel) + 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]) + 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} + 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 None + + +def io_functions(series, syms, rng, stop, log, cap=_RELATION, floor=0, found=None): + """Functions of the coordinates proven to lie in the field of the output coefficients: the entries of the + canonical kernel basis of the relation matrix, each relation checked as an identity of rational functions in + the states and coordinates, the kernel dimension by the rank at one point modulo a prime. A generator: each + configuration of orders and degree with more than `floor` and at most `cap` monomials that gives relations yields + their new entries.""" + rel = _relations(series, syms) + if not rel.ok: + log.append("no relations for this model") + return + p0 = all_primes()[0] + 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] + found = set() if found is None else found + done = [] + for ms, degree in _configs(len(rel.y), lambda m: len(rel.inputs(m)), cap, floor): + if work.ticks() > stop: + return + # a configuration holding one that gave relations holds their multiples and derivatives: the relations + # found later come with new observables + if any(_covers((ms, degree), d) for d in done) or not ioproj.jets_of(rel).within(ms): + continue + jets = _compiled(rel, ms, degree) + nmon = len(jets[1]) + piv, free, basis = _kernel_at(rel, jets, [rng.randrange(1, p0) for _ in idx], p0, pos, rng, nmon + 6) + if not basis or len(basis) > 6: + continue + # the theorem needs the kernel of M along the trajectory to be the space of the relations + K = nmon + 6 + got = _relation_matrix(rel, [rng.randrange(1, p0) for _ in syms], p0, ms, degree, K) + if got is None or len(_kernel_canonical(got[0], p0)[0]) != nmon - len(basis): + continue + + def values(xp, p, piv=piv, free=free, jets=jets, nmon=nmon): + pv, fr, b = _kernel_at(rel, jets, xp, p, pos, rng, nmon + 6) + 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") + continue + exprs = _rebuild(inter, [syms[k] for k in idx]) + if exprs is None: + continue + phis = _phis(rel, ms, degree) + # one relation per free column: 1 there, the interpolated entries on the pivots + it = iter(exprs) + lams = ({fc: spy.Integer(1), **{pc: next(it) for pc in piv}} for fc in free) + if not all(_identity(rel, syms, lam, phis) for lam in lams): + log.append(f"relations at orders {ms}, degree {degree}: identity fails") + continue + done.append((ms, degree)) + new = _new(exprs, found) + log.append(f"relations at orders {ms}, degree {degree}: {len(free)} proven") + yield new + + +def _new(exprs, found): + """The expressions that are no numbers and not in `found`, which takes them.""" + out = [] + for e in exprs: + key = str(e) + if not e.is_number and key not in found: + found.add(key) + out.append(e) + return out + + +def _profiles(rel, rng): + """The parametric profiles of the relations, computed once.""" + if not hasattr(rel, "_profiles"): + unknown = [j for j in range(rel.ns) if rel.X[j] is not None and j not in rel.known] + rel._profiles = ioproj.profiles(rel, unknown, all_primes()[0], rng) + return rel._profiles + + +def projection_functions(series, syms, rng, stop, log, found=None): + """Functions of the coordinates proven to lie in the field of the output coefficients: the coefficients of the + projections, per profile and observable the relation of the derivative of the observable on top of the profile + with the derivatives below (docs/method/global.rst, "The exact count"). Each relation is checked as an identity of + polynomials, and the rank of the Taylor coefficients of the relation along the trajectory of the first condition, + one less than the number of terms at a point modulo a prime, puts the coefficients in the field of the outputs. + A generator: each projection proven yields the coefficients not found before.""" + rel = _relations(series, syms) + if not rel.ok: + return + found = set() if found is None else found + p0 = all_primes()[0] + 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] + params = [syms[k] for k in idx] + # the projections tried before, also by an earlier pass with fewer observables + seen = rel.__dict__.setdefault("_projections", set()) + for h in _profiles(rel, rng): + # the supports of the projections of a profile first, then the relations with the fewest terms first + found_here = [] + for i in range(len(h)): + if work.ticks() > stop: + return + pr = ioproj.Projection.output(rel, h, i, pos, rng) + where = f"projection of observable {i} at profile {tuple(h)}" + if pr is None: + if (tuple(h), i) not in seen: + seen.add((tuple(h), i)) + log.append(f"{where}: a derivative of one with more than {ioproj._JET} terms") + continue + key = (tuple(pr.ms), pr.top, tuple(str(rel.y[r]) for r, m in enumerate(pr.ms) if m >= 0)) + if key in seen: + continue + seen.add(key) + S = pr.search([rng.randrange(1, p0) for _ in idx], p0, stop) + if S is not None: + _supports(rel)[(tuple(h), i)] = S + if S is None or len(S) < 2: + log.append(f"{where}: no relation found") + elif len(S) > ioproj.TERMS: + log.append(f"{where}: {len(S)} terms") + else: + found_here.append((len(S), i, where, pr)) + for _, _i, where, pr in sorted(found_here, key=lambda x: x[:2]): + if work.ticks() > stop: + return + S = pr.mons + rk = ioproj.series_rank(rel, pr, S, syms, rng, p0) + if rk != len(S) - 1: + log.append(f"{where}: rank {rk} of {len(S)} terms along the trajectory") + continue + co = ioproj.Coefficients(pr, len(idx), rng, stop) + if not co.run(): + log.append(f"{where}: {len(S)} terms, not interpolated ({co.why})") + continue + if not ioproj.identity(rel, pr, co, pos): + log.append(f"{where}: {len(S)} terms, identity fails") + continue + new = _new(co.expressions(params), found) + log.append(f"{where}: {len(S)} terms proven") + yield new + + +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: + got = elim.eliminate_relations(rel, random.Random(seed), terms) + 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()}})) + + +def elimination_functions(series, syms, rng, stop, log, found=None): + """Functions of the coordinates proven in the field of the output coefficients: per observable the coefficients of + the relation by elimination (elim.py), over one of fewest terms, those whose gradients raise the rank and as many + more (docs/method/global.rst, "The exact count"). The relation vanishes along every trajectory by construction, and + the rank of the Taylor coefficients of the monomials of the relation along the trajectory, one less than their + number at a point modulo a prime, makes it the only one on the support. The elimination runs in a separate process, + which starts where the search has not reached `stop` (work.ticks()) and ends at the cap elimination_terms of + work.CAPS; a generator as projection_functions().""" + rel = _relations(series, syms) + if not rel.ok or getattr(rel, "_elim_tried", False): + return + rel._elim_tried = True + try: + from . import elim + except ImportError: + log.append("elimination: python-flint is not installed") + return + if work.ticks() > stop: + 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) + got = pickle.loads(r.stdout) if r.returncode == 0 and r.stdout else None + except (pickle.UnpicklingError, EOFError): + got = None + if got is None or "why" in got: + log.append(f"elimination: {got['why']}" if got else "elimination: the process failed") + return + R = elim._Ring(rel, got["order"]) + _elimination_states(rel, R, got.get("states") or {}) + p0 = all_primes()[0] + 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)) + for obs, d in got["relations"].items(): + P = R.ctx.from_dict(d) + built = elim.relation_projection(rel, R, P) + where = f"elimination of observable {obs}" + if built is None: + log.append(f"{where}: the relation reads a known state outside the base functions") + continue + pr, support, coefs = built + rk = ioproj.series_rank(rel, pr, support, syms, rng, p0) + if rk != len(support) - 1: + log.append(f"{where}: rank {rk} of {len(support)} terms along the trajectory") + continue + ref, order = elim.normalized(coefs) + _, pins = elim.gradient_select(coefs, ref, order, len(gens), p0, rng) + 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") + yield _new(exprs, found) + + +def _elimination_states(rel, R, states): + """rel._elim_states: per state eliminated with A x + B = 0 along every trajectory, A nonzero at a point of one, + the coordinates that A and B read, the parameters and the starts of the states they read.""" + seg = rel.part["segs"][0] + out = {} + for j, ab in states.items(): + if ab is None: + continue + used = {i for d in ab for m in d for i, k in enumerate(m) if k} + reads = set() + for i in used: + n = R.names[i] + if n in R.params: + reads.add(spy.Symbol(n)) + elif n.startswith("si_x"): + v = seg["x0"][int(n[4:])][0] + reads |= set() if v is None else spy.sympify(v).free_symbols + out[j] = {"reads": reads, "state": j} + rel._elim_states = out + + +def elimination_state(series, syms, coord): + """For a coordinate that is the start of a state the elimination removed with A x + B = 0, A nonzero at a point + of a trajectory: {"reads", "state"}, the coordinates that A and B read; None otherwise.""" + rel = _relations(series, syms) + if not rel.ok: + return None + seg = rel.part["segs"][0] + i = next((k for k, v in enumerate(seg["x0"]) if v[0] is not None and v[0] == coord), None) + return None if i is None else getattr(rel, "_elim_states", {}).get(i) + + +def state_projection(series, syms, coord, rng, stop): + """For a coordinate that is the start of a state x_i: the projection of x_i, a relation linear in x_i with the + derivatives of the observables below a profile, checked as an identity of polynomials, with the coefficient of + x_i nonzero at the start, as in state_relation(); {"reads", "state", "terms"} or None.""" + rel = _relations(series, syms) + if not rel.ok: + return None + seg = rel.part["segs"][0] + i = next((k for k, v in enumerate(seg["x0"]) if v[0] is not None and v[0] == coord), None) + if i is None or i in rel.known or rel.X[i] is None: + return None + p0 = all_primes()[0] + 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] + for h in _profiles(rel, rng)[:2]: + # the derivatives below the profile, then with the next derivative of one observable below the degree of + # 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)]) + for lift, cap in tries: + if work.ticks() > stop: + return None + pr = ioproj.Projection.state(rel, h, i, pos, rng, lift) + if pr is None: + continue + S = pr.search([rng.randrange(1, p0) for _ in idx], p0, stop, cap=cap, top_degree=1) + if S is None or len(S) > ioproj.TERMS or not any(m[pr.top] for m in S) or all(m[pr.top] for m in S): + continue + co = ioproj.Coefficients(pr, len(idx), rng, stop) + if not co.run() or not ioproj.identity(rel, pr, co, pos): + continue + if not _nonzero_at_start(rel, pr, co, seg, syms, idx, pos, rng): + continue + exprs = co.expressions([syms[k] for k in idx]) + return {"reads": set().union(*[e.free_symbols for e in exprs]), "state": i, "terms": len(S)} + return None + + +def _supports(rel): + """{(profile, observable): support} of the projections found, None where none was found.""" + return rel.__dict__.setdefault("_supports", {}) + + +def _top_degree(rel, h, r, pos, rng, stop): + """The degree of the projection of observable r at profile h in the derivative on top, None where it is not + found.""" + key = (tuple(h), r) + pr = ioproj.Projection.output(rel, h, r, pos, rng) + if pr is None: + return None + if key not in _supports(rel): + p0 = all_primes()[0] + _supports(rel)[key] = pr.search([rng.randrange(1, p0) for _ in pos], p0, stop) + S = _supports(rel)[key] + return None if not S else max(m[pr.top] for m in S) + + +def _nonzero_at_start(rel, pr, co, seg, syms, idx, pos, rng): + """Whether the coefficient of the top state of a state projection is nonzero at the start of the first + condition: a nonzero value at one point modulo a prime.""" + p = all_primes()[0] + names = rel.names + for _ in range(8): + vals = {s_: rng.randrange(1, p) for s_ in syms} + theta = [vals[syms[k]] for k in idx] + pt = [rng.randrange(1, p) for _ in names] + for k, v in zip(pos, theta): + pt[k] = v + ok = True + for x, v in zip(rel.X, seg["x0"]): + if x is None or str(x) not in names or v[0] is None: + continue + e = spy.sympify(v[0]) + num, den = spy.fraction(spy.together(e.xreplace({s_: vals[s_] for s_ in syms}))) + if int(den) % p == 0: + ok = False + break + pt[names.index(str(x))] = int(num) % p * pow(int(den) % p, -1, p) % p + a = ioproj.coefficient_values(co, theta, p) if ok else None + if a is None: + continue + got = pr.base.values(np.array([pt], dtype=np.int64), p) + if not got[0][0]: + continue + B = got[1][0] + total = 0 + for c, m in zip(a, pr.mons): + if not m[pr.top]: + continue + t = c + for v, e in enumerate(m): + if e and v != pr.top: + t = t * pow(int(B[v]), e, p) % p + total += t + return total % p != 0 + return False + + +def _normalized(w, P, syms): + """(the proven function w over m, m) with m the largest monomial in the proven coordinates P that divides the + numerator of w, over the denominator of w where that reads P only; None where m is one.""" + key = frozenset(P) + if getattr(w, "_norm", (None,))[0] == key: + return w._norm[1] + Ps = sorted(P & w.num.free_symbols, key=str) + m = spy.Integer(1) + if Ps: + mons = spy.Poly(w.num, *Ps).monoms() + m = spy.prod([x ** min(mm[i] for mm in mons) for i, x in enumerate(Ps)]) + if w.den.free_symbols <= P: + m = m / w.den + res = None if m == 1 else (_Var(f"{w.name}n", expr=spy.cancel(w.expr / m), syms=syms), m) + w._norm = (key, res) + return res + + +def exact_fiber(series, orders, grp, syms, inputs=(), known=(), pre=()): + """{"exact", "why", "generators", "seconds"}: whether the field fixed by the group `grp` of exact maps lies in + the field of the output coefficients, so that the fiber at a generic point is the orbit (docs/method/global.rst, + "The exact count"). The search runs in a separate process and ends at the caps of work.CAPS: search_entries, + the entries of the matrices over GF(p) it reduces, and elimination_terms.""" + t0 = time.monotonic() + out = {"exact": False, "why": None, "generators": [], "seconds": 0.0} + if len(grp) > _GROUP: + out["why"] = f"the group of the exact maps has more than {_GROUP} elements" + return out + jet = re.compile("|".join(re.escape(u) + r"(_d\d+)?" for u in inputs)) if inputs else None + drawn = [str(x) for x in getattr(series, "drawn_starts", ())] + if series.known or any(jet is None or not jet.fullmatch(x) for x in drawn): + out["why"] = "the model holds constants that are no coordinates, taken at drawn values" + 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))) + try: + 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 + if got is None: + out["why"] = "the search failed" + out["seconds"] = round(time.monotonic() - t0, 2) + return out + got["seconds"] = round(time.monotonic() - t0, 2) + return got + + +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()) + ioproj.THREADS[0] = threads + work.MSOLVE_MEMORY = memory + work.CAPS.update(caps) + res = _exact_fiber(series, orders, grp, syms, caps["search_entries"], inputs, random.Random(seed), known, pre) + sys.stdout.buffer.write(pickle.dumps(res)) + + +def _exact_fiber(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): + out = _search(series, orders, grp, syms, cap, inputs, rng, known, pre) + out.setdefault("proven", []) + # the supports of the projections past ioproj.TERMS, whose coefficients discrete.pinned_count() may count + out["large"] = large_projections(series, syms) + return out + + +def large_projections(series, syms): + """[{"profile", "observable", "support"}] of the projections found with more than ioproj.TERMS terms.""" + key = (id(series), tuple(str(s_) for s_ in syms)) + if key not in _REL: + 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] + + +def _search(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): + t0 = work.ticks() + # the clock of the search: the entries of the matrices over GF(p) reduced, at most `cap` + stop = t0 + cap + ended = [f"the search reached the cap search_entries of {int(cap):,} entries of the matrices reduced"] + out = {"exact": False, "why": None, "generators": [], "entries": 0} + gens = generators(grp, syms) + if gens is None: + out["why"] = "no linear form of the coordinates separates the orbit" + return out + alpha, fs, traces, others = gens + outs = _Outputs(series, orders) + if not outs.index: + out["why"] = "no observable at the start of an experiment" + return out + 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]] + # 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)] + # functions an earlier search of this detection proved in the field of the outputs + W += [_Var(f"p{n_}", expr=spy.sympify(e), syms=syms) for n_, e in enumerate(pre)] + fs = [f for f in fs if f not in kappa] + pending = sorted(fs, key=spy.count_ops) + extra = (h for deg in (1, 2) for h in _reynolds(grp, syms, deg)) + log = [] + out["relations"], out["io_functions"] = log, [] + found = set() + + 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)) + io = relations(t0 + _SHARE * cap) + tried = set() + scaled = {} + + def subsystems(f): + # the proven functions whose symbols outside the proven coordinates lie in those of f and at most two more, + # with the proven coordinates they read: few variables, so that higher degrees fit + P = {w.expr for w in W if w.c is None and w.expr.is_Symbol} + sym_of = {w.expr: w for w in W if w.c is None and w.expr.is_Symbol} + Uf = spy.sympify(f).free_symbols - P + cand = [w for w in W if w.c is None and not w.expr.is_Symbol and w.free - P] + others = sorted(set().union(*[w.free - P for w in cand]) - Uf, key=str) + out = [] + p = all_primes()[0] + pts = pool.get(p, 2) + for k in range(3): + for E in itertools.combinations(others, k): + allowed = Uf | set(E) + V, seen = [], set() + for w in sorted((w for w in cand if (w.free - P) <= allowed), key=lambda w: len(w.tn) + len(w.td)): + # over the monomial in proven coordinates that divides it + nw = _normalized(w, P, syms) + if nw is not None: + scaled[id(nw[0])] = (w, nw[1]) + w = nw[0] + # one of the functions that differ by a constant factor + vals = [w.value(x, c, p) for x, c in pts] + if None in vals or not vals[0]: + continue + key = vals[1] * pow(vals[0], -1, p) % p + if key not in seen: + seen.add(key) + V.append(w) + V = V[:_SUBSYSTEM] + if len(V) < len(allowed): + continue + read = set().union(*[w.free for w in V]) & P + Ps = [sym_of[x] for x in sorted(read, key=str)] + if (V, Ps) not in out: + out.append((V, Ps)) + return out + + 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)) + for U, dv, dp in pairs: + if U > cap: + break + mons = [a + b for a in _monomials(nv, dv) for b in _monomials(nP, dp)] + yield sorted(mons, key=sum) + + def prove(f, coefficients, cap=_UNKNOWNS): + # the functions proven on the coordinates of f first, then small systems of proven functions, then all + # proven, then with the output coefficients + support = spy.sympify(f).free_symbols + near = [w for w in W if w.c is None and w.free <= support] + cs = [w for w in W if w.c is not None] + top = max((outs.index[w.c][1] for w in cs), default=0) + # the output coefficients join lowest order first + low = [near + [w for w in cs if outs.index[w.c][1] <= j] for j in range(top + 1)] if coefficients else [] + for V, Ps in subsystems(f): + key = (f, tuple(id(w) for w in V + Ps), cap, "products") + if key in tried: + continue + tried.add(key) + for mons in products(len(V), len(Ps), cap): + if work.ticks() > stop: + break + got = _find(f, V + Ps, syms, outs, pool, 0, stop, mons) + if got is not None: + # a proven function over a monomial in proven coordinates joins the tower before f + for v in V: + if id(v) in scaled and re.search(rf"\b{v.name}\b", got[0] + got[1]) and v not in W: + 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)}) + 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: + key = (f, tuple(sorted(id(w) for w in V)), cap) + if key in tried: + continue + tried.add(key) + for d in range(1, 9): + if not V or 2 * math.comb(len(V) + d, d) > cap or work.ticks() > stop: + break + got = _find(f, V, syms, outs, pool, d, stop) + if got is not None: + return got + return None + + out["proven"] = [str(w_.expr) for w_ in W if w_.c is None and w_.expr not in kappa] + + def take(new): + for h in new: + W.append(_Var(f"r{len(W)}", expr=h, syms=syms)) + out["io_functions"].append(str(h)) + out["proven"].append(str(h)) + + def add(f, got): + out["proven"].append(str(f)) + out["generators"].append({"function": str(f), "numerator": got[0], "denominator": got[1]}) + W.append(_Var(f"f{len(out['generators'])}", expr=f, syms=syms)) + + # each function proven joins the variables of the next: a tower of fields inside the field of the outputs + def step(coefficients, cap=_UNKNOWNS): + done = next(((f, got) for f in pending for got in [prove(f, coefficients, cap)] if got is not None), None) + if done is not None: + 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} + + def from_state(size): + # the start of a state: x_i(0) from a relation whose coefficients are rational in coordinates in F; small + # relations first, the large ones once the input-output relations are done + known = {w.expr for w in W if w.c is None and w.expr.is_Symbol} + for f in list(pending): + if not f.is_Symbol: + continue + # the start of a state the elimination removed with an equation of degree one in it + es = elimination_state(series, syms, f) + if es is not None and es["reads"] <= known: + pending.remove(f) + add(f, ("elimination", f"coefficients in {sorted(map(str, es['reads']))}")) + return True + if states.get(f, (None, 0))[1] < size: + # the projection before the large dense relations + sr = state_projection(series, syms, f, rng, stop) if size == _RELATION else None + end = min(stop, work.ticks() + (_DENSE if size == _RELATION else _DENSE / 3) * cap) + sr = sr or state_relation(series, syms, f, rng, end, size) + states[f] = (sr, size) + sr = states[f][0] + if sr is not None and sr["reads"] <= known: + pending.remove(f) + add(f, ("state relation", f"coefficients in {sorted(map(str, sr['reads']))}")) + # the state joins the observables, and the relations are searched again with it + rel = _relations(series, syms) + if sr["state"] not in rel.observed and rel.X[sr["state"]] not in rel.y and len(rel.y) < 6: + rel.observe(sr["state"]) + 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): + continue + # where only starts of states are left, their relations before the next input-output relations + if all(f in starts for f in pending) and from_state(_RELATION): + continue + t1 = work.ticks() + if io_restart[0]: + io_restart[0] = False + io = relations(stop) + new = next(io, None) + out["relation_entries"] = out.get("relation_entries", 0) + work.ticks() - t1 + if new is not None: + take(new) + continue + if from_state(_RELATION): + continue + if not out["io_functions"]: + # 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") + if step(True): + continue + for h in extra: + if h.is_number or any(w.expr is not None and spy.cancel(w.expr - h) == 0 for w in W): + continue + got = prove(h, True) + if got is not None: + add(h, got) + break + else: + break + if not pending: + # the traces join F where they are found; they are not needed for the theorem + for t in sorted(traces, key=spy.count_ops): + got = prove(t, True, 300) + if got is not None: + 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 "")) + return out + # the other coordinates in F(alpha): alpha joins the proven functions as a variable of these searches only + if others: + A = _Var("alpha", expr=alpha, syms=syms) + # a tower in F(alpha): each coordinate proven there joins the variables of the next + Fa = [A] + + def in_f_alpha(th): + # the proven functions of the coordinates that the images of th and alpha read first + S = set().union(spy.sympify(alpha).free_symbols, *[spy.sympify(g.get(th, th)).free_symbols for g in grp]) + near = [w for w in W if w.c is None and w.free <= S] + cs = [w for w in W if w.c is not None] + top = max((outs.index[w.c][1] for w in cs), default=0) + low = [near + Fa + [w for w in cs if outs.index[w.c][1] <= j] for j in range(top + 1)] + for V in [near + Fa] + low + [[w for w in W if w.c is None] + Fa, W + Fa]: + key = (th, tuple(id(w) for w in V), "alpha") + if key in tried: + continue + tried.add(key) + for d in range(1, 9): + if 2 * math.comb(len(V) + d, d) > _UNKNOWNS or work.ticks() > stop: + break + got = _find(th, V, syms, outs, pool, d, stop) + 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) + 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 + if gt is not None: + add(tr, gt) + else: + new = next(io, None) + if not new: + break + take(new) + got = in_f_alpha(th) + if got is None: + 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})"}) + Fa.append(_Var(f"a{len(Fa)}", expr=th, syms=syms)) + proven_syms.add(th) + out["alpha"] = str(alpha) + out["entries"] = work.ticks() - t0 + out["exact"] = True + return out diff --git a/src/symident/detection/fields.py b/src/symident/detection/fields.py index 2294a79..4b41304 100644 --- a/src/symident/detection/fields.py +++ b/src/symident/detection/fields.py @@ -1,5 +1,6 @@ """Gap series, exact scalings, field analyses per regime and the proof that the Lie order suffices.""" +import hashlib import json import re import threading @@ -31,6 +32,7 @@ from ..sym.modp import eval_rational_mod_batch from ..sym.parse import model_sympify from ..sym.scaling import scaling_symmetries_multi, verify_scalings +from ..sym.supportlift import support_lift from .bound import lie_row_degree @@ -150,10 +152,20 @@ def _evs(x): return list(x) +def scaling_tapes(multi): + """One tape per group of conditions with the same monomials (multi['scaling_groups'] of a shared tape): the + scaling rows and checks of a group are those of any member.""" + if multi.get("scaling_tapes"): + return list(multi["scaling_tapes"]) + groups = multi.get("scaling_groups") + tapes = multi["tapes"] + return [tapes[g[0]] for g in groups] if groups else list(tapes) + + def exact_scaling_set(multi, fixed): """Weight vectors of the scalings of the whole model, exactly checked.""" ver_keys = ["model_lines", "obs_lines", "ver_ic", "ver_ev", "ver_t0", "ver_time", "ver_rest"] - ver_tapes = _uniq([{k: t[k] for k in ver_keys if k in t} for t in multi["tapes"]]) + ver_tapes = _uniq([{k: t[k] for k in ver_keys if k in t} for t in scaling_tapes(multi)]) jets = set(multi.get("nuisance_jet_states") or []) inputs = [u for u in multi.get("forcings") or [] if u not in jets] @@ -163,12 +175,14 @@ 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: full = scaling_symmetries_multi( 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, + 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']}"] @@ -179,11 +193,12 @@ def ev_lines(t, add): if full is None: return [] ws = [d["vector"] for d in full.get("non_identifiable", [])] - ws = [w for w in ws if all(re.match(r"^-?[0-9]+$", str(v)) for v in w.values())] + exps = {str(r["E"]) for r in recast} + ws = [w for w in ws if all(k in exps or re.match(r"^-?[0-9]+$", str(v)) for k, v in w.items())] if not ws: return [] try: - ok = [bool(x) for x in verify_scalings(ws, ver_tapes)] + ok = [bool(x) for x in verify_scalings(ws, ver_tapes, shifts={str(r["L"]) for r in recast})] except Exception as exc: swallow(exc, "scaling verification") ok = [False] * len(ws) @@ -464,6 +479,9 @@ def _rename_init(expr, init): return str(e.xreplace({spy.Symbol(x): spy.Symbol(x + INIT) for x in init})) +_NAMES = re.compile(r"[A-Za-z_][A-Za-z0-9_.]*") + + def restricted_setup(setup, chains, joint): """The setup on the states that reach an observable of their chain, the states that stay at zero set to 0.""" regimes, tapes = setup["regimes"], setup["tapes"] @@ -475,37 +493,48 @@ def restricted_setup(setup, chains, joint): targets = {str(e["var"]) for ch in chains for i in ch for e in events[i]} zero = set() if not joint: - zero = {x for x in states if x not in targets and - all(any(l.split("=", 1)[0].strip() == x and l.split("=", 1)[1].strip() in ("0", "0.0") - for l in _lines(tapes[ch[0]].get("ver_ic"))) for ch in chains)} + 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")} 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} - drop = {x for x in zero if any(x in eqs[r] and spy.cancel(eqs[r][x].xreplace(sub)) != 0 - for r in visited)} + # 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]})} if not drop: break zero -= drop sub = {spy.Symbol(x): spy.Integer(0) for x in zero} def syms(e): - e = e.xreplace(sub) if sub else e - return {str(y) for y in e.free_symbols} & stset + names = {str(y) for y in e.free_symbols} + 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] ev_dep = [set().union(*[syms(model_sympify(str(e["value"]))) for e in evs]) for evs in events] - keep_of = {} + # regimes that differ in values only have the same dependencies, and the same closure from the same start + kinds = {} + kind = [kinds.setdefault(tuple(sorted((x, frozenset(d)) for x, d in dr.items())), len(kinds)) for dr in dep] + keep_of, closure = {}, {} for ch in chains: rs = sorted({setup["regime_of"][i] - 1 for i in ch}) seen = set().union(*[obs_dep[r] for r in rs]) | set().union(*[ev_dep[i] for i in ch]) seen -= zero - while True: - more = set().union(*[dep[r][x] for r in rs for x in seen if x in dep[r]]) - zero - seen - if not more: - break - seen |= more + key = (tuple(sorted({kind[r] for r in rs})), frozenset(seen)) + if key not in closure: + while True: + more = set().union(*[dep[r][x] for r in rs for x in seen if x in dep[r]]) - zero - seen + if not more: + break + seen |= more + closure[key] = seen + seen = closure[key] for i in ch: keep_of[i] = keep_of.get(i, set()) | seen keep_r = {} @@ -515,12 +544,18 @@ def syms(e): if not zero and all(keep_r.get(r, stset) >= {x for x in eqs[r]} for r in keep_r): return setup + zeroed = {} + def cut(lines, keep): out = [] for l in _lines(lines): lhs, rhs = (u.strip() for u in l.split("=", 1)) if lhs in keep or lhs not in stset: - out.append(f"{lhs} = {model_sympify(rhs).xreplace(sub)}") + 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 + 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)}" @@ -573,26 +608,33 @@ def holds(r, f): return True return False - of = {} + of, found = {}, {} for r in used: - if holds(r, field): - of[r] = field - continue - res = certify(regime_identities(regimes[r], field, jets)) own = [ch for ch in chains if setup["regime_of"][ch[0]] - 1 == r] - # initial values set by other parameters: the state components from their identities + 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")))] - lifts = (initial_lift(field, ics, states, regimes[r]["f"]), linear_lift(field, regimes[r], ics, states)) - lift = next((x for x in lifts if x is not None and holds(r, x)), None) + # 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)] + continue + if holds(r, field): + of[r] = field + 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)) + 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] = lift + 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) - res = certify(regime_identities(regimes[r], alt, jets)) if alt is not None else res + res = certify(regime_identities(regimes[r], alt if alt is not None else field, jets)) if res["ok"] is not True: return res of[r] = dict(alt, **extra) @@ -608,15 +650,24 @@ def holds(r, f): ids += part else: ids += event_identities(e["ev"], of[e["from"]], of[e["to"]], states) + seen_ics = set() for ch in chains: t1, r0 = setup["tapes"][ch[0]], setup["regime_of"][ch[0]] - 1 if not joint: - # start events are composed into the initial values + # start events are composed into the initial values; a value off the field, of a state no component + # reads, holds the identity 0 = 0, and chains with the same values give the same identities + moved = {str(k) for k, v in dict(of[r0]).items() if str(v) != "0"} + read = set().union(*[names(v) for v in dict(of[r0]).values()]) if of[r0] else set() ics = [] for line in _lines(t1.get("ver_ic")): x, e = (u.strip() for u in line.split("=", 1)) - ics.append(f"{x} = {_rename_init(e, init)}") - ids += initial_identities(ics, of[r0]) + e = _rename_init(e, init) + if x in moved or x in read or names(e) & moved: + ics.append(f"{x} = {e}") + key = (r0, tuple(ics)) + if key not in seen_ics: + seen_ics.add(key) + ids += initial_identities(ics, of[r0]) continue t0 = _evs(t1.get("ver_t0")) if t0: @@ -779,7 +830,12 @@ 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")) + "tm_b", "tm_cnum", "tm_cden", "tm_out", "leaf_slot", "leaf_src", "leaf_num", "leaf_den")) + + +def _jet_key(key): + """The name under which the kernel keeps the jets of the ranks `key`.""" + return hashlib.sha256(repr(key).encode()).hexdigest() def _reach_at(r, rho): @@ -960,18 +1016,21 @@ def step(t): G, Q = [None] * n_seg, [None] * n_seg def call(kind, s, Nc, threads): - if kind == "g": - 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) if id(sb[s]) not in seg_keys: 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()) 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) + q_start[s:s + 1], threads, drop, True, _jet_key(key)) if r.get("ok"): shared[key] = np.asarray(r["ranks"]).ravel() return r diff --git a/src/symident/detection/finalize.py b/src/symident/detection/finalize.py index 5bf060e..9fc4589 100644 --- a/src/symident/detection/finalize.py +++ b/src/symident/detection/finalize.py @@ -190,7 +190,7 @@ def finalize(raw, method, settings, elapsed=None, coordinates=None): "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"), + "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"), diff --git a/src/symident/detection/firstint.py b/src/symident/detection/firstint.py new file mode 100644 index 0000000..042e859 --- /dev/null +++ b/src/symident/detection/firstint.py @@ -0,0 +1,544 @@ +"""No nonconstant rational first integral: a certificate at one point of the parameters, from the eigenvalues of the +Jacobian at an equilibrium (docs/method/global.rst, "Several experiments"). + +At an equilibrium whose eigenvalues are linearly independent over Z the system has no nonconstant rational first +integral (Cong, Llibre and Zhang 2011, Theorem 1), and a first integral of bounded degree at a generic point of the +parameters would give one at every point, since the points with one form a closed set defined over Q. The +independence is proven exactly: per diagonal block of the Jacobian the Galois group of the characteristic polynomial +is 2-transitive, shown by the cycle types of Frobenius elements at primes of degree one (Dedekind), the splitting +fields of the blocks differ, and the traces of the blocks are linearly independent over Q.""" + +import math +import time +from fractions import Fraction + +import sympy as spy + +from .. import session +from ..sym.numfield import NumberField, charpoly_mod, cycle_type, order_of, rank_over_q +from ..sym.parse import model_sympify + +# the prime ideals of degree one a Galois test reads at most, and the first prime +_PRIME_IDEALS = 3000 +_FIRST_PRIME = 10007 +# the largest number field of an equilibrium a test takes, the most equilibria msolve may return, and the draws of +# the parameters +_MAX_DEGREE = 12 +_MAX_POINTS = 120 +_DRAWS = 3 + + +class _OpenError(Exception): + """The test does not settle the question at this equilibrium.""" + + +def _diff(P, j): + """The partial derivative of a sparse polynomial {exponents: Fraction} in the variable j.""" + out = {} + for m, c in P.items(): + if m[j]: + mm = m[:j] + (m[j] - 1,) + m[j + 1:] + out[mm] = out.get(mm, 0) + c * m[j] + return out + + +def _value(K, P, vals, pw): + """A sparse polynomial at the values `vals` (elements of K), with the power table `pw`.""" + acc = K.zero + for m, c in P.items(): + term = K.rational(c) + for j, e in enumerate(m): + if e: + key = (j, e) + if key not in pw: + pw[key] = vals[j] if e == 1 else K.mul(pw.get((j, e - 1)) or _power(K, vals[j], e - 1), vals[j]) + term = K.mul(term, pw[key]) + acc = K.add(acc, term) + return acc + + +def _power(K, a, e): + """a^e in K.""" + out = K.one + for _ in range(e): + out = K.mul(out, a) + return out + + +def _sccs(n, edges): + """The strongly connected components of the graph on range(n) with edges i -> j, iterative Tarjan.""" + order, low, stack, onst, comps = {}, {}, [], set(), [] + for root in range(n): + if root in order: + continue + work = [(root, iter(edges[root]))] + order[root] = low[root] = len(order) + stack.append(root) + onst.add(root) + while work: + v, it = work[-1] + w = next(it, None) + if w is not None: + if w not in order: + order[w] = low[w] = len(order) + stack.append(w) + onst.add(w) + work.append((w, iter(edges[w]))) + elif w in onst: + low[v] = min(low[v], order[w]) + continue + work.pop() + if work: + low[work[-1][0]] = min(low[work[-1][0]], low[v]) + if low[v] == order[v]: + c = [] + while True: + w = stack.pop() + onst.discard(w) + c.append(w) + if w == v: + break + comps.append(sorted(c)) + return comps + + +def _primes(start): + """The primes above `start`, increasing.""" + p = start + while True: + p = int(spy.nextprime(p)) + yield p + + +def _galois(K, J, blocks, laws): + """Per block of the Jacobian J over K: the multiplicity of the eigenvalue 0 and the cycle types that prove a + 2-transitive Galois group of the rest of the characteristic polynomial over K, and per pair of blocks with rests + of degree at least two a prime at which the orders of the Frobenius elements differ, so that the splitting fields + differ. The characteristic polynomials are taken modulo primes of degree one only: reduction commutes with them. + The multiplicities are those at a prime where they add up to the `laws`, which give as many zero eigenvalues; + raises _OpenError where the primes read do not show them.""" + zeros, need, pairs = None, {}, {} + seen = 0 + for p in _primes(_FIRST_PRIME): + if seen > _PRIME_IDEALS: + break + for tau in K.primes_of_degree_one(p): + seen += 1 + red = [[K.residue(a, p, tau) for a in row] for row in J] + if any(r is None for row in red for r in row): + continue + chis = [charpoly_mod([[red[i][j] for j in B] for i in B], p) for B in blocks] + mult = [len(c) - 1 - max(k for k, x in enumerate(c) if x) for c in chis] + if zeros is None: + if sum(mult) != 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} + 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) + if ct is None: + continue + types[b] = ct + n = rec["n"] + if rec["full"] is None and ct == [n]: + rec["full"] = where + if rec["minus"] is None and ct == [n - 1, 1]: + rec["minus"] = where + if rec["transposition"] is None and ct.count(2) == 1 and all(c % 2 for c in ct if c != 2): + rec["transposition"] = where + 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()): + 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") + 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") + 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 + + +def _text(K, a): + """An element of K as text in s, the generator of K.""" + 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("**", "^") + + +def _test(K, J, names, laws=0): + """The certificate at one equilibrium with Jacobian J over K, or _OpenError with the reason. With `laws` + conservation laws, the eigenvalue 0 of that multiplicity, the Jacobian on the level set of the laws, is left + out.""" + blocks = _sccs(len(J), _edges(K, J)) + traces = [K.zero for _ in blocks] + for b, B in enumerate(blocks): + for i in B: + traces[b] = K.add(traces[b], J[i][i]) + zeros, need, pairs = _galois(K, J, blocks, laws) + keep = [b for b, B in enumerate(blocks) if len(B) > zeros[b]] + 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)}") + 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])} + if zeros[b]: + e["zero_eigenvalues"] = zeros[b] + if r is not None: + e["group"] = f"S_{r['n']}" if r["transposition"] not in (None, "n/a") or r["n"] == 2 else "2-transitive" + e["primes"] = {"n-cycle": r["full"]} + if r["minus"] != "n/a": + e["primes"]["(n-1)-cycle"] = r["minus"] + if r["transposition"] not in (None, "n/a"): + e["primes"]["transposition"] = r["transposition"] + out.append(e) + return out, {f"{a},{b}": v for (a, b), v in pairs.items()} + + +def _jacobian(K, F, U, allv): + """The Jacobian of the states U at the values `allv` over K, at an equilibrium: there each entry is the + derivative of the numerator over the denominator.""" + pw, J = {}, [] + for i in U: + N, D = F[i] + dinv = K.inv(_value(K, D, allv, pw)) + J.append([K.mul(_value(K, _diff(N, j), allv, pw), dinv) for j in U]) + return J + + +def _edges(K, J): + """The graph of the off-diagonal nonzero entries of J, i -> j.""" + return [[j for j in range(len(J)) if j != i and not K.is_zero(J[i][j])] for i in range(len(J))] + + +def _attempt(K, F, U, allv, names, laws, d): + """(blocks and pairs of _test(), None, None) at the point `allv`, else (None, why, degree), the degree of a + field of the parameters to draw again in, or None.""" + try: + J = _jacobian(K, F, U, allv) + return _test(K, J, names, laws), None, None + except ZeroDivisionError: + return None, "a denominator vanishes at the equilibrium", None + except _OpenError as why: + # traces of blocks rational in the parameters are dependent at a rational point: a field of degree nb + # separates them + nb = len(_sccs(len(U), _edges(K, J))) + return None, str(why), nb if "linearly dependent over Q" in str(why) and d < nb else None + + +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)} + + +def _field_poly(rng, d): + """A monic irreducible integer polynomial of degree d, lowest degree first: irreducible modulo a prime.""" + while True: + w = [rng.randint(-5, 5) for _ in range(d)] + [1] + if w[0] == 0: + continue + for p in (101, 103, 107, 109, 113, 127): + if cycle_type(list(reversed(w)), p) == [d]: + return w + + +def _equilibria(F, U, fixed, theta, alpha, nonzero, level=()): + """(equilibria, why): the equilibria of the states U over Q (the field of alpha when given), as + [(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") + gvals = dict(fixed) + gvals.update(theta) + for i, s in zip(U, syms): + 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)) + eqs, dens = [], spy.Integer(1) + for i in U: + N, D = F[i] + num = spy.expand(expr(N)) + eqs.append(num) + dens = dens * expr(D) + sat = dens * (spy.prod(syms) if nonzero else 1) + msnames = names + (["a"] if alpha is not None else []) + allsyms = syms + ([a] if alpha is not None else []) + gens = allsyms + [spy.Symbol("si_w")] + + def ms(e): + e = spy.expand(e) + if e == 0: + return None + P = spy.Poly(e, *gens) + L = math.lcm(*[int(spy.Rational(c).q) for c in P.coeffs()]) + out = [] + for mono, c in P.terms(): + c = int(c * L) + 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(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: + return None, "the equilibria form a family of positive dimension" + if data[0] != 0: + return None, "the balances have no solution" + _, _, deg, vnames, lin, par = data[1] + if deg <= 0 or par[0] != 1: + return None, "msolve did not parametrize the equilibria" + if deg > _MAX_POINTS: + return None, f"the balances have {deg} solutions, more than {_MAX_POINTS}" + T = spy.Symbol("t") + elim = spy.Poly(list(reversed([int(c) for c in par[1][0][1]])), T) + out = [] + for fac, _ in spy.factor_list(spy.sqf_part(elim))[1]: + if fac.degree() > _MAX_DEGREE: + continue + K = NumberField([int(c) for c in reversed(fac.all_coeffs())]) + t = K.from_t([0, 1]) + den = K.from_t([int(c) for c in par[1][1][1]]) + try: + dinv = K.inv(den) + except ZeroDivisionError: + continue + vals = {} + for j, q in enumerate(par[1][2]): + vals[vnames[j]] = K.scale(K.mul(K.from_t([int(c) for c in q[0][1]]), dinv), Fraction(-1, int(q[1]))) + last = len(vnames) - 1 + rest = t + for j in range(last): + rest = K.sub(rest, K.scale(vals[vnames[j]], Fraction(int(lin[j])))) + vals[vnames[last]] = K.scale(rest, Fraction(1, int(lin[last]))) + out.append((K, vals)) + out.sort(key=lambda kv: kv[0].d) + return out, None if out else f"every equilibrium lies in a number field of degree above {_MAX_DEGREE}" + + +def _linear_point(F, U, fixed, nt, ns, rng, alpha): + """(K, x, theta): an equilibrium x at random values of K away from zero and parameters theta that make it one: + the parameters in products of parameters held at random values until the balances are linear in the others, + those and the free ones of the others at random elements of K (Q, or Q(alpha)), the rest solved over K. None + where the balances have no solution at x or force a parameter to zero.""" + 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)),) + # 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} + vals = dict(xs) + vals.update({i: K.rational(int(v)) for i, v in fixed.items()}) + held = {} + while True: + # the parameter in most products of parameters is held at a value + hits = {} + for i in U: + for m in F[i][0]: + ks = [j for j, e in enumerate(m[ns:], start=ns) if e and j not in held] + if sum(m[j] for j in ks) > 1: + for j in ks: + hits[j] = hits.get(j, 0) + 1 + if not hits: + break + held[max(hits, key=lambda j: (hits[j], -j))] = draw() + vals.update(held) + + def at(m): + # the value of the states and held parameters of a monomial + out = K.one + for j, e in enumerate(m): + if e and (j < ns or j in held): + 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: + row, b = [K.zero] * nt, K.zero + for m, c in F[i][0].items(): + k = next((j - ns for j, e in enumerate(m[ns:], start=ns) if e and j not in held), None) + if k is None: + b = K.sub(b, K.scale(at(m), c)) + else: + row[k] = K.add(row[k], K.scale(at(m), c)) + rows.append(row + [b]) + # the solved parameters in a random order: a fixed order can tie the traces of several blocks to one parameter + piv, r, cols = [], 0, list(range(nt)) + rng.shuffle(cols) + for col in cols: + p = next((i for i in range(r, len(rows)) if not K.is_zero(rows[i][col])), None) + if p is None: + continue + rows[r], rows[p] = rows[p], rows[r] + inv = K.inv(rows[r][col]) + rows[r] = [K.mul(x, inv) for x in rows[r]] + for i in range(len(rows)): + if i != r and not K.is_zero(rows[i][col]): + f = rows[i][col] + rows[i] = [K.sub(x, K.mul(f, y)) for x, y in zip(rows[i], rows[r])] + piv.append(col) + r += 1 + if any(all(K.is_zero(x) for x in row[:nt]) and not K.is_zero(row[nt]) for row in rows): + return None + theta = {j - ns: v for j, v in held.items()} + for k in range(nt): + if k not in piv and k not in theta: + theta[k] = draw() + for j, k in enumerate(piv): + acc = rows[j][nt] + for f, v in theta.items(): + if f not in piv and not K.is_zero(rows[j][f]): + acc = K.sub(acc, K.mul(v, rows[j][f])) + if K.is_zero(acc): + # a parameter the equilibrium forces to zero: a degenerate point + return None + theta[k] = acc + return K, xs, theta + + +def certificate(series, laws=()): + """{"proven": True, ...} where the states of the first condition of `series` with free starts have no nonconstant + rational first integral at a generic point of the parameters, constants and constant inputs, proven at one point + by the eigenvalues at an equilibrium; {"proven": False, "why": ...} where the test does not settle it. With the + conservation `laws` ({state: coefficient}, as from conservation_laws()), the system on a generic level set of + the laws: every rational first integral is then a function of the laws.""" + t0 = time.monotonic() + part = series.parts[0] + seg = part["segs"][0] + st = [str(x) for x in part["st"]] + ns = len(st) + known = set(part["known"]) + F = seg["F"] + U = [i for i in range(ns) if i not in known] + out = {"proven": False, "why": None, "theorem": "Cong, Llibre and Zhang 2011, Theorem 1"} + # a known series that grows at a constant rate is a clock: the flow from a later start is another model + clocks = [i for i in known if F[i][1] and all(not any(m) for P in F[i] for m in P) and any(F[i][0].values())] + reads = {j for i in U for P in F[i] for m in P for j, e in enumerate(m[:ns]) if e} + if reads & set(clocks): + out["why"] = "the right-hand sides read the clock" + return out + rng = session.current().rng("first integrals", tuple(series.coords)) + names = [st[i] for i in U] + params = [str(p) for p in series.params] + last = None + # equilibria away from zero first, over Q; a field of degree r where r blocks have rational traces + plan = [(1, nonzero) for nonzero in (True, False) for _ in range(_DRAWS)] + while plan: + d, nonzero = plan.pop(0) + # the known series (inputs) at constant values, the parameters at a point of Q or of Q(alpha) + fixed = {i: spy.Integer(rng.randint(2, 30)) for i in known} + alpha = _field_poly(rng, d) if d > 1 else None + a = spy.Symbol("a") + theta = {} + 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)) + 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 + if lin is not None: + K, xv, tv = lin + allv = [K.zero] * (ns + len(params)) + for i, v in fixed.items(): + allv[i] = K.rational(int(v)) + for i, v in xv.items(): + allv[i] = v + for k, v in tv.items(): + allv[ns + k] = v + got, why, retry = _attempt(K, F, U, allv, names, len(laws), d) + if got is None: + last = why + 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)) + 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)) + 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: + last = last or f"no isolated equilibrium: {why}" + continue + for K, vals in found: + x = [vals[f"z{j}"] for j in range(len(U))] + gv = {} + for k, v in theta.items(): + if alpha is None: + gv[k] = K.rational(Fraction(int(v.p), int(v.q))) + continue + acc = K.zero + for (e,), c in spy.Poly(v, a).terms(): + acc = K.add(acc, K.scale(_power(K, vals["a"], e), Fraction(int(c.p), int(c.q)))) + gv[k] = acc + for i, v in fixed.items(): + gv[i] = K.rational(int(v)) + for i, xi in zip(U, x): + gv[i] = xi + allv = [gv.get(j, K.zero) for j in range(ns + len(params))] + got, why, retry = _attempt(K, F, U, allv, names, len(laws), d) + if got is None: + last = why + if retry is not None: + plan.insert(0, (retry, nonzero)) + break + 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)) + return out + out["why"] = last or "no equilibrium of the draws settles the test" + out["seconds"] = round(time.monotonic() - t0, 2) + return out diff --git a/src/symident/detection/forward.py b/src/symident/detection/forward.py index a4a2588..f8419ef 100644 --- a/src/symident/detection/forward.py +++ b/src/symident/detection/forward.py @@ -21,7 +21,7 @@ from ..rexpr import sym_sort from ..sym.linalg import sym_rat_recon_big from ..sym.restforward import solve_forward_modular -from .closedform import _strip_name, eval_modq, expired, poly_string, simplify +from .closedform import _strip_name, eval_modq, poly_string, simplify def _nonzero_rows(B, p): @@ -91,6 +91,8 @@ def _basis(rp, nz, p): # points of the shared bank of the forward route, each a kernel call _BANK_MAX = 600 +# leaves of all entries past which each entry has a separate bank +_UNION_CAP = 48 def _fit_entry(primes, bankU_rows, reli_cols, mons, vals_of, vars_): @@ -142,7 +144,7 @@ def fb(reason): supp = sym_sort([znames[i] for i in np.nonzero(v)[0]]) return {"support": supp, "type": "general", "closed_form": False, "reason": reason} - if kcall_fwd is None or expired(ctrl): + if kcall_fwd is None: return [] if list_anchors else fb("forward path unavailable") rdiag = state.env("ROUTEDIAG") npt = len(sc["point0"]) @@ -263,14 +265,10 @@ def moved(lis, seed): groups = [cand[i:i + gsz] for i in range(0, len(cand), gsz)] single = [] for gi, g in enumerate(groups, start=1): - if expired(ctrl): - return fb("forward: timeout in relevance") m = (moved(g, 7919 * gi + 1), moved(g, 7919 * gi + 2)) if m[0] is not False or m[1] is not False: single.extend(g) for l in single: - if expired(ctrl): - return fb("forward: timeout in relevance") ch = np.zeros(len(phys_supp), dtype=bool) for dv in (3, 7, 11): pt = np.array(base0, dtype=np.int64) @@ -299,8 +297,6 @@ def need_of(k, d): def fill_bank_to(n): tries = 0 while bank["V"][0].shape[0] < n and tries < 12 * n: - if expired(ctrl): - break tries += 1 pt = np.array(base0, dtype=np.int64) pt[union_rel] = draw(len(union_rel)) @@ -328,8 +324,6 @@ def rec_entry(reli, c9): entries = {znames[ac]: "1"} entry_reli = {znames[ac]: []} for i, c9 in enumerate(phys_supp): - if expired(ctrl): - return fb("forward: timeout in fitting") nm = znames[c9] reli = rel_by[i] if not reli: @@ -347,8 +341,6 @@ def rec_entry(reli, c9): entry_reli[nm] = [] continue rr = rec_entry(reli, c9) - if rr is None and expired(ctrl): - return fb("forward: timeout in fitting") if rr is None: return fb(f"forward: entry {nm} not a bounded rational (deg>{d_cap})") entries[nm] = simplify(rr["expr"]) @@ -397,7 +389,7 @@ def perprime_forward_shared(sc, kcall, kcall_fwd, znames, z_slots, leaf_names, n rprimes = all_primes() n_prime_fwd = max(2, min(3, len(rprimes) - 1)) P1 = rprimes[0] - if kcall_fwd is None or expired(ctrl): + if kcall_fwd is None: return None rdiag = state.env("ROUTEDIAG") t_f = time.monotonic() @@ -532,8 +524,6 @@ def bisect(lis, seed): """Leaves that move each entry, by halving the groups that move one, a level at a time.""" level = [(lis, seed)] while level: - if expired(ctrl): - return False if map_fn is None: chs = [shift_test(g, sd) for g, sd in level] else: @@ -567,17 +557,27 @@ def changed_at(lis, seed): return None if rdiag: print(f"[fwds] relevance in {n_calls['n']} kernel calls ({el()})") - fwd_cap_dir = max(int(ctrl["relevance_cap_dir"]), 48) - ok_a = [] - for a in range(len(acs)): - u = {x for r in rel_by[a] for x in r} - m = max((len(r) for r in rel_by[a]), default=0) - ok_a.append(len(u) <= fwd_cap_dir and m <= ctrl["relevance_cap_sparse"]) + fwd_cap_dir = max(int(ctrl["relevance_cap_dir"]), _UNION_CAP) + ok_a = [max((len(r) for r in rel_by[a]), default=0) <= ctrl["relevance_cap_sparse"] for a in range(len(acs))] union_rel = sorted({x for a in range(len(acs)) if ok_a[a] for r in rel_by[a] for x in r}) + # past the cap, a bank per entry moves only the leaves of the entry from the base point: a point that + # 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 ''}") # 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"]))) - bank = {"U": np.zeros((0, len(union_rel)), dtype=np.int64), "V": [[] for _ in primes]} + banks = {} + + 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]} + return banks[key] def need_of(k, d): return 2 * mono_table(k, d).shape[0] + 6 @@ -585,44 +585,43 @@ def need_of(k, d): def sample(pt): return [kx_all(pt, pp, acs, solve_rates) for pp in primes] - def fill_bank_to(n): - tries = 0 + def fill_bank_to(bank, n): + cols, tries = bank["cols"], 0 while len(bank["V"][0]) < n and tries < 12 * n: - if expired(ctrl): - break k = 1 if map_fn is None else n - len(bank["V"][0]) tries += k pts = [] for _ in range(k): pt = np.array(base0, dtype=np.int64) - pt[union_rel] = draw(len(union_rel)) + pt[cols] = draw(len(cols)) pts.append(pt) for pt, vs in zip(pts, [sample(pts[0])] if map_fn is None else map_fn(sample, pts)): if vs is None or any(v is None for v in vs): continue - bank["U"] = np.vstack([bank["U"], pt[union_rel].reshape(1, -1)]) + bank["U"] = np.vstack([bank["U"], pt[cols].reshape(1, -1)]) for jp in range(len(primes)): bank["V"][jp].append(vs[jp]) return len(bank["V"][0]) >= n - def val_of(jp, a, c9, n): + def val_of(bank, jp, a, c9, n): return [int(bank["V"][jp][r][a][c9]) for r in range(n)] def rec_entry(a, reli, c9): - reli_cols = [union_rel.index(r) for r in reli] + bank = bank_of(reli) + reli_cols = [bank["cols"].index(r) for r in reli] vars_ = [leaf_names[r] for r in reli] for d in range(d_cap + 1): # a degree whose fit needs more points than the bank may hold is past reach, and so are the higher ones if need_of(len(reli), d) > _BANK_MAX: break mons = mono_table(len(reli), d) - if not fill_bank_to(need_of(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") continue expr = _fit_entry(primes, bank["U"], reli_cols, mons, - lambda jp, need: val_of(jp, a, c9, need), vars_) + lambda jp, need: val_of(bank, jp, a, c9, need), vars_) if expr is not None: return {"expr": expr, "reli": vars_} if rdiag: @@ -651,16 +650,14 @@ def opn(reason, a=a): entry_reli = {znames[ac]: []} res = None for i, c9 in enumerate(phys_supp_of[a]): - if expired(ctrl): - res = opn("forward: timeout") - break nm = znames[c9] reli = rel_by[a][i] if not reli: - if not fill_bank_to(1): + bank = bank_of([]) + if not fill_bank_to(bank, 1): res = opn("forward: empty bank") break - resc = [val_of(jp, a, c9, 1)[0] for jp in range(len(primes))] + resc = [val_of(bank, jp, a, c9, 1)[0] for jp in range(len(primes))] try: rc = sym_rat_recon_big(np.array([resc], dtype=np.int64), [int(p) for p in primes]) except Exception as exc: @@ -674,8 +671,7 @@ def opn(reason, a=a): continue rr = rec_entry(a, reli, c9) if rr is None: - res = opn("forward: timeout in fitting" if expired(ctrl) - else f"forward: entry {nm} not a bounded rational") + res = opn(f"forward: entry {nm} not a bounded rational") break entries[nm] = simplify(rr["expr"]) entry_reli[nm] = rr["reli"] @@ -753,7 +749,7 @@ def groups_for(idx): 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: timeout"} for i in gidx] + "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], @@ -776,6 +772,9 @@ def groups_for(idx): if res[k].get("closed_form"): out[i] = res[k] if rdiag: + for e in out: + 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)") diff --git a/src/symident/detection/hybrid.py b/src/symident/detection/hybrid.py index 88252e8..46c9b10 100644 --- a/src/symident/detection/hybrid.py +++ b/src/symident/detection/hybrid.py @@ -7,7 +7,7 @@ import numpy as np import sympy as spy -from .. import session, state +from .. import _core, session, state from ..gfp import PRIMES from ..rexpr import sym_sort from ..sym.scaling import scaling_symmetries_multi @@ -90,6 +90,11 @@ class HybridError(ValueError): """A hybrid model the analysis does not support or cannot certify.""" +def _applies(e, c): + """Whether event `e` applies to the condition of index `c`: every condition without "cond".""" + return e.get("cond") is None or c in [int(k) for k in e["cond"]] + + class _Cond: """One condition in the coordinates of the model: substitutions, initial values, observables, events.""" @@ -142,7 +147,6 @@ def __init__(self, hy, kw, regimes=None): self.fixed += [str(s) for s in CONSTS.values() if s in used and str(s) not in self.fixed] self.kw = dict(kw, fixed=list(self.fixed)) self.regimes, self.excluded = self._regimes() - self.roots = {r["surface"] for r in hy.roots} decl = self._declarations(regimes) for cd in self.conds: self._select(cd, decl[cd.index]) @@ -213,6 +217,8 @@ def app(e, t_sub=t_sub, gp=gp): cd.obs = {k: app(v) for k, v in g.items()} cd.events = [] for i, e in enumerate(self.time_events): + if not _applies(e, c): + continue tv = e["time"] vv = e["value"] if grid is not None and tv in grid.colnames(): @@ -224,6 +230,8 @@ def app(e, t_sub=t_sub, gp=gp): 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] + @@ -323,7 +331,7 @@ def _select(self, cd, decl): 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 self.roots] + 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: @@ -372,7 +380,7 @@ def _reach(self, cd, pair): def visibility(self, cd, j): """Whether the switch on surface j is visible, invisible or undecided in the observables of `cd`.""" - if j in self.roots: + if j in {r["surface"] for r in cd.roots}: return _VISIBLE pairs = [] for a in cd.regimes: @@ -529,22 +537,23 @@ def _copies(st, names=None): if st.unknown or any(v != _VISIBLE for v in cd.vis.values()): points.append((None, None)) resets = [] - for r in st.hy.roots: + for r in cd.roots: j = r["surface"] sol = st.on_surface(cd, j) if j in cd.surfaces and st.hy.kind[j] == "state" else None resets.append((sol if sol is not None and str(sol[0]) in st.dyn else None, r["event"])) # a copy from a point of a surface names that surface under "surface" for sol, ev, on in [(s, None, j) for s, j in points] + [(s, e, None) for s, e in resets]: - pt = {} + pt, mine = {}, [] for x in st.dyn: if sol is None or _sym(x) != sol[0]: pt[_sym(x)] = _sym(names(f"{x}_si")) - fresh.append(str(pt[_sym(x)])) + mine.append(str(pt[_sym(x)])) tsym = None if st.clock: tsym = _sym(names("si_time")) - fresh.append(str(tsym)) + mine.append(str(tsym)) pt[TIME] = tsym + fresh += mine pt.update({_sym(u): v for u, v in _start_inputs(st, cd).items()}) if sol is not None: pt[sol[0]] = sol[1].xreplace(pt) @@ -558,7 +567,8 @@ def _copies(st, names=None): 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}, st) + "inputs": {u: pt[_sym(u)] for u in st.inputs}, "surface": on, + "block": tuple(mine)}, st) return copies, fresh @@ -790,7 +800,7 @@ def regular(e, sub): 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 st.root_events] + [(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] @@ -874,7 +884,7 @@ def _coords(st): pars |= {str(s) for s in v.free_symbols} for e in cd.events: pars |= {str(s) for s in e["time"].free_symbols | e["value"].free_symbols} - for e in st.root_events: + for e in cd.root_events: pars |= {str(s) for s in cd.apply(_parse(e["value"])).free_symbols} pars -= set(st.f) | {"time"} | set(st.fixed) | set(st.inputs) | set(st.unknown) free = [] @@ -944,7 +954,7 @@ def _bracket(st, X, f): 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 st.root_events] + "method": e.get("method", "replace")} for e in cd.root_events] def _starts(st, cd): @@ -1215,7 +1225,7 @@ def _scaling_candidates(st): 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 st.root_events] + "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'])}") @@ -1367,10 +1377,13 @@ def _settings(st): def _entering(st, copies, fresh): """The fresh coordinates that can enter a row: entry values of states that reach an observable, and the clock.""" - fr, out = set(fresh), set() + fr, out, memo = set(fresh), set(), {} for cp in copies: pair = (cp["sides"], cp["switch"][1]) if cp.get("switch") is not None else (cp["sides"], cp["sides"]) - for x in st._reach(cp["cd"], pair): + key = (id(cp["ic"]), tuple(pair[0]), tuple(pair[1])) + if key not in memo: + memo[key] = _reach_held(st, cp, pair, fr) + for x in memo[key]: v = cp["ic"].get(x) if v is not None: out |= {str(a) for a in spy.sympify(v).free_symbols} & fr @@ -1379,20 +1392,102 @@ def _entering(st, copies, fresh): return out +def _reach_held(st, cp, pair, fr): + """The states that reach an observable of the copy in either regime of `pair`, with the held states at their + 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): + 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 + # of the pair, so the Lie derivatives of the copy are those of the fields restricted to that level set + held = {x for x in st.dyn if ic.get(x) is not None and not {str(a) for a in spy.sympify(ic[x]).free_symbols} & fr} + while True: + sub = {_sym(x): spy.sympify(ic[x]) for x in held} + drop = {x for x in held if not all(_regular_zero(f[x], sub) for f, _ in models)} + if not drop: + break + held -= drop + out = set() + for _, h in models: + for v in h.values(): + out |= {str(a) for a in spy.sympify(v).xreplace(sub).free_symbols if str(a) in st.f} + while True: + more = set(out) + for f, _ in models: + for x in out - held: + more |= {str(a) for a in spy.sympify(f[x]).xreplace(sub).free_symbols if str(a) in st.f} + if more == out: + return out - held + out = more + + +def _rank_mod(A, p): + """The rank of the columns of the integer matrix `A` modulo p.""" + return 0 if A.size == 0 else int(_core.sym_rref_mod((A.T % p).astype(np.float64), p)["rank"]) + + def _relaxed_dim(res, coords, fresh, entering): """(dimension, proven): the dimension of the stacked kernel projected onto the coordinates of the model.""" need, sub = _projected(res, coords) if sub is None or sub.shape[1] == 0: return need, True - from .. import _core ker = res["info"]["kernel"] - within = sub.shape[1] - int(_core.sym_rref_mod(sub.T.astype(np.float64), int(ker["p"]))["rank"]) + within = sub.shape[1] - _rank_mod(sub, int(ker["p"])) idle = [z for z in ker["coords"] if z in set(fresh) and z not in entering] # proven where every direction within the fresh coordinates alone is the unit direction of one that enters no row return need, within == len(idle) _OF_FRESH = "the fresh coordinates of the switch surfaces" +_FULL_BLOCKS = "the copies from the start and from the start points whose fresh columns have full rank" + + +def _dropping_blocks(res, coords, copies, entering): + """The start points whose entering fresh columns drop rank at the sample point of the kernel.""" + ker = res["info"].get("kernel") + if ker is None: + return set() + kc, p = list(ker["coords"]), int(ker["p"]) + N = np.asarray(ker["N"], dtype=np.int64).reshape(len(kc), -1) + if N.shape[1] == 0: + return set() + at = [kc.index(z) for z in coords if z in kc] + base = _rank_mod(N[at, :], p) + out = set() + for blk in {cp["block"] for cp in copies if cp.get("block")}: + own = [kc.index(z) for z in blk if z in kc and z in entering] + # the kernel within the fresh columns has a part on this start point exactly when the rank rises + if own and _rank_mod(N[at + own, :], p) > base: + out.add(blk) + return out + + +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 + rows = dict(_rows_model(st, kept, fresh), reconstruct=False, verify=False) + with state.options(keep_kernel=True, random_kernel=False, open_coords=tuple(fresh), inner=True): + res = detection_with_primes(rows) + need, proven = _relaxed_dim(res, coords, fresh, _entering(st, kept, fresh)) + return need if proven else None, res, rows + + +def _without_dropping_blocks(st, copies, fresh, res, coords, entering, start): + """The dimension of the projection, proven on the copies whose start points keep full column rank, or None; + `start` is the dimension on the copies without fresh coordinates, None where not taken.""" + drop = _dropping_blocks(res, coords, copies, entering) + if not drop: + return None + kept = [cp for cp in copies if cp.get("block") not in drop] + if start is not None and not any(cp.get("block") for cp in kept): + return start + return _on_copies(st, kept, fresh, coords)[0] def _at_random(rows, res, coords, fresh, entering, need): @@ -1430,7 +1525,6 @@ def _minor_bound(rows, res, cols): def _projected(res, coords): """The dimension of the stacked kernel projected onto the coordinates of the model, and that projection.""" - from .. import _core ker = res["info"].get("kernel") if ker is None and res.get("identifiable"): return len([z for z in coords if z not in res["info"]["coordinates"]]), None @@ -1449,7 +1543,7 @@ def _projected(res, coords): if not rows or N.shape[1] == 0: return len(missing), None sub = N[rows, :] % int(ker["p"]) - return len(missing) + int(_core.sym_rref_mod(sub.T.astype(np.float64), int(ker["p"]))["rank"]), sub + return len(missing) + _rank_mod(sub, int(ker["p"])), sub def hybrid_detection(hy, kw, regimes=None, setup=None): @@ -1463,6 +1557,7 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): 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 while True: names = _Names(_model_symbols(st)) jets = _jet_chains(st, order, names) @@ -1472,6 +1567,13 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): 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 + plain = [cp for cp in copies if not cp.get("block")] + start, res, rows = _on_copies(st, plain, [], coords) + if start == 0: + copies, fresh, short = plain, [], False + break rows = _rows_model(st, copies, fresh, jets, jet_fresh, order) # the closed forms below read only directions without fresh coordinates with state.options(keep_kernel=True, random_kernel=True, open_coords=tuple(fresh)): @@ -1484,6 +1586,10 @@ def hybrid_detection(hy, kw, regimes=None, setup=None): entering = _entering(st, copies, fresh) need, proven = _relaxed_dim(res, coords, fresh, entering) projection = None + if not proven and not jets: + fewer = _without_dropping_blocks(st, copies, fresh, res, coords, entering, start) + if fewer is not None and fewer <= need: + projection, need, proven = {"status": "proven", "of": _OF_FRESH, "rows": _FULL_BLOCKS}, fewer, True if not proven: projection, need = _at_random(rows, res, coords, fresh, entering, need) if jets: diff --git a/src/symident/detection/interp.py b/src/symident/detection/interp.py index 1ead173..f679f0e 100644 --- a/src/symident/detection/interp.py +++ b/src/symident/detection/interp.py @@ -7,8 +7,8 @@ from ..gfp import PRIMES, mono_table, null_residues from ..rexpr import sym_sort from ..sym.recast import drop_monomial_content, exp_backsub_expr, trig_full_angle -from .closedform import expired, poly_string, simplify -from .perprime import _TIMEOUT, _fallback, _lift_const, pinned_monomials +from .closedform import poly_string, simplify +from .perprime import _fallback, _lift_const, pinned_monomials from .relevance import dense_need, direction_relevance from .sparse import _default_kbatch, _pivots_eq, general_rational_entry, sparse_entry @@ -85,8 +85,6 @@ def nv(rp, p, zvals=zvals0): def fallback(reason=None): return _fallback(box["pool_next"], znames, base_nv, reason) - if expired(ctrl): - return fallback(_TIMEOUT) def const_entry(col): if box["const_base"] is None: @@ -158,8 +156,6 @@ def ex(v): tries = 0 rows_u, rows_r = [], [[] for _ in support_cols] while len(rows_u) < max_need and tries < 30 * max_need: - if expired(ctrl): - return fallback(_TIMEOUT) if not rows_u and tries >= 2 * max_need: 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 @@ -223,8 +219,6 @@ def ex(v): 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 and expired(ctrl): - return fallback(_TIMEOUT) 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=" diff --git a/src/symident/detection/ioproj.py b/src/symident/detection/ioproj.py new file mode 100644 index 0000000..99a4be2 --- /dev/null +++ b/src/symident/detection/ioproj.py @@ -0,0 +1,1503 @@ +"""Input-output projections for the exact count (docs/method/global.rst, "The exact count"): per observable the relation +of one derivative with the derivatives below a profile: the support found modulo a prime, the coefficients interpolated +in the parameters, the relation checked as an identity of polynomials and the coefficients shown to lie in the field of +the output coefficients.""" + +import ast +import math +import os +import tempfile +from fractions import Fraction + +import numpy as np +import sympy as spy + +from .. import _core +from ..gfp import all_primes, prime_run, sieve +from . import work + +# the largest number of candidate monomials of one projection modulo a prime +CAP = 6000 +# the largest number of terms of a projection whose coefficients are interpolated +TERMS = 1500 +# the largest number of unknowns of one interpolation in the parameters +_UNKNOWNS = 6000 +# the largest box of the numerators interpolated densely, all at once +_DENSE = 1500 +# the most terms of a derivative whose next derivative a profile reads +_JET = 5000 +# the largest total degree of a projection tried +_DEGREE = 14 +# the most candidate monomials of a projection taken from bounds on the Newton polytope +POLYTOPE = 10000 +# the threads of the kernels, set by the callers +THREADS = [1] + + +def _threads(): + return max(1, int(THREADS[0])) + + +def _inv(a, p): + """Elementwise inverse modulo p of a nonzero int64 array.""" + return _pow(a, p - 2, p) + + +class _Polys: + """Polynomials of the ring of the relations as term arrays, evaluated at many points modulo p in C++.""" + + def __init__(self, polys, nv): + exps, coefs, off = [], [], [0] + for P in polys: + for m, c in P.terms(): + exps.append(m) + coefs.append((int(c.numerator), int(c.denominator))) + off.append(len(exps)) + self.exps = np.array(exps, dtype=np.int32).reshape(-1, nv) + self.coefs, self.off, self._res = coefs, np.array(off, dtype=np.int64), {} + + 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()) + + +def _pow(a, e, p): + """Elementwise power modulo p of an int64 array.""" + out = np.ones_like(a) + b = a % p + while e: + if e & 1: + out = out * b % p + b = b * b % p + e >>= 1 + return out + + +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): + self.numer, self.exps = numer, tuple(exps) + + +class Jets: + """The derivatives of the observables along the flow as Quo over the factors Q, the product of the distinct + denominators of the right-hand sides, and E_r, the denominator of observable r: with L(P) = P~ / Q for a polynomial + P, the derivative of N / (Q^a E^b) is (N~ Q E - N (a Q~ E + b E~ Q)) / (Q^(a+2) E^(b+1)).""" + + def __init__(self, rel): + self.rel = rel + R = rel.R.ring if hasattr(rel.R, "ring") else rel.R + self.R = R + gens = list(R.gens) + self.X = [None if x is None else gens[rel.names.index(str(x))] for x in rel.X] + + def parts(q): + n, d = (q.numer, q.denom) if hasattr(q, "numer") else (q, R.one) + n, d = R(n) if n.ring != R else n, R(d) if d.ring != R else d + if d.is_ground: + return n * R.domain.quo(R.domain.one, d.LC), None + c = d.LC + return n * R.domain.quo(R.domain.one, c), d * R.domain.quo(R.domain.one, c) + + self._parts = parts + fs = [None if f is None else parts(f) for f in rel.f] + dens = [] + for f in fs: + if f is not None and f[1] is not None and f[1] not in dens: + dens.append(f[1]) + Q = R.one + for d in dens: + Q = Q * d + self.Fh = [] + for f in fs: + if f is None: + self.Fh.append(None) + continue + n, d = f + t = n + for g in dens: + if d is None or g != d: + t = t * g + self.Fh.append(t) + self.Q = None if not dens else Q + self.Qt = None if self.Q is None else self.tilde(self.Q) + self.fac = [] if self.Q is None else [self.Q] + self._obs = {} + + def tilde(self, P): + """P~ = Q L(P), L the derivative along the flow.""" + out = self.R.zero + for x, F in zip(self.X, self.Fh): + if x is not None and F is not None: + d = P.diff(x) + if d: + out = out + d * F + return out + + def _factor(self, E): + if E not in self.fac: + self.fac.append(E) + return self.fac.index(E) + + def observable(self, r, m): + """The derivatives 0..m of observable r as Quo.""" + y = self.rel.y[r] + key = (r, str(y)) + if key not in self._obs: + M, E = self._parts(y) + ie = None if E is None else self._factor(E) + self._obs[key] = [[(M, 0, 0)], ie, None if E is None else self.tilde(E)] + lst, ie, Et = self._obs[key] + E = None if ie is None else self.fac[ie] + while len(lst) <= m: + N, a, b = lst[-1] + Nt = self.tilde(N) + if self.Q is None and E is None: + lst.append((Nt, 0, 0)) + elif self.Q is None: + lst.append((Nt * E - N * Et * b, 0, b + 1)) + elif E is None: + 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]] + + def within(self, ms): + """Whether each derivative of observable r up to order ms[r] is the derivative of one with at most _JET + terms, computed up to the first that has more.""" + for r, m in enumerate(ms): + for k in range(1, m + 1): + if len(self.observable(r, k - 1)[k - 1].numer) > _JET: + return False + return True + + def quo(self, N, a=0, ie=None, b=0): + e = {} + if a and self.Q is not None: + e[0] = a + if b and ie is not None: + e[ie] = e.get(ie, 0) + b + return Quo(N, sorted(e.items())) + + def state(self, k): + return Quo(self.X[k], []) + + def denom(self, q): + out = self.R.one + for k, e in q.exps: + out = out * self.fac[k] ** e + return out + + +def jets_of(rel): + """The Jets of `rel`, built once.""" + if not hasattr(rel, "_qjets"): + rel._qjets = Jets(rel) + return rel._qjets + + +class Base: + """The base functions of a projection, Quo over the factors of their Jets, evaluated together at many points + modulo p.""" + + def __init__(self, rel, funcs): + self.J = jets_of(rel) + self.funcs = list(funcs) + self.nv = len(rel.names) + self.nf = len(self.J.fac) + self.P = _Polys([q.numer for q in self.funcs] + list(self.J.fac), self.nv) + + def values(self, pts, p): + """(rows kept, values): the points where no denominator vanishes and the base functions there.""" + V = self.P(pts, p) + nb = len(self.funcs) + num, F = V[:, :nb], V[:, nb:] + used = sorted({k for q in self.funcs for k, _ in q.exps}) + ok = (F[:, used] != 0).all(axis=1) if used else np.ones(len(V), dtype=bool) + num, F = num[ok], F[ok] + den = np.ones_like(num) + for v, q in enumerate(self.funcs): + for k, e in q.exps: + den[:, v] = den[:, v] * _pow(F[:, k], e, p) % p + return ok, num * _inv(den, p) % p + + +def _monomials(nb, degree, top=None, cap_top=None): + """Exponent vectors of total degree at most `degree`, the exponent of variable `top` at most `cap_top`, lowest + degree first.""" + out = [] + for d in range(degree + 1): + for m in _exps(nb, d): + if top is None or m[top] <= cap_top: + out.append(m) + return out + + +def _exps(nb, d): + if nb == 0: + return [()] if d == 0 else [] + return [(a,) + r for a in range(d, -1, -1) for r in _exps(nb - 1, d - a)] + + +def _count(nb, degree, cap_top, cap2=None): + """The number of exponent vectors of _monomials(nb, degree, top, cap_top), with `cap2` also those with the + 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)) + + +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()) + + +class Projection: + """A projection of the relations `rel`: the relation of one top function with the derivatives of each observable + r up to order ms[r] and the input states read. For an observable, the top is the derivative of the order of the + profile and ms the profile less one; for the start of a state, the top is the state, and `capped` = (variable, + cap) bounds the degree of a derivative on top of the profile below that of the projection of the observable.""" + + 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))] + if extra is not None: + top, funcs = len(funcs), funcs + [J.state(extra)] + self.base = Base(rel, funcs) + self.nb = len(funcs) + self.top = top + self.mons = None + self.capped = None + + @classmethod + def output(cls, rel, h, i, pos, rng): + """None where a derivative of the base is that of one with more than _JET terms.""" + ms = [k - 1 for k in h] + ms[i] = h[i] + if not jets_of(rel).within(ms): + return None + return cls(rel, ms, pos, rng, top=sum(m + 1 for m in ms[:i]) + h[i]) + + @classmethod + def state(cls, rel, h, k, pos, rng, lift=None): + """With lift = (i, d), the base holds the derivative of observable i of order h[i], whose projection has + degree d in it, at degree below d: a normal form modulo the projection. None as in output().""" + ms = [x - 1 for x in h] + if lift is not None: + ms[lift[0]] = h[lift[0]] + if not jets_of(rel).within(ms): + 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) + return pr + + def points(self, theta, p, m): + """Base values at m random points of the states with the parameters at theta.""" + nv = self.base.nv + out = [] + if not hasattr(self, "_gen"): + self._gen = np.random.default_rng(self.rng.getrandbits(64)) + while sum(len(o) for o in out) < m: + k = m - sum(len(o) for o in out) + 4 + pts = self._gen.integers(1, p, size=(k, nv), dtype=np.int64) + pts[:, self.pos] = np.array(theta, dtype=np.int64) % p + _, B = self.base.values(pts, p) + out.append(B) + return np.vstack(out)[:m] + + def search(self, theta, p, stop, cap=CAP, top_degree=None): + """The exponent vectors of the support of the relation at the parameter point theta, of degree at most + `top_degree` in the top function; None where no relation has at most `cap` candidate monomials or the + kernel is not one vector. The boxes up to a quarter of the cap first, then the monomials inside the + bounds on the Newton polytope (newton_bounds()), then the larger boxes.""" + pool = [np.zeros((0, self.nb), dtype=np.int64)] + + def kernel(box): + mons = box if isinstance(box, list) else _monomials(self.nb, box[0], self.top, box[1]) + if self.capped is not None: + 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) + work.tick(A.shape) + return mons, _core.io_kernel(A, p, _threads()) + + def found(mons, v): + S = [mons[j] for j in range(len(mons)) if v[j]] + # a relation without the function on top is one of a smaller profile + if not any(m[self.top] for m in S): + return None + self.mons = S + return S + + # the largest boxes below a rising cap: one without a relation holds none of the smaller ones, and a + # kernel of one vector is the relation + done = set() + for c in (cap // 4, None, cap // 2, cap): + if c is None: + if self.capped is not None or work.ticks() > stop: + continue + mons = self.polytope(theta, p, stop) + if self.newton and top_degree is not None and self.newton[_unit(self.nb, self.top)][1] > top_degree: + # the projection has a larger degree in the top function, and every relation is a multiple + return None + if mons is None: + continue + mons, ker = kernel(mons) + 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] + 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: + continue + done.add(b) + mons, ker = kernel(b) + if len(ker["free"]) == 1: + return found(mons, ker["basis"][0]) + if not ker["free"]: + continue + # several relations: the least box with one + for box in sorted(x for x in boxes if x[0] <= b[0] and x[1] <= b[1]): + if work.ticks() > stop: + return None + mons, ker = kernel(box) + if len(ker["free"]) == 1: + return found(mons, ker["basis"][0]) + if ker["free"]: + return None + return None + return None + + def weights(self): + """Weights of the base functions for bounds on the Newton polytope: the order of each derivative plus one, + one for the inputs and a state on top.""" + out = [k + 1 for m in self.ms if m >= 0 for k in range(m + 1)] + return out + [1] * (self.nb - len(out)) + + def polytope(self, theta, p, stop): + """The monomials inside the bounds on the Newton polytope of the projection at the parameter point theta + (newton_bounds()), at most POLYTOPE of them, the bounds in self.newton; None where they are not found.""" + self.newton = None + sl = _Slice(self, theta, p, self.rng, stop) + if not sl.ok: + 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)] + bounds = newton_bounds(sl, fixed, stop) + if bounds is None: + return None + mons = _inside(nb, bounds, POLYTOPE) + # random weights while the candidates exceed the cap + for _ in range(4): + if mons is not None or work.ticks() > stop: + break + more = newton_bounds(sl, [tuple(rng.randrange(0, 4) for _ in range(nb)) for _ in range(8)], stop) + if more is None: + break + bounds.update(more) + mons = _inside(nb, bounds, POLYTOPE) + self.newton = bounds + return mons + + def vector(self, theta, p, mons=None): + """The kernel vector on the monomials `mons` at the parameter point theta, last entry one; None where the + kernel is not one vector with that entry nonzero.""" + mons = mons or self.mons + B = self.points(theta, p, len(mons) + 6) + A = _mono_matrix(B, mons, p) + work.tick(A.shape) + ker = _core.io_kernel(A, p, _threads()) + if ker["free"] != [len(mons) - 1]: + return None + return np.asarray(ker["basis"][0], dtype=np.int64) + + +def _unit(n, v): + return tuple(1 if u == v else 0 for u in range(n)) + + +def _gf_terms(P, sub, p): + """{((variable, exponent), ...): coefficient} of the polynomial P modulo p, the variables of `sub` at their + values.""" + out = {} + for m, c in P.terms(): + v = int(c.numerator) % p * pow(int(c.denominator) % p, -1, p) % p + key = [] + for g, e in enumerate(m): + if not e: + continue + if g in sub: + v = v * pow(sub[g], e, p) % p + else: + key.append((g, e)) + key = tuple(key) + out[key] = (out.get(key, 0) + v) % p + return {k: c for k, c in out.items() if c} + + +def _msolve_count(names, polys, p): + """The number of distinct solutions over the algebraic closure of GF(p) of the polynomials (dicts over the + indices of `names`), from the rational parametrization of msolve; None where the solutions are not finitely + many, the system is past the caps of msolve (a tenth of msolve_entries) or msolve fails.""" + from ..sym.msolve import MsolveMissingError, _msolve_binary + + def text(d): + out = [] + for key, c in d.items(): + mono = "*".join(names[g] + (f"^{e}" if e > 1 else "") for g, e in key) + out.append(f"{c}*{mono}" if mono else f"{c}") + return "+".join(out) or "0" + + try: + binary = _msolve_binary() + except MsolveMissingError: + return None + eqs = [text(d) for d in polys] + if work.msolve_too_large(names, eqs): + return None + 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: + fh.write(",".join(names) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") + # a count of the search takes a tenth of the cap of msolve, and the matrices of msolve count on the clock + # of the search + with work.local_caps(msolve_entries=work.cap("msolve_entries") / 10): + r = work.run_msolve([binary, "-f", fi, "-o", fo, "-P", "1", "-t", str(_threads())]) + work.tick(int(r.entries)) + txt = open(fo).read().strip() if os.path.exists(fo) else "" + if r.returncode != 0 or not txt: + return None + data = ast.literal_eval(txt.rstrip(":")) + if data == [-1]: + return 0 + if data[0] != 0 or data[1][2] <= 0: + return None + return int(data[1][2]) + + +class _Slice: + """The base functions of a projection at the parameter point theta modulo p as a polynomial system: the states + read that give the Jacobian of the base functions rank nb - 1 stay unknown, the others take random values, each + factor of the denominators is an unknown u_k, and w inverts the product of the factors.""" + + def __init__(self, pr, theta, p, rng, stop): + self.ok, self.p, self.stop = False, p, stop + J = jets_of(pr.rel) + funcs, nb = pr.base.funcs, pr.nb + used = sorted({k for q in funcs for k, _ in q.exps}) + polys = [q.numer for q in funcs] + [J.fac[k] for k in used] + nv = len(pr.rel.names) + appear = sorted({g for P in polys for m in P.monoms() for g, e in enumerate(m) if e} - set(pr.pos)) + pt = [rng.randrange(1, p) for _ in range(nv)] + for k, v in zip(pr.pos, theta): + pt[k] = int(v) % p + ok, vals = pr.base.values(np.array([pt], dtype=np.int64), p) + if not ok[0] or len(appear) < nb - 1: + return + rows = _gradients(J, funcs, [J.R.gens[g] for g in appear], pt, p) + if rows is None: + return + free = [] + for c in range(len(appear)): + if _rank([[r[j] for r in rows] for j in free + [c]], p) == len(free) + 1: + free.append(c) + if len(free) == nb - 1: + break + if len(free) != nb - 1: + return + self.free = [appear[c] for c in free] + sub = {g: pt[g] for g in range(nv) if g not in self.free} + # unknowns: w, the factors, the free states, t, s + self.names = ["w"] + [f"u{k}" for k in used] + [f"x{g}" for g in self.free] + ["t", "s"] + at = {g: 1 + len(used) + j for j, g in enumerate(self.free)} + self.u = {k: 1 + j for j, k in enumerate(used)} + self.t, self.s = len(self.names) - 2, len(self.names) - 1 + + def remap(d): + return {tuple((at[g], e) for g, e in key): c for key, c in d.items()} + + self.N = [remap(_gf_terms(q.numer, sub, p)) for q in funcs] + self.F = {k: remap(_gf_terms(J.fac[k], sub, p)) for k in used} + self.dens = [tuple((self.u[k], e) for k, e in q.exps) for q in funcs] + self.image = [int(v) for v in vals[0]] + self.nb, self.used, self.rng = nb, used, rng + self.ok = True + self.fiber = self.count(self.image) + self.ok = bool(self.fiber) + + def count(self, values, direc=None, weights=None, torus=False): + """The number of points of the slice where the base functions take the values c_v + b_v t^(w_v), c the + values, b the direction and w the weights, with t nonzero for `torus`; the values alone without a + direction.""" + p = self.p + eqs = [] + for v in range(self.nb): + d = dict(self.N[v]) + den = self.dens[v] + if values[v] % p: + d[den] = (d.get(den, 0) - values[v]) % p + if direc is not None and direc[v] % p: + key = tuple(sorted(den + ((self.t, weights[v]),))) if weights[v] else den + d[key] = (d.get(key, 0) - direc[v]) % p + eqs.append({k: c for k, c in d.items() if c}) + for k in self.used: + d = {m: (-c) % p for m, c in self.F[k].items()} + key = ((self.u[k], 1),) + 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] + if direc is not None: + names = names + ["t"] + if torus: + names = names + ["s"] + eqs.append({((self.t, 1), (self.s, 1)): 1, (): p - 1}) + return _msolve_count(names, eqs, p) if work.ticks() <= self.stop else None + + +def _gradients(J, funcs, gens, pt, p): + """Per base function N / prod F_k^e_k the gradient in `gens` at the point pt modulo p, by (grad N - N sum_k + e_k grad F_k / F_k) / prod F_k^e_k; None at a pole.""" + out = [] + for q in funcs: + polys = [q.numer] + [q.numer.diff(x) for x in gens] + 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] + 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)] + at += 1 + len(gens) + if not F: + return None + den = den * pow(F, e, p) % p + iF = pow(F, -1, p) + lg = [(a + e * b * iF) % p for a, b in zip(lg, dF)] + iD = pow(den, -1, p) + out.append([(a - n * b) * iD % p for a, b in zip(g, lg)]) + return out + + +def newton_bounds(sl, weights, stop): + """{w: (low, high)}: per weight vector w the least and the largest of over the support of the projection, + modulo p. A curve c + b t^w with random c and b meets the image of the base functions where the projection P has + the roots of P(c + b t^w), of degree high(w), each the image of the points of one fiber; the curve b t^w with t + nonzero meets it in high(w) - low(w) points. Counts of points only propose: the support found from them is + checked as every other. None where a count fails.""" + p, rng, nb, k = sl.p, sl.rng, sl.nb, sl.fiber + out = {} + for w in weights: + if work.ticks() > stop: + return None + c = [rng.randrange(1, p) for _ in range(nb)] + b = [rng.randrange(1, p) for _ in range(nb)] + hi = sl.count(c, b, w) + if hi is None or hi % k: + return None + hi //= k + lo = 0 + if sum(1 for x in w if x) > 1 and hi: + n = sl.count([0] * nb, b, w, torus=True) + if n is None or n % k: + return None + lo = hi - n // k + out[tuple(w)] = (lo, hi) + return out + + +def _inside(nb, bounds, cap): + """The exponent vectors m with low(w) <= <= high(w) for the bounds {w: (low, high)}, lowest total degree + first; None for more than cap of them. Every weight is nonnegative, so a partial sum above high(w) stays above.""" + W = np.array(list(bounds), dtype=np.int64).reshape(-1, nb) + lo = np.array([b[0] for b in bounds.values()], dtype=np.int64) + hi = np.array([b[1] for b in bounds.values()], dtype=np.int64) + per = [] + for v in range(nb): + caps = [h // w[v] for w, h in zip(W, hi) if w[v]] + per.append(min(caps) if caps else 0) + # the largest sum the variables from v on can add + rest = np.zeros((nb + 1, len(W)), dtype=np.int64) + for v in range(nb - 1, -1, -1): + rest[v] = rest[v + 1] + W[:, v] * per[v] + cur = np.zeros((1, 0), dtype=np.int64) + S = np.zeros((1, len(W)), dtype=np.int64) + for v in range(nb): + e = np.arange(per[v] + 1, dtype=np.int64) + S2 = (S[:, None, :] + e[None, :, None] * W[None, None, :, v]).reshape(-1, len(W)) + C2 = np.hstack([np.repeat(cur, len(e), axis=0), np.tile(e, len(cur))[:, None]]) + keep = (S2 <= hi).all(axis=1) & (S2 + rest[v + 1] >= lo).all(axis=1) + cur, S = C2[keep], S2[keep] + if len(cur) > 8 * cap: + return None + if len(cur) > cap or not len(cur): + return None + out = [tuple(int(x) for x in m) for m in cur] + out.sort(key=lambda m: (sum(m), tuple(-x for x in m))) + return out + + +# rational functions of one variable modulo p + + +def _poly_trim(a): + while a and not a[-1]: + a.pop() + return a + + +def _newton(ts, vs, p): + """Coefficients (lowest first) of the polynomial of degree < len(ts) through the points.""" + n = len(ts) + c = list(vs) + for j in range(1, n): + for i in range(n - 1, j - 1, -1): + c[i] = (c[i] - c[i - 1]) * pow(ts[i] - ts[i - j], -1, p) % p + out = [0] * n + for i in range(n - 1, -1, -1): + # out = out * (x - ts[i]) + c[i] + out = [(a - ts[i] * b) % p for a, b in zip([0] + out[:-1], out)] + out[0] = (out[0] + c[i]) % p + return out + + +def _pdivmod(a, b, p): + a = list(a) + q = [0] * max(1, len(a) - len(b) + 1) + inv = pow(b[-1], -1, p) + for k in range(len(a) - len(b), -1, -1): + c = a[k + len(b) - 1] * inv % p + q[k] = c + 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]) + + +def _psub(a, b, p): + n = max(len(a), len(b)) + return _poly_trim([((a[i] if i < len(a) else 0) - (b[i] if i < len(b) else 0)) % p for i in range(n)]) + + +def _pmul(a, b, p): + if not a or not b: + return [] + out = [0] * (len(a) + len(b) - 1) + for i, x in enumerate(a): + if x: + for j, y in enumerate(b): + out[i + j] = (out[i + j] + x * y) % p + return out + + +def ratrec1(ts, vs, p): + """(numerator, denominator) of the rational function of one variable with these values, the denominator monic: + the step of the extended Euclidean algorithm before the quotient of largest degree, at least three, so that the + degrees leave three of the points over; None otherwise.""" + m = [1] + for t in ts: + m = _pmul(m, [(-t) % p, 1], p) + r0, r1 = m, _poly_trim(_newton(ts, vs, p)) + if not r1: + return [], [1] + s0, s1 = [], [1] + best, gap = None, 2 + while r1: + q, r = _pdivmod(r0, r1, p) + if len(q) - 1 > gap: + best, gap = (r1, s1), len(q) - 1 + r0, r1 = r1, r + s0, s1 = s1, _psub(s0, _pmul(q, s1, p), p) + if best is None: + return None + r1, s1 = best + c = pow(s1[-1], -1, p) + return [x * c % p for x in r1], [x * c % p for x in s1] + + +def _pgcd(a, b, p): + while b: + a, b = b, _pdivmod(a, b, p)[1] + c = pow(a[-1], -1, p) + return [x * c % p for x in a] + + +def _plcm(a, b, p): + return _pdivmod(_pmul(a, b, p), _pgcd(a, b, p), p)[0] + + +def _line(vec, base, direction, p, npts, start=1): + """Per entry (numerator, denominator) of the restriction to the line base + t direction, t from `start`; None + where not found.""" + ts, vals = [], [] + t = start - 1 + while len(ts) < npts: + t += 1 + if t > 3 * npts: + return None + v = vec([(b + t * d) % p for b, d in zip(base, direction)], p) + if v is not None: + ts.append(t) + vals.append(v) + out = [] + for e in range(len(vals[0])): + got = ratrec1(ts, [int(v[e]) for v in vals], p) + if got is None: + return None + out.append(got) + return out + + +def _common_denominator(fracs, p): + """The least common multiple of the denominators of the (numerator, denominator) pairs.""" + L = [1] + for _, d in fracs: + L = _plcm(L, d, p) + return L + + +def _degrees(fracs, p): + """Degrees of the polynomials C_e over the line with e -> C_e / C_last of the entries, the common + denominator cleared.""" + L = _common_denominator(fracs, p) + out = [] + for n, d in fracs: + q = _pdivmod(L, d, p)[0] + out.append(len(_pmul(n, q, p)) - 1 if n else -1) + return out + + +def _box(nv, total, per): + """Exponent vectors with total degree at most `total` and degree at most per[v] in variable v.""" + out = [] + + def rec(v, left, cur): + if v == nv: + out.append(tuple(cur)) + return + for e in range(min(left, per[v]) + 1): + cur.append(e) + rec(v + 1, left - e, cur) + cur.pop() + rec(0, total, []) + out.sort(key=lambda m: (sum(m), m)) + return out + + +def _vander(pts, mons, p): + nv = len(mons[0]) if mons else 0 + X = np.array(pts, dtype=np.int64) + top = [max(m[v] for m in mons) for v in range(nv)] + pw = [[np.ones(len(pts), dtype=np.int64)] for _ in range(nv)] + for v in range(nv): + for _ in range(top[v]): + pw[v].append(pw[v][-1] * X[:, v] % p) + M = np.ones((len(pts), len(mons)), dtype=np.int64) + for j, m in enumerate(mons): + for v, e in enumerate(m): + if e: + M[:, j] = M[:, j] * pw[v][e] % p + return M + + +def _ratrec(rows, primes): + """Per column the rational number with these residues modulo the primes (one row each), by the Chinese remainder + theorem and rational reconstruction with numerator and denominator below the square root of half the product; + None where one has none.""" + M = math.prod(primes) + lift = [(M // q) * pow(M // q, -1, q) for q in primes] + bound = math.isqrt(M // 2) + out = [] + for col in zip(*rows): + a = sum(v * w for v, w in zip(col, lift)) % M + r0, r1, s0, s1 = M, a, 0, 1 + while r1 > bound: + qq = r0 // r1 + r0, r1 = r1, r0 - qq * r1 + s0, s1 = s1, s0 - qq * s1 + if s1 == 0 or abs(s1) > bound or math.gcd(r1, abs(s1)) != 1: + return None + out.append(Fraction(r1, s1)) + return out + + +def _primes(): + """The primes of the interpolation of coefficients: the engine primes, then lower ones up to 32.""" + head = all_primes() + return head + [q for q in prime_run(32) if q not in head] + + +class _StoppedError(Exception): + """The search reached the cap on the entries of the matrices reduced.""" + + +class Coefficients: + """The coefficients of a projection as rational functions of the parameters, N_e / D with one denominator, + interpolated modulo several primes and rebuilt over Q; candidates only.""" + + def __init__(self, proj, nparams, rng, stop): + self.proj, self.n, self.rng, self.stop = proj, nparams, rng, stop + self.why = None + + def _vec(self, order): + """The kernel vector on the monomials in `order` (the normalizing one last) at a parameter point.""" + mons = [self.proj.mons[j] for j in order] + + def f(theta, p): + if work.ticks() > self.stop: + raise _StoppedError + v = self.proj.vector(theta, p, mons) + return None if v is None else v[:-1] + + return f + + def run(self): + try: + return self._run() + except _StoppedError: + self.why = "the end of the search" + return None + + def _run(self): + primes = _primes() + p = primes[0] + T = len(self.proj.mons) + rng = self.rng + # the degrees on a random line, the coefficients cleared of their common denominator, choose the normalizing + # coefficient of least degree + base = [rng.randrange(1, p) for _ in range(self.n)] + direc = [rng.randrange(1, p) for _ in range(self.n)] + order0 = list(range(T)) + npts = 24 + while True: + fr = _line(self._vec(order0), base, direc, p, npts) + if fr is not None and all(len(n) + len(d) + 2 <= npts - 4 for n, d in fr): + break + npts *= 2 + if npts > 400: + self.why = "degrees above 200 on a line" + return None + degs = _degrees(fr + [([1], [1])], p) + star = min(range(T), key=lambda j: (degs[j], -sum(self.proj.mons[j]), j)) + order = [j for j in range(T) if j != star] + [star] + vec = self._vec(order) + fr = _line(vec, base, direc, p, npts) + if fr is None: + self.why = "the line of the normalized coefficients" + return None + # the common denominator D: the least common multiple of the denominators on the line, and per parameter on + # lines parallel to the axes + dden = len(_common_denominator(fr, p)) - 1 + dnum = [len(nn) - 1 + dden - (len(d) - 1) if nn else -1 for nn, d in fr] + per_den, per_num, pure = [], [[] for _ in fr], True + for v in range(self.n): + e = [0] * self.n + e[v] = 1 + b = [rng.randrange(1, p) for _ in range(self.n)] + fv = _line(vec, b, e, p, npts) + if fv is None: + self.why = "a line parallel to an axis" + return None + L = _common_denominator(fv, p) + dv = len(L) - 1 + per_den.append(dv) + pure = pure and not any(L[:-1]) + for k, (nn, d) in enumerate(fv): + per_num[k].append(len(nn) - 1 + dv - (len(d) - 1) if nn else -1) + Dco = {} + if pure and sum(per_den) == dden: + # a power of t on every axis: D is a monomial + boxD = [tuple(per_den)] + for q in primes: + Dco[q] = np.array([1], dtype=np.int64) + again = None + else: + # a random combination of the entries has the common denominator as denominator + r = [rng.randrange(1, 1 << 20) for _ in fr] + + def comb(theta, q, vec=vec, r=r): + v = vec(theta, q) + return None if v is None else np.array([sum(int(a) * b for a, b in zip(v, r)) % q], dtype=np.int64) + + boxD = _box(self.n, dden, per_den) + if len(boxD) > _UNKNOWNS // 4: + self.why = f"{len(boxD)} unknowns of the denominator" + return None + beta = [rng.randrange(1, 1 << 20) for _ in range(self.n)] + width = max(dnum) + dden + 6 + again = (comb, beta, width) + for q in primes[:2]: + got = self._denominator(comb, beta, width, boxD, q) + if got is None: + self.why = self.why or "the denominator" + return None + Dco[q] = got + # the numerators over the denominator: in one box at once where it is small, else sparse per entry + boxes = [_box(self.n, max(dnum[k], 0), [max(x, 0) for x in per_num[k]]) for k in range(len(fr))] + allm = sorted(set().union(*[set(b) for b in boxes]), key=lambda m: (sum(m), m)) + + def numerators(q): + if len(allm) <= _DENSE: + arr = self._numerators(vec, Dco[q], boxD, allm, len(fr), q) + return None if arr is None else [dict(zip(allm, row)) for row in arr] + return self._sparse(vec, Dco[q], boxD, boxes, q) + + num = {} + for q in primes[:2]: + num[q] = numerators(q) + if num[q] is None: + self.why = self.why or "the numerators" + return None + used = primes[:2] + prev = None + while True: + # rational reconstruction of every coefficient from the primes used, the same without the last prime + dco = self._lift({q: Dco[q] for q in used}, used) + nco = self._lift_dicts([num[q] for q in used], used) + if dco is not None and nco is not None and (dco, nco) == prev: + break + prev = None if dco is None or nco is None else (dco, nco) + if len(used) == len(primes) or work.ticks() > self.stop: + self.why = "the rational reconstruction of the coefficients" + return None + q = primes[len(used)] + if q not in Dco: + Dco[q] = self._denominator(*again, boxD, q) + if Dco[q] is None: + return None + num[q] = numerators(q) + if num[q] is None: + return None + used = used + [q] + self.order = order + self.boxD = boxD + self.den = {m: c for m, c in zip(boxD, dco) if c} + self.nums = [{m: c for m, c in d.items() if c} for d in nco] + return True + + @staticmethod + def _lift(by, used): + """The rationals with the residues `by[q]` modulo the primes `used`, as _ratrec().""" + return _ratrec([[int(x) for x in by[q]] for q in used], used) + + @staticmethod + def _lift_dicts(per_prime, used): + """Per entry the coefficients over Q from their residues per prime, None where the supports differ or a + coefficient has no bounded rational.""" + out = [] + for k in range(len(per_prime[0])): + keys = sorted(per_prime[0][k]) + if any(sorted(d[k]) != keys for d in per_prime[1:]): + return None + if not keys: + out.append({}) + continue + got = _ratrec([[int(d[k][m]) for m in keys] for d in per_prime], used) + if got is None: + return None + out.append(dict(zip(keys, got))) + return out + + def _sparse(self, vec, dco, boxD, boxes, q): + """Per entry {monomial: coefficient modulo q} of the numerators by Ben-Or and Tiwari: values at the points + c_v b_v^j, b_v the first primes and c a random shift, one point for all entries.""" + bases = sieve(self.n) + width = len(boxes) + cap_len = 2 * TERMS + 2 + for _ in range(3): + c = [self.rng.randrange(1, q) for _ in range(self.n)] + cur, seqs, have, target, failed = list(c), [[] for _ in range(width)], 0, 16, False + while not failed: + while have < target: + v = vec(cur, q) + Dv = sum(int(a) * math.prod(pow(x, e, q) for x, e in zip(cur, m)) for m, a in zip(boxD, dco)) % q + if v is None or not Dv: + failed = True + break + for k in range(width): + seqs[k].append(int(v[k]) * Dv % q) + cur = [x * b % q for x, b in zip(cur, bases)] + have += 1 + if failed: + break + if all(2 * int(_core.sym_b_morder(sq, q)) < have for sq in seqs): + break + if have >= cap_len: + self.why = f"numerators with more than {TERMS} terms" + return None + target = min(2 * have, cap_len) + if failed: + continue + out = [] + for k in range(width): + cand = np.array(boxes[k], dtype=np.int64).reshape(-1, self.n) + res = _core.sym_mono_residues(cand, bases, q) + r = _core.sym_sparse_poly(seqs[k], cand, res, q) + if r.get("status") != "ok": + self.why = f"the sparse numerator of an entry ({r.get('status')})" + return None + exps = np.asarray(r["exps"], dtype=np.int64).reshape(-1, self.n) + row = {} + for m, a in zip(exps, np.atleast_1d(r["coeffs"])): + m = tuple(int(x) for x in m) + shift = math.prod(pow(x, e, q) for x, e in zip(c, m)) % q + row[m] = int(a) * pow(shift, -1, q) % q + out.append(row) + return out + self.why = "no points for the sparse numerators" + return None + + def _samples(self, vec, q, m): + """m random parameter points modulo q where `vec` has a value, and the values; (None, None) after many + misses.""" + pts, vals = [], [] + tries = 0 + while len(pts) < m: + tries += 1 + if tries > 3 * m + 20: + return None, None + x = [self.rng.randrange(1, q) for _ in range(self.n)] + v = vec(x, q) + if v is not None: + pts.append(x) + vals.append(v) + return pts, np.array(vals, dtype=np.int64) + + def _denominator(self, comb, beta, width, boxD, q): + """The coefficients of D on boxD modulo q with D(beta) = 1: on the line beta + t (theta - beta) the common + denominator is L(t) / L(0), L the denominator of a random combination of the entries there.""" + pts, vals = [], [] + tries = 0 + while len(pts) < len(boxD) + 8: + tries += 1 + if tries > 3 * len(boxD) + 30: + return None + x = [self.rng.randrange(1, q) for _ in range(self.n)] + g = [(a - b) % q for a, b in zip(x, beta)] + fr = _line(comb, [b % q for b in beta], g, q, width, start=0) + if fr is None: + continue + _, L = fr[0] + if not L[0]: + continue + pts.append(x) + vals.append(sum(L) % q * pow(L[0], -1, q) % q) + A = np.hstack([_vander(pts, boxD, q), (-np.array(vals, dtype=np.int64)[:, None]) % q]) + work.tick(A.shape) + ker = _core.io_kernel(A, q, _threads()) + 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 + + 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.""" + U = len(allm) + pts, vals = self._samples(vec, q, U + 8) + if pts is None: + return None + Dv = (_vander(pts, boxD, q) * dco[None, :] % q).sum(axis=1) % q + rhs = vals * Dv[:, None] % q + V = _vander(pts, allm, q) + A = np.hstack([V, (-rhs) % q]) + work.tick(A.shape) + ker = _core.io_kernel(A, q, _threads()) + piv = ker["pivots"] + if piv[:U] != list(range(U)): + self.why = "the numerators are not determined by their box" + return None + # the vector with 1 on the column of a numerator holds the coefficients of that numerator in the first U entries + basis = np.asarray(ker["basis"], dtype=np.int64) + free = ker["free"] + out = np.zeros((width, U), dtype=np.int64) + for k in range(width): + j = free.index(U + k) if U + k in free else None + if j is None: + return None + out[k] = basis[j][:U] % q + return out + + 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)) + + D = poly(self.den) + out = [None] * len(self.order) + for k, j in enumerate(self.order[:-1]): + out[j] = spy.cancel(poly(self.nums[k]) / D) + out[self.order[-1]] = spy.Integer(1) + return out + + +def profiles(rel, unknown, p, rng, limit=6): + """Parametric profiles: per observable the number h_r of derivatives in a transcendence basis of the + derivatives of all of them over the states `unknown`, by the rank of their Jacobian at a random point modulo p; + greedy in rounds and depth first, from each observable.""" + ny = len(rel.y) + J = jets_of(rel) + gens = [J.X[j] for j in unknown] + pt = [rng.randrange(1, p) for _ in rel.names] + memo = {} + + def row(r, k): + if (r, k) not in memo: + if k and len(J.observable(r, k - 1)[k - 1].numer) > _JET: + memo[(r, k)] = None + else: + got = _gradients(J, [J.observable(r, k)[k]], gens, pt, p) + memo[(r, k)] = None if got is None else got[0] + return memo[(r, k)] + + out = [] + orders = [list(range(s, ny)) + list(range(s)) for s in range(ny)] + for strategy in ("rounds", "depth"): + for perm in orders: + h, rows, rk = [0] * ny, [], 0 + active = list(perm) + while active: + for r in list(active): + if r not in active: + continue + while True: + if h[r] > len(gens): + active.remove(r) + break + nxt = row(r, h[r]) + cand = rows + [nxt] + if nxt is not None and _rank(cand, p) > rk: + rows, rk = cand, rk + 1 + h[r] += 1 + if strategy == "rounds": + break + else: + active.remove(r) + break + if h not in out: + out.append(h) + if len(out) >= limit: + return out + return out + + +def _rank(rows, p): + """The rank of the rows modulo p.""" + A = np.array(rows, dtype=np.int64) + work.tick(A.shape) + ker = _core.io_kernel(A.T.copy(), p, 1) + return A.shape[0] - len(ker["free"]) + + +def _dot(a, b, p): + """sum_i a_i b_i modulo p for int64 arrays of residues below 2^31, without overflow.""" + lo, hi = a & 0xFFFF, a >> 16 + return (int(np.dot(lo, b) % p) + (int(np.dot(hi, b) % p) << 16)) % p + + +class _Series: + """Polynomials in the states with numeric coefficients, their Taylor coefficients along a trajectory computed + order by order from those of the states, each monomial from one of lower degree.""" + + def __init__(self, polys, vars_, vals, p, K): + self.p, self.K = p, K + self.vars = vars_ + zero = (0,) * len(vars_) + self.mons, self.at = [zero], {zero: 0} + self.polys = [] + for P in polys: + terms = {} + for m, c in P.terms(): + key = tuple(m[g] for g in vars_) + v = int(c.numerator) % p * pow(int(c.denominator), -1, p) % p + for g, e in enumerate(m): + if e and g not in vars_: + v = v * pow(vals[g], e, p) % p + terms[key] = (terms.get(key, 0) + v) % p + self._add(key) + self.polys.append([(self.at[m], c) for m, c in terms.items() if c]) + self.ser = np.zeros((len(self.mons), K + 1), dtype=np.int64) + self.ser[0, 0] = 1 + + 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:] + self._add(lower) + self.at[m] = len(self.mons) + self.mons.append(m) + + def order(self, X, k): + """The coefficients of order k of the monomials, X[v] the series of variable v known up to order 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) + + def value(self, i, k): + return sum(c * int(self.ser[j, k]) for j, c in self.polys[i]) % self.p + + +def trajectory(rel, values, p, K): + """Taylor coefficients up to order K, modulo p, of the observables and of the known states along the trajectory of + the first condition with the coordinates at `values` ({symbol: residue}); None at a pole.""" + J = jets_of(rel) + seg = rel.part["segs"][0] + names = rel.names + vals = [0] * len(names) + for s, v in values.items(): + if str(s) in names: + vals[names.index(str(s))] = v % p + kept = [j for j in range(rel.ns) if J.X[j] is not None] + gidx = {j: names.index(str(rel.X[j])) for j in kept} + vars_ = [gidx[j] for j in kept] + known = set(rel.known) + kser = _known_series(rel, values, p, K) + if kser is None: + return None + X = np.zeros((len(kept), K + 1), dtype=np.int64) + sub = {s: spy.Integer(int(v)) for s, v in values.items()} + for a, j in enumerate(kept): + if j in known: + X[a] = kser[j] + continue + x0 = seg["x0"][j][0] + num, den = (int(t) for t in _fraction(x0, sub)) + if den % p == 0: + return None + X[a, 0] = num % p * pow(den % p, -1, p) % p + unknown = [a for a, j in enumerate(kept) if j not in known] + Q = J.Q if J.Q is not None else J.R.one + S = _Series([J.Fh[kept[a]] for a in unknown] + [Q], vars_, vals, p, K) + q0 = None + dser = {a: [] for a in unknown} + qs = [] + for k in range(K): + S.order(X, k) + qs.append(S.value(len(unknown), k)) + if q0 is None: + q0 = qs[0] + if not q0: + return None + iq = pow(q0, -1, p) + for n, a in enumerate(unknown): + # x' Q = F: the coefficient k of x' from those below + rest = sum(qs[i] * dser[a][k - i] for i in range(1, k + 1)) % p + d = (S.value(n, k) - rest) * iq % p + dser[a].append(d) + X[a, k + 1] = d * pow(k + 1, -1, p) % p + S.order(X, K) + obs = [] + for r in range(len(rel.y)): + M, E = J._parts(rel.y[r]) + T = _Series([M, E if E is not None else J.R.one], vars_, vals, p, K) + for k in range(K + 1): + T.order(X, k) + m_ = [T.value(0, k) for k in range(K + 1)] + e_ = [T.value(1, k) for k in range(K + 1)] + if not e_[0]: + return None + ie = pow(e_[0], -1, p) + y = [] + for k in range(K + 1): + y.append((m_[k] - sum(e_[i] * y[k - i] for i in range(1, k + 1))) * ie % p) + obs.append(y) + states = {j: X[a] for a, j in enumerate(kept)} + return obs, states + + +class _Terms: + """A polynomial of the series as {exponents: Fraction}, read as terms.""" + + def __init__(self, d): + self.d = d + + def terms(self): + return list(self.d.items()) + + +def _integrate(polys, vars_, vals, starts, p, K): + """Taylor coefficients up to order K of the states with x_i' D_i = N_i, polys = [N_1, ..., D_1, ...]; None at + a pole.""" + n = len(starts) + S = _Series(polys, vars_, vals, p, K) + X = np.zeros((n, K + 1), dtype=np.int64) + X[:, 0] = starts + dser = [[] for _ in range(n)] + dens = [[] for _ in range(n)] + for k in range(K): + S.order(X, k) + for i in range(n): + dens[i].append(S.value(n + i, k)) + if not dens[i][0]: + return None + rest = sum(dens[i][l] * dser[i][k - l] for l in range(1, k + 1)) % p + d = (S.value(i, k) - rest) * pow(dens[i][0], -1, p) % p + dser[i].append(d) + X[i, k + 1] = d * pow(k + 1, -1, p) % p + return X + + +def _known_series(rel, values, p, K): + """{state: Taylor coefficients up to order K modulo p} of the states with a known series.""" + part, seg = rel.part, rel.part["segs"][0] + known = sorted(part["known"]) + if not known: + return {} + ns = len(part["st"]) + params = [str(x) for x in rel.series.params] + byname = {str(s): v for s, v in values.items()} + vals = [0] * ns + [byname.get(x, 0) % p for x in params] + starts = [] + for i in known: + c = Fraction(str(seg["x0"][i][0])) + starts.append(c.numerator % p * pow(c.denominator, -1, p) % p) + polys = [_Terms(seg["F"][i][0]) for i in known] + [_Terms(seg["F"][i][1]) for i in known] + X = _integrate(polys, known, vals, starts, p, K) + return None if X is None else {i: X[a] for a, i in enumerate(known)} + + +def _fraction(expr, sub): + """(numerator, denominator) of `expr` with the substitution `sub`, as sympy integers.""" + v = spy.sympify(expr).xreplace(sub) + n, d = spy.fraction(spy.together(v)) + return spy.Integer(n), spy.Integer(d) + + +def taylor_rows(rel, ms, values, p, K): + """The first K Taylor coefficients, along the trajectory of the first condition with the coordinates at + `values`, of the derivatives y_r^(j), j <= ms[r], and of the input states read; None at a pole.""" + m = max(ms) + got = trajectory(rel, values, p, m + K) + if got is None: + return None + obs, states = got + rows = [] + for r, mr in enumerate(ms): + for j in range(mr + 1): + c = obs[r] + rows.append([c[k + j] * (math.factorial(k + j) // math.factorial(k)) % p for k in range(K)]) + for i in rel.inputs(m): + rows.append([int(v) for v in states[i][:K]]) + return np.array(rows, dtype=np.int64) + + +def series_rank(rel, proj, mons, syms, rng, p): + """The rank of the Taylor coefficients of the monomials along the trajectory of the first condition at a random + point modulo p.""" + S = taylor_rows(rel, proj.ms, {s: rng.randrange(1, p) for s in syms}, p, len(mons) + 6) + if S is None or S.shape[0] != proj.nb: + return None + ser = _core.io_series_monomials(S, np.array(mons, dtype=np.int32), p, _threads()) + work.tick(ser.shape) + ker = _core.io_kernel(np.ascontiguousarray(ser.T), p, _threads()) + return len(mons) - len(ker["free"]) + + +def combine(J, coeffs, quos): + """(numerator, exponents T): sum_j coeffs_j quos_j over the common denominator prod_k F_k^T_k, each term times + the powers of the factors it lacks; without gcds.""" + T = {} + for q in quos: + for k, x in q.exps: + T[k] = max(T.get(k, 0), x) + pw = {} + total = J.R.zero + for c, q in zip(coeffs, quos): + if not c: + continue + term = c * q.numer + have = dict(q.exps) + for k, x in T.items(): + e = x - have.get(k, 0) + if e: + if (k, e) not in pw: + pw[(k, e)] = J.fac[k] ** e + term = term * pw[(k, e)] + total = total + term + return total, T + + +def products(J, base, mons): + """The monomials of the base functions as Quo.""" + pw = {} + out = [] + for m in mons: + num, ex = J.R.one, {} + for v, e in enumerate(m): + if not e: + continue + if (v, e) not in pw: + pw[(v, e)] = base[v].numer ** e + num = num * pw[(v, e)] + for k, x in base[v].exps: + ex[k] = ex.get(k, 0) + x * e + out.append(Quo(num, sorted(ex.items()))) + return out + + +def identity(rel, proj, coef, params_pos): + """Whether sum_j a_j m_j(base) is zero, the coefficients a_j = N_j / D and the base functions N_v / prod_k F_k^e_vk: + the polynomial sum_j N_j prod_v N_v^m_jv prod_k F_k^(T_k - t_jk) in the ring of the states and coordinates, t_jk + the exponent of F_k in the denominator of monomial j and T_k the largest; without gcds.""" + J = jets_of(rel) + R = J.R + ng = R.ngens + mons = proj.mons + + def ring_poly(co): + out = R.zero + for m, c in co.items(): + e = [0] * ng + for k, x in zip(params_pos, m): + e[k] = x + out = out + R({tuple(e): R.domain.convert(c.numerator) / R.domain.convert(c.denominator)}) + return out + + coeffs = [None] * len(mons) + for k, j in enumerate(coef.order[:-1]): + coeffs[j] = ring_poly(coef.nums[k]) + coeffs[coef.order[-1]] = ring_poly(coef.den) + return combine(J, coeffs, products(J, proj.base.funcs, mons))[0] == 0 + + +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(): + t = c.numerator % p * pow(c.denominator, -1, p) + for x, e in zip(theta, m): + if e: + t = t * pow(int(x), e, p) % p + s += t + return s % p + + D = ev(coef.den) + if not D: + return None + iD = pow(D, -1, p) + out = [0] * len(coef.order) + for k, j in enumerate(coef.order[:-1]): + out[j] = ev(coef.nums[k]) * iD % p + out[coef.order[-1]] = 1 + return out diff --git a/src/symident/detection/monodromy.py b/src/symident/detection/monodromy.py new file mode 100644 index 0000000..9b1a4d8 --- /dev/null +++ b/src/symident/detection/monodromy.py @@ -0,0 +1,780 @@ +"""Points of the fiber by numerical monodromy, certified by the Krawczyk operator: proposals of discrete maps. + +The fiber of the output coefficients is overdetermined. A square subsystem of coefficients with independent +gradients is solved by parameter homotopies around random loops in the space of the values, starting from the +known point; the points that also keep the other coefficients are proposed as points of the fiber. Each is then +enclosed in a box with a unique zero of the square subsystem (docs/method/global.rst, "Monodromy and certified points"). +The numbers only propose: a map read from the points counts once it is proven exactly.""" + +import itertools +from fractions import Fraction + +import numpy as np +import sympy as spy + +from .. import session +from ..gfp import PRIMES +from . import work + +# step bounds of the tracker, in the homotopy parameter +_H_MAX, _H_MIN = 0.05, 1e-9 +# a tracked point past this modulus has left for infinity +_FAR = 1e8 +# relative tolerance of a point of the fiber on the coefficients outside the square subsystem +_TOL = 1e-7 +# the most points of the square subsystem modulo a prime that monodromy is run on +_SQUARE = 200 + + +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): + self.v, self.d = v, d + + def _of(self, x): + if isinstance(x, _Batch): + return x + return _Batch(np.full(self.v.shape, complex(float(x)) if isinstance(x, Fraction) else complex(x))) + + def __add__(self, x): + x = self._of(x) + d = self.d if x.d is None else x.d if self.d is None else self.d + x.d + return _Batch(self.v + x.v, d) + + __radd__ = __add__ + + def __neg__(self): + return _Batch(-self.v, None if self.d is None else -self.d) + + def __sub__(self, x): + return self + (-self._of(x)) + + def __rsub__(self, x): + return self._of(x) - self + + def __mul__(self, x): + if not isinstance(x, _Batch): + c = complex(float(x)) if isinstance(x, Fraction) else complex(x) + return _Batch(self.v * c, None if self.d is None else self.d * c) + if self.d is None: + d = None if x.d is None else x.d * self.v[:, None] + elif x.d is None: + d = self.d * x.v[:, None] + else: + d = self.d * x.v[:, None] + x.d * self.v[:, None] + return _Batch(self.v * x.v, d) + + __rmul__ = __mul__ + + def __truediv__(self, x): + x = self._of(x) + if np.any(x.v == 0): + raise ZeroDivisionError("division by zero at a point of the batch") + q = self.v / x.v + if x.d is None: + return _Batch(q, None if self.d is None else self.d / x.v[:, None]) + d = -x.d * q[:, None] if self.d is None else self.d - x.d * q[:, None] + return _Batch(q, d / x.v[:, None]) + + def __rtruediv__(self, x): + return self._of(x) / self + + def __pow__(self, e): + if e == 0: + return self._of(1) + 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 + + +def _flat(ys, orders, gap, free): + """The coefficients of the observables as one list, coefficient k of observable j up to orders[j], each with + the coefficients in eps up to `gap`; the rows of copies with a free start are left out.""" + out, index = [], [] + for j, y in enumerate(ys): + 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]): + out.append(c) + index.append((j, k, m)) + return out, index + + +def coefficients(series, X, orders, gap=0, jac=True): + """(values (P, M), Jacobian (P, M, n) or None, index) of the output coefficients at the rows of X (P, n), + complex; None where a point of the batch meets a pole.""" + X = np.atleast_2d(np.asarray(X, dtype=complex)) + P, n = X.shape + eye = np.eye(n, dtype=complex) + cv = [_Batch(X[:, i].copy(), np.repeat(eye[i][None, :], P, axis=0) if jac else None) for i in range(n)] + one, zero = _Batch(np.ones(P, dtype=complex)), _Batch(np.zeros(P, dtype=complex)) + try: + ys = series._outputs(cv, max(orders), gap, one, zero) + except (ZeroDivisionError, FloatingPointError, OverflowError): + return None + if ys is None: + return None + rows, index = _flat(ys, orders, gap, series.free_rows) + 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) + return vals, J, index + + +class _System: + """The fiber at a base point: the square subsystem `rows` of the coefficients, solved for given values, and all + coefficients up to `orders`, which a point of the fiber keeps.""" + + def __init__(self, series, orders, rows, base, gap=0): + self.series, self.orders, self.gap = series, list(orders), gap + self.n = len(series.cs) + self.base = np.asarray([complex(float(Fraction(str(base[s])))) for s in series.cs]) + sub = [0] * len(orders) + for j, k in rows: + sub[j] = max(sub[j], k) + self.sub_orders = sub + got = coefficients(series, self.base, sub, 0, jac=False) + if got is None: + raise ZeroDivisionError("the base point is a pole") + _, _, index = got + pos = {(j, k): i for i, (j, k, m) in enumerate(index) if m == 0} + self.rows = [pos[r] for r in rows] + self.target = got[0][0, self.rows] + full = coefficients(series, self.base, self.orders, gap, jac=False) + if full is None: + raise ZeroDivisionError("the base point is a pole") + self.full = full[0][0] + + def square(self, X): + """(values, Jacobian) of the square subsystem at the rows of X; None at a pole.""" + got = coefficients(self.series, X, self.sub_orders, 0) + if got is None: + return None + v, J, _ = got + return v[:, self.rows], J[:, self.rows, :] + + def residual(self, X): + """The largest relative deviation of the coefficients up to `orders` at the rows of X from those at the + base point, inf at a pole.""" + got = coefficients(self.series, X, self.orders, self.gap, jac=False) + if got is None: + return np.full(len(np.atleast_2d(X)), np.inf) + dev = np.abs(got[0] - self.full[None, :]) / (1 + np.abs(self.full[None, :])) + return dev.max(axis=1) + + +def _solve(J, r): + """The solutions of the batch of linear systems J x = r, a row of NaN where one is singular.""" + try: + return np.linalg.solve(J, r[..., None])[..., 0] + except np.linalg.LinAlgError: + out = np.full(r.shape, np.nan, dtype=complex) + for i in range(len(r)): + try: + out[i] = np.linalg.solve(J[i], r[i]) + except np.linalg.LinAlgError: + pass + return out + + +def _eval_safe(F, X): + """F at the rows of X, row by row where the batch meets a pole: (values, Jacobian, ok).""" + got = F(X) + if got is not None: + return got[0], got[1], np.ones(len(X), dtype=bool) + n = X.shape[1] + v = np.full((len(X), n), np.nan, dtype=complex) + 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]) + if g is not None: + v[i], J[i], ok[i] = g[0][0], g[1][0], True + return v, J, ok + + +def track(F, X0, wa, wb, meter=None, weight=1): + """The end points at w = wb of the paths of F(x) = w from the points X0 at w = wa along the segment, by an + Euler predictor and a Newton corrector with step control; a row of NaN where a path fails or stops at the cap + of `meter`, which counts `weight` units per step of all paths at once.""" + meter = meter or work.unlimited() + X = np.array(X0, dtype=complex) + P = len(X) + t = np.zeros(P) + h = np.full(P, _H_MAX / 2) + live = np.ones(P, dtype=bool) + dw = wb - wa + while True: + act = np.where(live & (t < 1))[0] + if not len(act) or meter.spend(weight): + break + x = X[act] + hh = np.minimum(h[act], 1 - t[act]) + _, J, ok = _eval_safe(F, x) + dx = _solve(np.where(ok[:, None, None], J, np.eye(J.shape[1])), np.repeat(dw[None, :], len(act), axis=0)) + xp = x + hh[:, None] * dx + tp = t[act] + hh + w = wa[None, :] + tp[:, None] * dw[None, :] + good = ok & np.all(np.isfinite(xp), axis=1) + first = None + for _ in range(3): + v, J, okc = _eval_safe(F, xp) + step = _solve(np.where(okc[:, None, None], J, np.eye(J.shape[1])), np.where(okc[:, None], v - w, 0)) + good &= okc & np.all(np.isfinite(step), axis=1) + sn = np.where(good, np.linalg.norm(np.where(np.isfinite(step), step, 0), axis=1), np.inf) + if first is None: + first = sn + xp = np.where(good[:, None], xp - step, xp) + scale = 1 + np.linalg.norm(np.where(np.isfinite(xp), xp, 0), axis=1) + conv = good & (sn <= 1e-9 * scale) & (first <= 0.05 * scale) + far = np.linalg.norm(np.where(np.isfinite(xp), xp, _FAR * 10), axis=1) > _FAR + X[act[conv]] = xp[conv] + t[act[conv]] = tp[conv] + h[act[conv]] = np.minimum(h[act[conv]] * 1.6, _H_MAX) + h[act[~conv]] /= 2 + dead = (h[act] < _H_MIN) | (conv & far) + live[act[dead]] = False + X[~live | (t < 1)] = np.nan + return X + + +def _newton(F, X, w, steps=6): + """Newton steps on F(x) = w from the rows of X, a row of NaN where a step fails.""" + for _ in range(steps): + v, J, ok = _eval_safe(F, X) + step = _solve(np.where(ok[:, None, None], J, np.eye(J.shape[1])), np.where(ok[:, None], v - w, 0)) + X = np.where((ok & np.all(np.isfinite(step), axis=1))[:, None], X - step, np.nan) + return X + + +def _new(points, x, tol=1e-6): + """Whether x differs from every one of `points` relative to tol.""" + s = 1 + np.linalg.norm(x) + return all(np.linalg.norm(p - x) > tol * s for p in points) + + +def monodromy(system, rng, meter, target=None, stall=5, cap=400): + """(fiber, square): the points of the square subsystem of `system` found by loops w0 -> w1 -> w2 -> w0 in the + space of the values from the base point, and those among them that keep every coefficient up to the orders of + the system. Stops after `stall` loops without a new point, at `cap` points, at `target` points of the fiber + or at the cap of `meter` on the work of the steps of the paths (_step_work()).""" + n = system.n + F = system.square + w0 = system.target + sols = [system.base.copy()] + quiet = 0 + while quiet < stall and len(sols) < cap and not meter.over: + scale = 1 + np.abs(w0) + # nodes away from w0: a triangle through them winds around the branch locus more often + w1 = scale * (rng.standard_normal(n) + 1j * rng.standard_normal(n)) + w2 = scale * (rng.standard_normal(n) + 1j * rng.standard_normal(n)) + X = np.array(sols) + for a, b in ((w0, w1), (w1, w2), (w2, w0)): + X = track(F, X, a, b, meter, _step_work(system)) + X = X[np.all(np.isfinite(X), axis=1)] + if not len(X): + break + X = _newton(F, X, w0[None, :]) if len(X) else X + added = 0 + for x in X: + if np.all(np.isfinite(x)) and _new(sols, x): + sols.append(x) + added += 1 + quiet = 0 if added else quiet + 1 + if target is not None: + res = system.residual(np.array(sols)) + if int(np.sum(res < _TOL)) >= target: + break + S = np.array(sols) + res = system.residual(S) + return S[res < _TOL], S + + +def _step_work(system): + """The work of one step of the paths: four evaluations of the square subsystem with the Jacobian, each the + Taylor series of the model up to the orders of the subsystem, (k + 1)^2 products per term at order k.""" + size = sum(len(N) + len(D) for part in system.series.parts for seg in part["segs"] for N, D in seg["F"]) + top = max(system.sub_orders) + 1 + return 4 * size * (system.n + 1) * sum((k + 1) ** 2 for k in range(top)) + + +def rur_points(fib, point, digits=40): + """The complex points of the fiber at the rational `point`, coordinates in the order of the series, from the + rational parametrization of msolve over Q per block, the roots taken numerically; None on failure.""" + import mpmath + + from .discrete import FiberTooLargeError + from .discrete import _solve as solve_block + try: + sysd = fib.system(point) + except (FiberTooLargeError, ZeroDivisionError): + return None + if sysd is None: + return None + per = [] + for block in sysd["blocks"]: + data = solve_block(fib, 0, block, ["-P", "1"]) + if data is None or data[0] != 0: + return None + _, _, deg, vn, lin, par = data[1] + if deg <= 0 or par[0] != 1: + 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 + + 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])] + sols = [] + last = len(vn) - 1 + for t in roots: + dv = ev(den, 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]) + sols.append({k: complex(v) for k, v in vals.items()}) + per.append(sols) + out = [] + for combo in itertools.product(*per): + merged = {k: v for sol in combo for k, v in sol.items()} + merged.update({k: complex(float(v)) for k, v in sysd["fixed"].items()}) + if any(nm not in merged for nm in fib.names): + return None + out.append([merged[nm] for nm in fib.names]) + return np.array(out, dtype=complex).reshape(len(out), len(fib.names)) + + +# ---- the Krawczyk operator in interval arithmetic -------------------------------------------- + +def _dn(x): + return np.nextafter(x, -np.inf) + + +def _up(x): + return np.nextafter(x, np.inf) + + +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): + self.rl, self.rh, self.il, self.ih = rl, rh, il, ih + + @staticmethod + def point(z): + z = np.asarray(z, dtype=complex) + return _Rect(z.real.copy(), z.real.copy(), z.imag.copy(), z.imag.copy()) + + @staticmethod + def const(x, shape=()): + try: + f = float(x) if isinstance(x, (int, Fraction)) else None + except OverflowError: + return _Rect(np.full(shape, -np.inf), np.full(shape, np.inf), np.zeros(shape), np.zeros(shape)) + if f is not None and Fraction(f) == Fraction(x): + return _Rect(np.full(shape, f), np.full(shape, f), np.zeros(shape), np.zeros(shape)) + if f is not None: + return _Rect(np.full(shape, _dn(f)), np.full(shape, _up(f)), np.zeros(shape), np.zeros(shape)) + return _Rect.point(np.full(shape, complex(x))) + + def __add__(self, o): + return _Rect(_dn(self.rl + o.rl), _up(self.rh + o.rh), _dn(self.il + o.il), _up(self.ih + o.ih)) + + def __neg__(self): + return _Rect(-self.rh, -self.rl, -self.ih, -self.il) + + def __sub__(self, o): + return self + (-o) + + def __mul__(self, o): + def mul(a, b, c, d): + p = np.stack([a * c, a * d, b * c, b * d]) + bad = np.isnan(p).any(axis=0) + return np.where(bad, -np.inf, _dn(p.min(axis=0))), np.where(bad, np.inf, _up(p.max(axis=0))) + + acl, ach = mul(self.rl, self.rh, o.rl, o.rh) + bdl, bdh = mul(self.il, self.ih, o.il, o.ih) + adl, adh = mul(self.rl, self.rh, o.il, o.ih) + bcl, bch = mul(self.il, self.ih, o.rl, o.rh) + return _Rect(_dn(acl - bdh), _up(ach - bdl), _dn(adl + bcl), _up(adh + bch)) + + def scale(self, lo, hi): + """The product with the real interval [lo, hi].""" + return self * _Rect(lo, hi, np.zeros_like(lo), np.zeros_like(lo)) + + def has_zero(self): + return (self.rl <= 0) & (self.rh >= 0) & (self.il <= 0) & (self.ih >= 0) + + def inverse(self): + def sq(a, b): + lo = np.where((a <= 0) & (b >= 0), 0.0, _dn(np.minimum(a * a, b * b))) + return lo, _up(np.maximum(a * a, b * b)) + + cl, ch = sq(self.rl, self.rh) + dl, dh = sq(self.il, self.ih) + nl, nh = _dn(cl + dl), _up(ch + dh) + if np.any(~(nl > 0)): + raise ZeroDivisionError("an enclosure of a divisor holds zero") + conj = _Rect(self.rl, self.rh, -self.ih, -self.il) + return conj.scale(_dn(1 / nh), _up(1 / nl)) + + def mag(self): + """Upper bounds of the moduli, through |re| + |im|.""" + return _up(np.maximum(np.abs(self.rl), np.abs(self.rh)) + np.maximum(np.abs(self.il), np.abs(self.ih))) + + def __getitem__(self, i): + return _Rect(self.rl[i], self.rh[i], self.il[i], self.ih[i]) + + +def _sum(rects, shape): + out = _Rect.const(0, shape) + for r in rects: + out = out + r + return out + + +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 + + def __init__(self, v, d=None): + self.v, self.d = v, d + + def _of(self, x): + return x if isinstance(x, _IDual) else _IDual(_Rect.const(x)) + + def __add__(self, x): + x = self._of(x) + d = self.d if x.d is None else x.d if self.d is None else self.d + x.d + return _IDual(self.v + x.v, d) + + __radd__ = __add__ + + def __neg__(self): + return _IDual(-self.v, None if self.d is None else -self.d) + + def __sub__(self, x): + return self + (-self._of(x)) + + def __rsub__(self, x): + return self._of(x) - self + + def __mul__(self, x): + x = self._of(x) + if self.d is None: + d = None if x.d is None else x.d * _bcast(self.v) + elif x.d is None: + d = self.d * _bcast(x.v) + else: + d = self.d * _bcast(x.v) + x.d * _bcast(self.v) + return _IDual(self.v * x.v, d) + + __rmul__ = __mul__ + + def __truediv__(self, x): + x = self._of(x) + r = x.v.inverse() + q = self.v * r + if x.d is None: + return _IDual(q, None if self.d is None else self.d * _bcast(r)) + num = -(x.d * _bcast(q)) if self.d is None else self.d - x.d * _bcast(q) + return _IDual(q, num * _bcast(r)) + + def __rtruediv__(self, x): + return self._of(x) / self + + def __pow__(self, e): + out = self._of(1) + for _ in range(e): + out = out * self + return out + + 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 + + +def _bcast(r): + n = _IDual.n + return _Rect(np.full(n, r.rl), np.full(n, r.rh), np.full(n, r.il), np.full(n, r.ih)) + + +def _ivalues(series, cv, orders, gap, rows): + """The coefficients `rows` as _IDual at the enclosures `cv` of the coordinates; None at a pole.""" + one, zero = _IDual(_Rect.const(1)), _IDual(_Rect.const(0)) + try: + ys = series._outputs(cv, max(orders), gap, one, zero) + except ZeroDivisionError: + return None + if ys is None: + return None + flat, _ = _flat(ys, orders, gap, series.free_rows) + return [flat[r] if isinstance(flat[r], _IDual) else _IDual(_Rect.const(flat[r])) for r in rows] + + +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 + A = got[1][0] + nrm = np.linalg.norm(A, axis=1) + keep = np.where(nrm > 0)[0] + 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]]) + + +def krawczyk(series, orders, gap, rows, base, x, radius): + """The box around x (complex, one entry per coordinate) with the given radius per coordinate, as + [((re_lo, re_hi), (im_lo, im_hi))], if the Krawczyk operator proves a unique zero of the square subsystem + c_rows(x') = c_rows(base) in it, else None; `rows` index the coefficients up to `orders` as coefficients() + lists them, and `base` holds rationals.""" + n = len(series.cs) + _IDual.n = n + tb = _ivalues(series, [_IDual(_Rect.const(Fraction(str(base[s])))) for s in series.cs], orders, gap, rows) + xm = np.asarray(x, dtype=complex) + gm = _ivalues(series, [_IDual(_Rect.point(z)) for z in xm], orders, gap, rows) + if tb is None or gm is None: + return None + g = [a.v - b.v for a, b in zip(gm, tb)] + r = np.asarray(radius, dtype=float) + box = _Rect(_dn(xm.real - r), _up(xm.real + r), _dn(xm.imag - r), _up(xm.imag + r)) + eye = np.eye(n) + cv = [_IDual(box[i], _Rect(eye[i].copy(), eye[i].copy(), np.zeros(n), np.zeros(n))) for i in range(n)] + JX = _ivalues(series, cv, orders, gap, rows) + if JX is None or any(c.d is None for c in JX): + return None + # Y: a floating-point inverse of the Jacobian at the midpoint, with exact entries + Jm = np.array([(c.d.rl + c.d.rh) / 2 + 1j * (c.d.il + c.d.ih) / 2 for c in JX]) + try: + Y = np.linalg.inv(Jm) + except np.linalg.LinAlgError: + 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])) + 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,)) + # 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.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,)) + 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 + return [((float(box.rl[i]), float(box.rh[i])), (float(box.il[i]), float(box.ih[i]))) for i in range(n)] + + +def certify(series, orders, gap, base, x): + """The Krawczyk box of x on the square subsystem of square_rows(), trying radii from small to large; None if + none is proven.""" + with np.errstate(all="ignore"): + rows = square_rows(series, orders, gap, x) + if rows is None: + return None + for r in (1e-10, 1e-7): + box = krawczyk(series, orders, gap, rows, base, x, r * (1 + np.abs(x))) + if box is not None: + return box + return None + + +def disjoint(a, b): + """Whether two boxes of krawczyk() share no point: some coordinate has disjoint rectangles.""" + for (ra, ia), (rb, ib) in zip(a, b): + if ra[1] < rb[0] or rb[1] < ra[0] or ia[1] < ib[0] or ib[1] < ia[0]: + return True + return False + + +# ---- 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 = [] + for part in (z.real, z.imag): + f = Fraction(part).limit_denominator(den) + 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) + + +def _coordinate_forms(base, img, moved, syms): + """The images c*theta_j^e (e = 1, -1) and c*theta_j + d of the base point that reproduce the value of each + image coordinate, c and d Gaussian rationals; per coordinate a list of sympy expressions.""" + out = [] + for i, z in enumerate(img): + forms = [] + for j, s in enumerate(syms): + b = base[j] + for e in (1, -1): + c = _nice(z / b ** e) + if c is not None and c != 0: + forms.append(c * s ** e) + if j == i: + d = _nice(z - b) + if d is not None and d != 0: + forms.append(s + d) + if not moved[i] and not forms: + forms.append(syms[i]) + out.append(forms) + return out + + +def read_maps(system, points, rng, meter, cap=64): + """Maps sigma with sigma(base) at one of `points` whose image coordinates are c*theta_j^(+-1) or theta_i + d, + that keep the coefficients at two further random points within the tolerance; sympy dicts.""" + syms = list(system.series.cs) + base = system.base + maps = [] + for x in points: + moved = [abs(a - b) > 1e-9 * (1 + abs(b)) for a, b in zip(x, base)] + if not any(moved): + continue + forms = _coordinate_forms(base, x, moved, syms) + if any(not f for f in forms): + continue + # the identity first, then the simplest forms + forms = [sorted(f, key=lambda e: (e != s, spy.count_ops(e))) for f, s in zip(forms, syms)] + for combo in itertools.islice(itertools.product(*forms), cap): + if meter.over: + return maps + sig = dict(zip(syms, combo)) + if any(all(spy.simplify(sig[s] - m[s]) == 0 for s in syms) for m in maps): + break + if _keeps(system, sig, rng): + maps.append(sig) + break + return maps + + +def _keeps(system, sig, rng, points=2): + """Whether the map `sig` keeps the coefficients of `system` at `points` random points within _TOL.""" + syms = list(system.series.cs) + f = spy.lambdify(syms, [sig[s] for s in syms], "numpy") + for _ in range(points): + th = 0.5 + rng.random(len(syms)) + img = np.asarray(f(*th), dtype=complex) + got = coefficients(system.series, np.array([th, img]), system.orders, system.gap, jac=False) + if got is None: + return False + a, b = got[0] + if np.max(np.abs(a - b) / (1 + np.abs(a))) > _TOL: + return False + return True + + +def propose(series, fib, meter=None, target=None): + """{"points", "square", "source", "certified", "boxes", "base", "why"} and the maps read from the points + (unproven): the points of the fiber at a random rational point, by monodromy where the square subsystem has + at most _SQUARE points modulo a prime, and where it stops short of the count `target`, from the rational + 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: + out["why"] = "copies with a free start on a switching surface" + return out, [] + n = len(series.cs) + orders = fib.orders + rows = series.rank_rows(max(orders) + 2, PRIMES[0]) + if rows is None or len(rows) != n: + 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)) + 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: + with np.errstate(all="ignore"): + system = _System(series, orders, rows, base, fib.gap) + except ZeroDivisionError: + 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} + with work.quick_msolve(): + est = complex_count(Fiber(series, system.sub_orders, fib.positive), pt, PRIMES[0]) + out["square"] = est + pts = np.zeros((0, n), dtype=complex) + if est is not None and est <= _SQUARE: + with np.errstate(all="ignore"): + pts, _ = monodromy(system, rng, meter, target) + out["source"] = "monodromy" + if meter.over: + out["why"] = meter.reason() + # without a count the fiber has no finite parametrization to take + if target is not None and len(pts) < target and not meter.over: + more = rur_points(fib, base) + if more is not None and len(more): + with np.errstate(all="ignore"): + more = more[system.residual(more) < _TOL] + add = [x for x in more if _new(list(pts), x)] + if add: + pts = np.vstack([pts] + [np.array(add)]) + out["source"] = "monodromy and parametrization" if out["source"] else "parametrization" + out["points"] = len(pts) + boxes = [] + for x in pts: + if meter.over: + break + b = certify(series, orders, fib.gap, base, x) + if b is not None and all(disjoint(b, c) for c in boxes): + boxes.append(b) + out["certified"], out["boxes"] = len(boxes), boxes + with np.errstate(all="ignore"): + maps = read_maps(system, pts, rng, meter) + return out, maps + + +def proposals(series, fib, k, known, meter=None): + """(info, maps): the result of propose() at the orders of the fiber `fib` and the proposed maps that are not in + `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))] + if k is not None and grp is not None and len(grp) >= k: + return None, [] + info, maps = propose(series, fib, meter, target=k) + new = [m for m in maps if not any(_same_map(m, x) for x in known)] + info["maps"] = [{str(s): str(e) for s, e in m.items() if e != s} for m in new] + return info, new diff --git a/src/symident/detection/multiexp.py b/src/symident/detection/multiexp.py new file mode 100644 index 0000000..0913a90 --- /dev/null +++ b/src/symident/detection/multiexp.py @@ -0,0 +1,182 @@ +"""The count of several experiments: K copies of a model with free starts share the parameters, each with other +starts, and the count of their fiber on the parameters and the starts of the first bounds the fiber of the model where +the model has no nonconstant rational first integral (docs/method/global.rst, "Several experiments").""" + +import math +import re +import time + +import sympy as spy + +from ..gfp import PRIMES + +# the most experiments the choice tries +_MAX_EXPERIMENTS = 8 + + +def eligible(series): + """(starts, why): per state with an unknown series the coordinate it starts from, or None and the reason where + the route does not apply: one condition without events and switches, every state starting from a coordinate + that nothing else reads, and no clock read.""" + if len(series.parts) != 1: + return None, "the route takes a model with one condition" + part = series.parts[0] + if len(part["segs"]) != 1 or series.has_events: + return None, "the route takes a model without events" + seg = part["segs"][0] + if seg.get("free") or seg.get("on") is not None: + return None, "the route takes a model without switches" + st = part["st"] + ns, known = len(st), set(part["known"]) + params = list(series.params) + starts = {} + for i, x in enumerate(st): + if i in known: + continue + v = seg["x0"][i][0] + if v is None or not v.is_Symbol or v not in series.cs: + return None, f"the start of {x} is fixed ({v}): the flow from a later start leaves the family of starts" + if v in starts.values(): + return None, f"two states start from the coordinate {v}" + starts[i] = v + # a coordinate a start takes must enter the model only there + used = set() + for P in [P for N, D in list(seg["F"]) + list(seg["G"]) for P in (N, D)]: + for m in P: + used |= {params[j - ns] for j, e in enumerate(m) if e and j >= ns} + for v in starts.values(): + 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} + if reads & clocks: + return None, "the model reads the clock" + return starts, None + + +def conservation_laws(seg, states): + """A basis of the linear forms sum_i c_i x_i in `states` that the right-hand sides of the segment keep constant, + sum_i c_i f_i = 0 identically in the states and inputs, the coefficients rational in the other symbols; each + as {state: coefficient}, in reduced echelon form (a pivot state with coefficient one per law).""" + 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"]] + others = sorted(set().union(*[e.free_symbols for e in rhs]) - set(variables), key=str) + nums, dens = zip(*[spy.fraction(spy.together(e)) for e in rhs]) + common = spy.lcm_list(list(dens)) if dens else spy.Integer(1) + cols = [spy.Poly(spy.expand(n * spy.cancel(common / d)), *variables) for n, d in zip(nums, dens)] + monos = sorted({m for P in cols for m in P.monoms()}) + if not monos: + return [{str(x): spy.Integer(1)} for x in xs] + rows = [[P.coeff_monomial(mm) for P in cols] for mm in monos] + dom = spy.QQ.frac_field(*others) if others else spy.QQ + M = DomainMatrix.from_Matrix(spy.Matrix(rows)).convert_to(dom) + null = M.nullspace() + if null.shape[0] == 0: + return [] + R = null.rref()[0].to_Matrix() + out = [] + for r in range(R.rows): + law = {str(x): spy.factor(R[r, j]) for j, x in enumerate(xs) if R[r, j] != 0} + if law: + out.append(law) + return out + + +def _fresh(name, k, taken): + """The name of `name` in experiment k, clear of `taken`, which it joins.""" + out = f"{name}_e{k}" + while out in taken: + out += "_" + taken.add(out) + return out + + +def stacked(parts, coords, series, starts, K, laws=()): + """(parts, coords): K experiments of the single condition of `parts`, the first with the starts of the model, the + others with new start coordinates, on the level set of the conservation `laws` of the first: the pivot state of + 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))} + first = {st[i]: spy.Symbol(str(v)) for i, v in starts.items()} + pivots = [next(iter(law)) for law in laws] + out, extra = [], [] + for k in range(K): + ic = dict(seg["ic"]) + if k: + new = {} + for i, v in starts.items(): + if st[i] not in pivots: + new[st[i]] = spy.Symbol(_fresh(str(v), k + 1, taken)) + extra.append(str(new[st[i]])) + for x, law in zip(pivots, laws): + c = {y: model_sympify(str(e)) for y, e in law.items()} + g = sum((c[y] * first[y] for y in c), spy.Integer(0)) + new[x] = g - sum((c[y] * new[y] for y in c if y != x), spy.Integer(0)) + ic.update({x: str(e).replace("**", "^") for x, e in new.items()}) + out.append({"segments": [dict(seg, ic=ic, label=f"e{k + 1}:")]}) + return out, list(coords) + extra + + +def plan(parts, coords, series, starts, ks=None, laws=()): + """[(K, series, crit)] per number of experiments K in `ks` (by default 2 up to the parameters over the + 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) + ks = range(2, min(_MAX_EXPERIMENTS, max(2, math.ceil(n_t / max(1, n_y)) + 1)) + 1) + out = [] + for K in ks: + pk, ck = stacked(parts, coords, series, starts, K, laws) + sk = Series(pk, ck) + crit = sk.output_orders(2 * len(ck), PRIMES[0]) + if crit is not None: + out.append((K, sk, crit)) + out.sort(key=lambda e: (max(e[2]), e[0])) + return out + + +def count(parts, coords, series, positive, floor, experiments=None): + """The multi-experiment count: {"why"} where the route does not apply, else {"experiments", "orders", "count", + "first_integrals", "fiber", "crit", "seconds"}, with "failed" where msolve gives no count. The experiments share + the level set of the conservation laws of the first; the count modulo a prime takes the orders from the rank + 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: + return {"why": why} + st = [str(x) for x in series.parts[0]["st"]] + # linear first integrals are declared by the laws: the experiments share their level set + 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} + 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: + return {"why": "the stacked experiments do not reach full rank", "first_integrals": fi} + K, sk, crit = plans[0] + # a function proven in the field of the outputs of one experiment holds on the first of them + pad = (0,) * (len(sk.cs) - len(series.cs)) + 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)} + if cc is None: + out["failed"] = discrete.no_count_reason(fib.order) + return out diff --git a/src/symident/detection/observability/analysis.py b/src/symident/detection/observability/analysis.py index 84aa377..30499c1 100644 --- a/src/symident/detection/observability/analysis.py +++ b/src/symident/detection/observability/analysis.py @@ -1,6 +1,7 @@ """Observability over GF(p) for all conditions: saturated kernel, certified Lie order, scalings, residual directions.""" import re +import time import warnings import numpy as np @@ -10,8 +11,9 @@ from ...gfp import PRIMES, SpanTest, in_span, null_residues, random_point, uniform_point, verify_prime from ...par import thread_map from ...rexpr import sym_sort -from ...sym.msolve import MsolveMissingError, msolve_timeout +from ...sym.msolve import MsolveMissingError from ...sym.parse import model_sympify +from ...sym.shared import kernel_tapes from ..classify import joint_expand_scal, peel_scalings, report_physical from ..closedform import recast_backsub from ..conditions import scaling_component @@ -26,11 +28,13 @@ rank_of, rank_score, regime_keys, + scaling_tapes, static_fields, ) from ..rank import nullspace_basis, saturate_certify from ..verify import verify_in_nullspace -from .context import Run, ok, strs +from . import select +from .context import Run, ints, ok, strs from .guard import saturation_guard from .joint import JointSystem from .plain import PlainSystem @@ -62,6 +66,14 @@ def _rational_forms(exprs): _REWRITE_STEPS = 64 +def _int_weight(w, p): + """An integer weight modulo p; 0 for a weight symbolic in a coordinate, which leaves the rank a lower bound.""" + try: + return int(str(w)) % p + except ValueError: + return 0 + + def _in_rational_span(w, ws): """Whether the integer weights `w` are a rational combination of the weight vectors `ws`.""" names = sorted({k for v in [w, *ws] for k in v}) @@ -162,7 +174,7 @@ def kbatch(self, point_list, prime_vec, Nt): def leaves(): 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.tapes, run.n_leaves, run.n_states, run.z_slots, leaves(), + 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: @@ -174,7 +186,7 @@ def 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.tapes, run.n_leaves, run.n_states, run.z_slots, leaves(), + 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: @@ -199,6 +211,68 @@ def leaves(): if self.joint: self.sys.warm_off = warm_saved + def cover_tapes(self): + """The tapes of the conditions whose rows reach the rank of all of them at the base point (sym_obs_cover), + formed once; None where the path has no cover or every condition is needed. Kernels on them propose + values only: every closed form is checked on all conditions.""" + run, sc = self.run, self.sc + if "_cover" in self.__dict__: + return self._cover + 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) + 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) + return self._cover + + def kbatch_cover(self, point_list, prime_vec, Nt): + """kbatch() on the cover of the conditions where there is one.""" + tapes = self.cover_tapes() + 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) + + def lanes(self): + """Whether each column of V annihilates the rows of the cover at each of many points, from jets seeded + along the columns (sym_obs_annihilates_batch): per point a boolean array, None at a point without + the rows; None without the path.""" + if not self.can_batch: + return None + run = self.run + + 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) + 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): + """Whether each column of V annihilates all rows, in one pass over the conditions; None without the path.""" + run = self.run + if run.has_gaps or run.ss_constraint or self.recast or run.nuis_cols or self.transient: + 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) + return [bool(x) for x in np.atleast_1d(o["zero"])] if ok(o) else None + return f + def dir_call(self): """Whether a direction annihilates all rows, from jets along it; None without the path.""" run = self.run @@ -206,7 +280,7 @@ def dir_call(self): return None def f(pt, q, Nt, v): - o = _core.sym_obs_directional(run.tapes, run.n_leaves, run.n_states, run.z_slots, + 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): @@ -306,7 +380,7 @@ def _scaling_cap(self): x = np.zeros(sys.n_shared, dtype=np.int64) for k, w in v.items(): if k in shared: - x[shared.index(k)] = int(w) % PRIMES[0] + 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), @@ -346,7 +420,8 @@ def saturate(self): 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) + 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 " @@ -802,6 +877,8 @@ 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 x = np.zeros(len(pp), dtype=np.int64) for k, w in v.items(): if k in pp: @@ -840,23 +917,22 @@ def _direct_kernel(self, ker_dim): # 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 []) - with msolve_timeout(float(state.env_value("DIRECTSECS", "120"))): - pt_d = None - for base in bases: - try: - pt_d = sys.sat_prep(base, rounds=2) - except Exception as exc: - swallow(exc, "direct kernel point") - pt_d = None - if pt_d is not None: - break - if pt_d is None: - pt_d = self.point0_solved + pt_d = None + for base in bases: try: - rc = self.kcall4(pt_d, PRIMES[0], sc["nt_used"], sc.get("mtot_used") or 0) - except Exception as e: - swallow(e, "direct kernel") - rc = {"ok": False, "why": str(e)} + pt_d = sys.sat_prep(base, rounds=2) + except Exception as exc: + swallow(exc, "direct kernel point") + pt_d = None + if pt_d is not None: + break + if pt_d is None: + pt_d = self.point0_solved + try: + rc = self.kcall4(pt_d, PRIMES[0], sc["nt_used"], sc.get("mtot_used") or 0) + except Exception as e: + swallow(e, "direct kernel") + 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: " + @@ -876,8 +952,9 @@ 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 - model_lines = [strs(t.get("model_lines")) for t in self.multi["tapes"]] - obs_lines = [strs(t.get("obs_lines")) for t in self.multi["tapes"]] + 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: @@ -890,7 +967,7 @@ def _peel(self): res = None # a scaling is exact where initial values and events are checked too: those of the whole model come first ws = self.exact_scalings(self.scal_fixed) - states = {l.split("=", 1)[0].strip() for t in self.multi["tapes"] for l in strs(t.get("model_lines"))} + states = {l.split("=", 1)[0].strip() for t in tapes for l in strs(t.get("model_lines"))} def lift(w): # a scaling acts on the states by the scaling weights; with unknown inputs the lift gives their change @@ -908,7 +985,8 @@ def lift(w): 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) + 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): @@ -1149,6 +1227,7 @@ def _eliminate_states(self, dirs): if not self.joint or not lines or not states: return dirs coords = {z for z in self.znames if not _CSUFFIX.search(z)} + atoms = set(self.atom_names or []) try: eqs = [model_sympify(ln.split("=", 1)[1]) for ln in lines] except SYMPY_FAILS as exc: @@ -1161,8 +1240,9 @@ def _eliminate_states(self, dirs): out.append(d) 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 v in vec.values()) + 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) @@ -1506,7 +1586,7 @@ def _prove_by_scalings(self, result): for i, v in enumerate(ws): for k, w in v.items(): if k in coords: - V[i, coords.index(k)] = int(w) % PRIMES[0] + V[i, coords.index(k)] = _int_weight(w, PRIMES[0]) if self.static_rows is not None and all(c in self.phys_params0 for c in coords): V = np.vstack([V, np.asarray(self.static_rows)[:, [self.phys_params0.index(c) for c in coords]]]) k = int(_core.sym_rref_mod(V.astype(np.float64), PRIMES[0])["rank"]) if V.size else 0 @@ -1582,10 +1662,97 @@ def observability_analytic_multi(multi, closed_form=False, cores=1, equil_zero_s 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.""" - an = Analysis(multi, closed_form, cores, equil_zero_states, cond_zero_states, t0events, n_conditions, - chain_of, n_gaps, implicit_steady_state, control, verify, codim_spec) - out = an.execute() - if isinstance(out, dict): - an.run.stage("done") - out["timing"] = list(an.run.stages) - return out + 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) + + def analyze(idx): + an = build(idx) + out = an.execute() + if isinstance(out, dict): + 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: + return out + return analyze(list(range(K))) + + +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: + an.sys.unchain() + for i in range(len(an.sys.cont_off)): + an.sys.cont_off[i] = True + pt = random_point(an.run.n_leaves, seed=session.current().seed("selection rest proof") % (1 << 31)) + pt = an.sys.sat_prep(pt, rounds=2) + if pt is None: + return "no resting state at a random point" + an.sc = {"point0": pt} + return _rest_proof(an, d) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return f"{type(exc).__name__}" + except Exception as exc: + swallow(exc, "selection rest proof") + return f"{type(exc).__name__}" + + +def _on_selection(multi, build, analyze, rest, cores): + """The analysis on the conditions that change the rank at a random point, with each direction proven on the + others; None where that does not pay or a direction is not shown on a condition left out. With `rest`, the + conditions start at rest.""" + t0 = time.monotonic() + K = len(multi["tapes"]) + if rest: + sel = select.choose_resting(build(list(range(K))), *select.taking_order(multi["tapes"])) + else: + sel = select.choose(multi, cores) + if sel is None: + return None + kept = sel["kept"] + for rnd in range(select._ROUNDS): + 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) + out = analyze(kept) + if not isinstance(out, dict) or out.get("rerun_blocks"): + return out + nt = int(out.get("lie_order_used") or 0) + if not rest and nt > sel["lie_order"] and out["rank"] < out["dim"]: + # the conditions that raise the rank of the kept ones at the order the analysis reached + more = select.choose(multi, cores, nt, kept) + sel["lie_order"] = nt + if more is None: + return None + if set(more["kept"]) - set(kept): + 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) + 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["conditions"] = K + return out + kept = sorted(set(kept) | set(cov["add"])) + return None diff --git a/src/symident/detection/observability/context.py b/src/symident/detection/observability/context.py index 5493557..ee76dfc 100644 --- a/src/symident/detection/observability/context.py +++ b/src/symident/detection/observability/context.py @@ -1,5 +1,6 @@ """The shared state of one observability analysis.""" +import hashlib import os import threading import time @@ -8,6 +9,7 @@ from ... import _core, state from ...par import process_map, thread_map +from ...sym.shared import kernel_tapes from ...sym.tape import _OP_SPOW @@ -32,17 +34,33 @@ def ok(r): return r is not None and bool(r.get("ok")) -def tape_fields(t): - """The kernel's view of one compiled tape.""" - out = {"op": ints(t.get("op")), "a": ints(t.get("a")), "b": ints(t.get("b")), - "cnum": strs(t.get("cnum")), "cden": strs(t.get("cden")), - "state_slots": ints(t.get("state_slots")), "f_out": ints(t.get("f_out")), - "g_out": ints(t.get("g_out")), "ic_leaf": ints(t.get("ic_leaf")), - "ic_num": strs(t.get("ic_num")), "ic_den": strs(t.get("ic_den"))} +def tape_fields(t, memo=None): + """The kernel's view of one compiled tape; with `memo`, arrays that tapes share are converted once and stay + shared.""" + memo = {} if memo is None else memo + + def conv(x, f): + if x is None: + return f(x) + k = (id(x), f) + if k not in memo: + memo[k] = (x, f(x)) + return memo[k][1] + + def iv(k): + return conv(t.get(k), ints) + + 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")} if t.get("ic_op") is not None: - out.update({"ic_op": ints(t["ic_op"]), "ic_a": ints(t["ic_a"]), "ic_b": ints(t["ic_b"]), - "ic_cnum": strs(t["ic_cnum"]), "ic_cden": strs(t["ic_cden"]), - "ic_out": ints(t["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"])}) 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"]), @@ -58,7 +76,7 @@ def tape_fields(t): # 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") + "tm_a", "tm_b", "tm_out", "leaf_src") def read_columns(tapes, n_leaves, z_slots): @@ -172,7 +190,8 @@ def __init__(self, multi, cores, ctrl, chain_of, n_gaps, t0events, cond_zero_sta self.max_gap = int(ctrl["gap_order_cap"]) if self.has_gaps else 0 units = len(self.chain_groups) if self.has_gaps else len(multi["tapes"]) self.cores_call = int(max(1, min(self.cores, units))) - self.tapes = [tape_fields(t) for t in multi["tapes"]] + memo = {} + self.tapes = [tape_fields(t, memo) for t in multi["tapes"]] self.t0events = list(t0events or []) self.cond_zero_states = list(cond_zero_states or []) self.equil_zero_states = list(equil_zero_states or []) @@ -282,8 +301,11 @@ def chain_rows(self, idx, point, p, Nt, Mtot, threads, zs, cols): if e0 is None: 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) + 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), @@ -294,6 +316,16 @@ def chain_rows(self, idx, point, p, Nt, Mtot, threads, zs, cols): "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): + """A digest of what the kernel reads of the tapes `idx`, memoized.""" + 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() + return memo[key] + def _keep_rows(self, key, e): """Keep the rows `e` of chain_rows under `key`.""" memo = self.__dict__.setdefault("_chain_rows", {}) @@ -389,6 +421,13 @@ def block_threads(self): """Threads per block call: one with gaps, else all cores.""" return 1 if self.has_gaps else self.cores + def kernel_tapes(self): + """The tapes for a kernel call over every tape (kernel_tapes), formed once.""" + kt = self.__dict__.get("_kernel_tapes") + if kt is None or kt[0] is not self.tapes: + kt = self._kernel_tapes = (self.tapes, kernel_tapes(self.tapes)) + return kt[1] + def chain_tapes(self, idx): """The tapes at the indices `idx`.""" return [self.tapes[i] for i in idx] diff --git a/src/symident/detection/observability/joint.py b/src/symident/detection/observability/joint.py index 3e558d3..36ec69f 100644 --- a/src/symident/detection/observability/joint.py +++ b/src/symident/detection/observability/joint.py @@ -600,6 +600,10 @@ def f(point, p, Nt, Mtot=0): return f return [mk(mi) for mi in range(self.kc)] + def stacked_profile(self): + """No stacked profile: the joint rows hold the resting constraints.""" + return None + def block_profiles(self): """The rank per Lie order of a condition's chain from one jet (gap paths).""" run = self.run diff --git a/src/symident/detection/observability/narrow.py b/src/symident/detection/observability/narrow.py index 8279935..2f1dd01 100644 --- a/src/symident/detection/observability/narrow.py +++ b/src/symident/detection/observability/narrow.py @@ -8,8 +8,11 @@ from ...errors import SYMPY_FAILS, swallow, sympy_fail from ...gfp import PRIMES, invmod, mulmod from ...rexpr import sym_sort +from ...sym.shared import kernel_tapes from ..groups import shift_groups, translation_groups from ..interp import exp_backsub, interpolate_direction +from ..perprime import _lift_const +from ..relevance import direction_relevance from ..verify import verify_in_nullspace from .context import ints, ok, strs @@ -30,6 +33,8 @@ def __init__(self, rec, bf, anchor): self.nt = an.sc["nt_used"] self.conds = None self.fpos = None + self.sub = None + self.wide = False def res(rp, p, zvals=None): return self.residue(rp, p) @@ -60,7 +65,8 @@ def kb(self, point_list, prime_vec, Nt): 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_ - os_ = _core.sym_obs_null_batch(run.tapes, run.n_leaves, run.n_states, self.zs, M, list(prime_vec), + 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) if not an.transient: return [run.modulo_nuisance(o, q, nc) for o, q in zip(os_, prime_vec)] if nc else os_ @@ -81,6 +87,29 @@ def kb(self, point_list, prime_vec, Nt): "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): + """The conditions whose rows on the support reach the rank of all of them at the base point (sym_obs_cover): + their kernel on the support is the kernel of all conditions there, so the fits read them alone; the + closed form is checked on every condition afterwards.""" + 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) + if not ok(r) or int(r["rank"]) != self.m - 1: + return + idx = ints(r["conditions"]) + self.sub = (idx, kernel_tapes([run.tapes[i] for i in idx])) + + def lanes(self): + """Analysis.lanes on the conditions the kernels of the support read, at the Lie order of the support.""" + f = self.an.lanes() + if f is None or self.an.joint: + return None + tapes = self.an.run.kernel_tapes() if self.sub is None else self.sub[1] + return lambda points, primes, Nt, V: f(points, primes, min(Nt, self.nt), V, tapes) + def kc(self, point, p, Nt): """The kernel on the column subset at `point` mod `p`, Lie order `Nt`.""" return self.kb([point], [p], Nt)[0] @@ -128,7 +157,8 @@ 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"]))] + 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 = [] @@ -172,11 +202,24 @@ def _jet(self, limit): "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 + translation group is needed.""" + 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) + 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"] + 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, an.ctrl, self.kb, aux_leaves=an.aux_leaves) + 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) @@ -185,30 +228,88 @@ def _fit(self, ref, base0, rel): r.pop("fit_how", None) return r + def _read_off(self, want): + """The direction where the entries are constants, or constants times the coordinate (a scaling on the + support, the direction times the anchor coordinate): read at the base point, held at two fresh points and + lifted from the primes; None otherwise.""" + an, sc, P = self.an, self.an.sc, PRIMES[0] + zs = an.z_slots + if not len(zs): + return None + a = self.anchor + + 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) + base0 = np.asarray(sc["point0"], dtype=np.int64) + w0 = logw(want, base0, P) + kinds = {"constant": want[self.cols] % P, "scaling": w0} + for _ in range(2): + pt = np.asarray(sc["pool"](self.rec.pool_next + np.arange(len(base0))), dtype=np.int64) + self.rec.pool_next += len(base0) + v = self.res(self.kc(pt, P, self.nt), 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)} + if not kinds: + return None + kd = "constant" if "constant" in kinds else "scaling" + per = [] + for p in PRIMES: + v = self.res(self.kc(base0, p, self.nt), p) + if v is None: + continue + per.append((v[self.cols] % p if kd == "constant" else logw(v, base0, p), p)) + if not per or any(x is None for x, _ in per): + return None + vec = {} + for j, c in enumerate(self.cols): + w = _lift_const([int(x[j]) for x, _ in per], [p for _, p in per]) + if w is None: + return None + 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})"} + def _shorter_order(self, ref, want): - """The lowest Lie order among 4, 8, 16, 32 that still gives the direction.""" - for k in (4, 8, 16, 32): - if k >= self.nt: - break + """The lowest Lie order among the powers of two from 4 below the order of the kernel that still gives the + direction.""" + k = 4 + while k < self.nt: rk = self.kc(self.an.sc["point0"], PRIMES[0], k) bk = self.res(rk, PRIMES[0]) if bk is not None and np.array_equal(bk, want): self.nt = k return rk + k *= 2 return ref def run(self): """The direction as an entry, or None when the support does not contain it.""" an, rec, sc, P = self.an, self.rec, self.an.sc, PRIMES[0] run, ctrl = an.run, an.ctrl - if self.m < 2: + if not self.m: return None if an.joint and any(_CSUFFIX.search(an.znames[c]) for c in self.cols): return None + if self.m == 1: + # 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)"}) self.fpos = self.cols.index(self.anchor) if an.joint and not self._touched(): return None res = self.res + self._cover() ref = self.kc(sc["point0"], P, sc["nt_used"]) base = res(ref, P) want = mulmod(self.bf % P, invmod(int(self.bf[self.anchor]) % P, P), P) @@ -220,9 +321,26 @@ def run(self): 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 "")) - rel = rec.probe_groups(self.kb, ref["pivots"], rec.pool_next, res, ref) + # 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 + lanes = self.lanes() + cap = ctrl["relevance_cap_dir"] if self.m > 6 or state.env("NOJET") else None + if cap is not None: + e = self._read_off(want) + if e is not None: + 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) rec.pool_next += an.n_aug * (ctrl["probe_retries"] + 16) - groups = [] if state.env("NOGROUP") else translation_groups(rel, ref, res, self.kb, sc, P, run.n_leaves) + 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) 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"]] @@ -232,7 +350,13 @@ 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) + 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"} rec.pool_next += an.n_aug * (ctrl["probe_retries"] + 16) else: groups = [g for g in groups if g.get("type") != "mul"] @@ -265,13 +389,26 @@ def run(self): 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) + + def _checked(self, e): + """The closed form `e` checked at fresh points, or marked for the joint check of the narrow route.""" + an, rec, sc = self.an, self.rec, self.an.sc + 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"} - eb = an.multi.get("exp_back") or {} - if eb.get("names"): - e.setdefault("checked", dict(e["vector"])) - e["vector"] = exp_backsub(e["vector"], eb, an.multi.get("exp_atoms")) - return e + return back_substituted(an, e) + + +def back_substituted(an, e): + """The closed form `e` in the coordinates of the model, the checked form kept.""" + eb = an.multi.get("exp_back") or {} + if eb.get("names"): + e.setdefault("checked", dict(e["vector"])) + e["vector"] = exp_backsub(e["vector"], eb, an.multi.get("exp_atoms")) + return e diff --git a/src/symident/detection/observability/plain.py b/src/symident/detection/observability/plain.py index e01ed26..e90425f 100644 --- a/src/symident/detection/observability/plain.py +++ b/src/symident/detection/observability/plain.py @@ -107,7 +107,7 @@ def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): 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.tapes, run.n_leaves, run.n_states, run.z_slots, pt, p, + 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) @@ -214,3 +214,15 @@ def block_calls(self): def block_profiles(self): """The rank per Lie order of a block from one jet.""" return self.run.obs_block_profiles() + + def stacked_profile(self): + """The rank per Lie order of the rows of every tape from one jet, None where kcall adds further rows or the + tapes have gaps.""" + run = self.run + if run.has_gaps or run.nuis_cols or self.transient: + 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 f diff --git a/src/symident/detection/observability/proof.py b/src/symident/detection/observability/proof.py index a5b8f0b..9bb50a9 100644 --- a/src/symident/detection/observability/proof.py +++ b/src/symident/detection/observability/proof.py @@ -9,6 +9,7 @@ from ... import session, state from ...errors import SYMPY_FAILS, RouteError, swallow, sympy_fail from ...gfp import PRIMES, rref_modp +from ...par import process_map from ...sym.direction import classify_generator from ...sym.exact import ( _rhs, @@ -51,10 +52,12 @@ def _fail(dirs, why): def _weights(vec): + """Rational weights, or weights rational in coordinates (the weight of a recast power); None otherwise.""" try: - return {k: spy.Rational(str(v)) for k, v in vec.items()} - except (TypeError, ValueError, SyntaxError): + out = {k: model_sympify(str(v)) for k, v in vec.items()} + except SYMPY_FAILS: return None + return out if all(x.is_Rational or (x.is_rational_function() and x.free_symbols) for x in out.values()) else None def _exact_scalings(an, dirs): @@ -62,16 +65,20 @@ def _exact_scalings(an, dirs): as the lift.""" ws = [_weights(w) for w in an.exact_scalings(an.scal_fixed)] coords = set(an.znames) - {an.znames[i] for i in an.run.nuis_cols} + # 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: 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) for w in ws: if not w or not w.get(k0): continue - c = v[k0] / w[k0] - if all(v.get(k, 0) == c * w.get(k, 0) for k in set(v) | (set(w) & coords)): + 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)): 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)} @@ -183,26 +190,42 @@ def _output_proof(light, chains, vec): return certify(ids) -def light_proofs(light, chains, dirs, joint, plain, forms): +# directions past which a pass of the lifts runs in forked workers +_PAR_LIFTS = 16 + + +def light_proofs(light, chains, dirs, joint, plain, forms, map_fn=None): """Each of `dirs` proven by the lift of one form of the direction, else, with `plain`, by the output identities. - A direction proven makes the others a new try, since their brackets may contain its field.""" + 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): + ex = exact_direction(light, vec, chains, joint, known=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'}") known, todo = [], list(dirs) while todo: left = [] - for d in todo: - first = None - for vec in forms(d): - ex = exact_direction(light, vec, chains, joint, known=known) - if ex["ok"] is True: - d["exact"], d["state_components"] = True, lift_of(d, vec, ex.get("states")) - d.pop("proof", None) - known.append(ex["fields"]) - break - first = first or ex + if map_fn is not None and len(todo) >= _PAR_LIFTS: + fixed = list(known) + got = map_fn(lambda d: attempt(d, fixed), todo) + else: + got = None + for k, d in enumerate(todo): + r = attempt(d, known) if got is None else got[k] + vec, ex, why = r if r is not None else (None, None, "lift of the closed form: a worker failed") + if ex is not None: + d["exact"], d["state_components"] = True, lift_of(d, vec, ex.get("states")) + d.pop("proof", None) + known.append(ex["fields"]) else: - d["proof"] = ("no lift through an inverted power recast" if first is None else - f"lift of the closed form: {first.get('why') or 'undecided'}") + d["proof"] = why left.append(d) if len(left) == len(todo): break @@ -676,7 +699,7 @@ def _rest_degrees(an, q): # routes whose closed forms pass the kernel check at points uniform modulo the verification prime -_RANDOM_ROUTES = ("fit", "read-off", "narrow fit", "jets", "homotopy fit") +_RANDOM_ROUTES = ("fit", "read-off", "narrow", "jets", "homotopy fit") def _checked_at_random(route): @@ -736,7 +759,8 @@ def prove_exact(an, result): 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)) + 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") diff --git a/src/symident/detection/observability/reconstruct.py b/src/symident/detection/observability/reconstruct.py index cf66578..d1c6e47 100644 --- a/src/symident/detection/observability/reconstruct.py +++ b/src/symident/detection/observability/reconstruct.py @@ -20,16 +20,16 @@ ) from ...rexpr import sym_sort from ...sym.restforward import excluding_rates -from ..closedform import expired, recast_backsub, simplify +from ..closedform import recast_backsub, simplify from ..fields import field_directions, field_setup from ..forward import fwd_adopt, perprime_forward_multi, perprime_forward_shared from ..interp import entry_degrees, exp_backsub, interpolate_direction from ..perprime import interpolate_perprime from ..relevance import build_shared_bank, dense_need, direction_relevance -from ..verify import verify_direction, verify_in_nullspace +from ..verify import verify_batch, verify_direction, verify_in_nullspace from .context import ints, ok, strs from .homotopy import Homotopy -from .narrow import _CSUFFIX, Narrow +from .narrow import _CSUFFIX, Narrow, back_substituted # minimal supports the narrow route tries beyond one per residual direction _CIRCUIT_CAP = 16 @@ -47,7 +47,7 @@ def _coord(nm): def _actionable(reason): """Whether a reason names a cap or setting to change.""" - return reason is not None and any(w in str(reason) for w in ("raise", "cap", "timeout", "time limit")) + return reason is not None and any(w in str(reason) for w in ("raise", "cap")) # samples of a dense fit past which the log-coordinate gauge is tried first @@ -62,15 +62,12 @@ def __init__(self, an, residual): self.residual = list(residual) self.ctrl = an.ctrl self.dir_call = an.dir_call() + # the kernels that propose closed forms: on a cover of the conditions where the path has one + self.kb = an.kbatch_cover if an.can_batch else an.kbatch + # the closed forms of the narrow route are checked together after the route, where the path allows it and + # many directions are open + self.dir_batch = an.dir_batch() if len(residual) >= 8 else None self.t0 = time.monotonic() - to = self.ctrl.get("timeout") - # one deadline per detection: reruns and nested analyses share it - ses = state.get("session") - dl = self.t0 + to if to is not None and np.isfinite(to) else None - if ses is not None and dl is not None: - ses.deadline = dl if ses.deadline is None else ses.deadline - dl = ses.deadline - self.ctrl["deadline"] = dl self.probe_next = self.sc["pool_next"] self.pool_next = self.probe_next + an.n_aug * (self.ctrl["probe_retries"] + 16) self.zvals0 = np.asarray(self.sc["point0"])[an.z_slots] if len(an.z_slots) else None @@ -145,7 +142,7 @@ def probe(self, kb, piv0, first, base=None, leaves=None): pending = list(leaves) piv0 = ints(piv0) for att in range(ctrl["probe_retries"]): - if not pending or expired(ctrl): + if not pending: break perts = [] for li in pending: @@ -162,9 +159,18 @@ def probe(self, kb, piv0, first, base=None, leaves=None): pending = [li for li, r in zip(pending, resolved) if not r] return rp - def probe_groups(self, kb, piv0, first, res_fn, ref, base=None): - """Relevance probe by bisection over leaf groups; a group that leaves the residues unchanged is irrelevant.""" + def probe_groups(self, kb, piv0, first, res_fn, ref, base=None, stop_above=None, vecs=None, lanes=None): + """Relevance probe by bisection over leaf groups; a group that leaves the residues unchanged is irrelevant. + With `stop_above`, the groups halve down to single leaves, and None is returned as soon as more leaves off + the auxiliary ones are relevant. With `vecs` (the kernel vectors of the residues at `base`, nz x D), a + group leaves the residues unchanged where the vectors annihilate the rows at the point of the group + (Analysis.lanes), and the kernel is formed only where a single leaf moves them; `lanes` replaces + Analysis.lanes.""" an, sc, ctrl, P = self.an, self.sc, self.ctrl, PRIMES[0] + if vecs is None: + lanes = None + elif lanes is None: + lanes = an.lanes() if base is None: base = sc["point0"] bv = res_fn(ref, P) @@ -176,6 +182,11 @@ def probe_groups(self, kb, piv0, first, res_fn, ref, base=None): rp = [{"rp": ref, "zvals": zb, "pertval": base[li]} for li in range(an.n_aug)] off = first + an.n_aug * ctrl["probe_retries"] groups = [list(range(an.n_aug))] + if stop_above is not None: + # parallel groups first, then halves: the rounds stay few and the found leaves are counted as they come + per = max(1, -(-an.n_aug // 64)) + groups = [list(range(i, min(an.n_aug, i + per))) for i in range(0, an.n_aug, per)] + aux, found = set(an.aux_leaves), 0 single = [] while groups: perts = [] @@ -184,13 +195,24 @@ def probe_groups(self, kb, piv0, first, res_fn, ref, base=None): pt[g] = sc["pool"](off + np.arange(len(g))) off += len(g) perts.append(pt) - cands = kb(perts, [P] * len(perts), sc["nt_used"]) + zero = lanes(perts, [P] * len(perts), sc["nt_used"], vecs) if lanes is not None else None + if zero is None: + cands = kb(perts, [P] * len(perts), sc["nt_used"]) + else: + 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 []): + 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 - if v is not None and np.array_equal(np.asarray(v), np.asarray(bv)): + 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: own = [c for c, nm in enumerate(an.znames) if nm == an.leaf_names_aug[li]] @@ -205,9 +227,14 @@ def probe_groups(self, kb, piv0, first, res_fn, ref, base=None): elif piv_ok: 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: single.append(g[0]) - if len(nxt) > len(groups): + if stop_above is not None: + if found + len([x for x in single if x not in aux]) > stop_above: + return None + elif len(nxt) > len(groups): nxt = [[x] for g in nxt for x in g] groups = nxt if single: @@ -248,7 +275,7 @@ def narrowed(self): span = an.scal_rows.T.copy() if an.scal_rows.shape[0] else np.zeros((nz, 0), dtype=np.int64) out, tried = [], set() for i, (v, anchor) in enumerate(cands): - if len(out) >= len(self.residual) or expired(self.ctrl): + if len(out) >= len(self.residual): break v = np.asarray(v, dtype=np.int64) % P key = mulmod(v, invmod(int(v[np.nonzero(v)[0][0]]), P), P).tobytes() @@ -272,11 +299,38 @@ def narrowed(self): if e is not None and e.get("closed_form"): out.append(e) span = np.concatenate([span, np.asarray(v, dtype=np.int64).reshape(nz, 1)], axis=1) + 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.drop_spanned(span) return out + def _confirm(self, out, span): + """The closed forms of the narrow route checked together on every condition (verify_batch); one that fails + is left open and leaves the span of the closed directions.""" + 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) + 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) + 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"}) + continue + kept.append(back_substituted(an, e) if f is not None else e) + cols.append(n0 + i) + self.tlog(f"narrow: {len(kept)} of {len(out)} closed forms hold on every condition") + return kept, span[:, cols] + def statics(self): """Static subsystem fields that lie in the kernel, the residual reduced by them.""" an, nz, P = self.an, self.an.nz, PRIMES[0] @@ -506,8 +560,7 @@ def homotopy(self, interp): "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 - "timeout" if expired(self.ctrl) else None) + "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)): @@ -573,16 +626,14 @@ def open_entry(reason): 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} - if expired(self.ctrl): - return open_entry("reconstruction time budget (reconst_control(timeout=)) exceeded") 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, an.kbatch, self.rel_probe, + 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, - an.kbatch, bank, fast_only, aux_leaves=an.aux_leaves, degrees=degrees) + 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) @@ -632,8 +683,10 @@ def full_probe(self): 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) - return self.probe_groups(an.kbatch, self.sc["pivots"], self.probe_next, all_res, self.sc["ref"]) - return self.probe(an.kbatch, self.sc["pivots"], self.probe_next) + 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(self.kb, self.sc["pivots"], self.probe_next) def peeled(self): """Minimal-support directions read off in log coordinates.""" @@ -684,7 +737,7 @@ def zvals_of(pt): 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, an.kbatch, sc["nt_used"], self.ctrl) + 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 @@ -692,7 +745,7 @@ def zvals_of(pt): [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) and not expired(self.ctrl): + if any(nd > _LOG_FIRST for nd in needs): lg = logcoord_gauge(self.residual, an.scal_rows, PRIMES[0], an.nz, sc, self.zvals0) for ii in range(len(self.residual) if len(lg["anchors"]) == len(self.residual) else 0): if needs[ii] > _LOG_FIRST and lg["residue_fns"][ii] is not None: @@ -705,7 +758,7 @@ def zvals_of(pt): 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, an.kbatch, sc["pivots"], sc["nt_used"], len(PRIMES), self.ctrl) + 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 @@ -736,7 +789,7 @@ def rescue(gauge, log_coords=False): if len(gauge["anchors"]) != len(self.residual): return for ii in [i for i, e in enumerate(interp) if not e.get("closed_form")]: - if gauge["residue_fns"][ii] is None or expired(self.ctrl): + if gauge["residue_fns"][ii] is None: continue rec = self.one(gauge["anchors"][ii], gauge["residue_fns"][ii], log_coords=log_coords) self.attempt("log-coordinate gauge" if log_coords else "canonical gauge", rec) @@ -801,8 +854,8 @@ def run(self): 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(an.kbatch, self.sc["pivots"], self.probe_next, ms_res, - self.sc["ref"]) + 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 "")) diff --git a/src/symident/detection/observability/select.py b/src/symident/detection/observability/select.py new file mode 100644 index 0000000..93d28bb --- /dev/null +++ b/src/symident/detection/observability/select.py @@ -0,0 +1,377 @@ +"""The conditions that change the rank: chosen at a random point, with the directions proven on the others.""" + +from fractions import Fraction + +import numpy as np +import sympy as spy + +from ... import _core, session, state +from ...errors import SYMPY_FAILS, swallow, sympy_fail +from ...gfp import PRIMES, random_point +from ...par import process_map +from ...sym.parse import model_sympify +from ...sym.shared import kernel_tapes +from ..closedform import eval_modq +from ..conditions import scaling_component +from ..fields import exact_direction, exact_scaling_set, field_setup, lie_reach_max, restricted_setup +from .context import ints, ok, tape_fields + +# conditions below which every condition is analyzed +MIN_CONDITIONS = 24 +# rounds of conditions added where a direction fails on a condition left out +_ROUNDS = 3 +# conditions of a direction proven one at a time before the rest of them are added +_SINGLE = 16 +# directions past which the lifts run in forked workers +_PAR_LIFTS = 16 + + +def resting(multi, implicit_steady_state): + """Whether every condition starts at rest (equilibrate).""" + return bool(implicit_steady_state and multi.get("joint_steady_state")) + + +def eligible(multi, n_gaps, implicit_steady_state): + """Whether the conditions are chosen before the analysis: many conditions of one segment each, without unknown + inputs or recast atoms, each with the Lie orders at which the coordinates reach the output; at rest without + conserved totals and without leaves of non-rational terms.""" + tapes = multi.get("tapes") or [] + if len(tapes) < MIN_CONDITIONS or state.get("inner") or state.env("NOSELECT") or n_gaps: + 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")): + return False + 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) + + +def _reach(t): + """The coordinates that reach the output of the tape `t` at some Lie order.""" + return np.asarray(t["lie_reach"], dtype=np.int64) >= 0 + + +def taking_order(tapes): + """(order, first): the conditions one of each structure in turn, a structure being the set of coordinates that + reach the output; `first` marks the first condition in the order that reaches a coordinate.""" + groups = {} + for i, t in enumerate(tapes): + groups.setdefault(_reach(t).tobytes(), []).append(i) + lists = list(groups.values()) + order = [g[k] for k in range(max(len(g) for g in lists)) for g in lists if k < len(g)] + first = np.zeros(len(tapes), dtype=np.int64) + seen = np.zeros(len(tapes[0]["lie_reach"]), dtype=bool) + for i in order: + r = _reach(tapes[i]) + if np.any(r & ~seen): + first[i] = 1 + seen |= r + return order, first, len(lists) + + +def choose(multi, cores, nt=None, kept=()): + """The conditions whose rows at a random point raise the rank of the rows of the conditions before them, and the + first reader of each coordinate (sym_obs_cover), the conditions `kept` first; None where the kernel fails at + every point tried.""" + tapes = multi["tapes"] + order, first, n_struct = taking_order(tapes) + if kept: + order = list(kept) + [c for c in order if c not in kept] + first[list(kept)] = 1 + memo = {} + kt = kernel_tapes([tape_fields(t, memo) for t in tapes]) + nz = len(multi["z_slots"]) + 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) + if ok(r): + return {"kept": sorted(ints(r["conditions"])), "rank": int(r["rank"]), "lie_order": nt, + "structures": n_struct, "taken": int(r["taken"])} + return None + + +def choose_resting(an, order, first, n_struct): + """choose() for conditions at rest, from the Analysis `an` of all of them: the rows of each condition on the + shared coordinates once the resting states of the condition, solved at the point itself, are eliminated; None + where a resting state is not solved.""" + sys, run = an.sys, an.run + if sys.equil_conds != list(range(len(run.tapes))): + return None + if sys.chained: + sys.unchain() + P = PRIMES[0] + nt = lie_reach_max(run.multi["tapes"]) + 2 + for k in range(4): + pt = random_point(run.n_leaves, seed=session.current().seed("condition selection", k) % (1 << 31)) + if sys.fwd_on: + pt = sys.fwd_seed(pt, P) + if pt is None: + continue + rows, owner = [], [] + for c in order: + sc0 = sys.solve_direct(pt, P, c) + if sc0 is None: + rows = None + break + loc = sys.cond_local(c, sys.cond_obs(c, sc0["ptc"], P, nt, 0), sc0, P, scale=len(sys.recast_rel) > 0) + if loc is None: + rows = None + break + Q = sys._project([loc], P, run.cores)[1] + for q in Q: + rows += [np.asarray(r, dtype=np.int64) for r in q] + owner += [c] * len(q) + if rows is None: + continue + nsh = len(sys.shared_idx) + gain = {} + rank = 0 + if rows: + r = _core.sym_independent_rows(np.vstack(rows).reshape(-1, nsh).astype(np.float64), P, run.cores) + rank = int(r["rank"]) + for i in ints(r["rows"]): + gain[owner[i]] = gain.get(owner[i], 0) + 1 + kept = sorted({c for c in order if gain.get(c) or first[c]}) + return {"kept": kept, "rank": rank, "lie_order": nt, "structures": n_struct, "taken": len(order)} + return None + + +def restrict(multi, kept): + """`multi` with the tapes of the conditions `kept`; the scaling groups of a shared tape are kept whole, so that an + exact scaling holds for every condition.""" + out = dict(multi, tapes=[multi["tapes"][i] for i in kept]) + if multi.get("scaling_groups") and not multi.get("scaling_tapes"): + pos = {c: j for j, c in enumerate(kept)} + out["scaling_groups"] = [g for g in ([pos[c] for c in grp if c in pos] for grp in multi["scaling_groups"]) if g] + return out + + +def _field(d): + """The generator {coordinate: component} of the closed form of `d`.""" + vec = {str(k): str(v) for k, v in d["vector"].items()} + if d.get("type") == "scaling": + vec = {k: scaling_component(w, k) for k, w in vec.items()} + return {k: v for k, v in vec.items() if v.strip() not in ("0", "")} + + +def _weights(d): + """The weights of `d` where it is a scaling, the component of each coordinate a rational multiple of it; None + otherwise.""" + try: + if d.get("type") == "scaling": + w = {k: Fraction(str(x)) for k, x in d["vector"].items()} + else: + w = {} + for k, x in d["vector"].items(): + q = spy.cancel(model_sympify(str(x)) / spy.Symbol(k)) + if not q.is_Rational: + return None + w[k] = Fraction(int(q.p), int(q.q)) + except (TypeError, ValueError, ZeroDivisionError, *SYMPY_FAILS): + return None + w = {k: x for k, x in w.items() if x != 0} + return w or None + + +def _proportional_scaling(d, ws, coords): + """Whether `d` is a scaling proportional to one of the exact scalings `ws` of the whole model on `coords`.""" + v = _weights(d) + if v is None: + return False + k0 = next(iter(v)) + for w in ws: + w = {k: Fraction(str(x)) for k, x in w.items() if k in coords and Fraction(str(x)) != 0} + if not w.get(k0): + continue + c = v[k0] / w[k0] + if set(v) == set(w) and all(v[k] == c * w[k] for k in v): + return True + return False + + +def _annihilated(multi, conds, fields, nt, cores): + """Per condition of `conds`, per field, whether the field annihilates every row of the condition up to Lie order + `nt` at a random point; None for a field that does not evaluate there.""" + znames = list(multi["znames"]) + leaves = list(multi["leaf_names"]) + P = PRIMES[1] + pt = random_point(int(multi["n_leaves"]), seed=session.current().seed("selection check") % (1 << 31)) + env = {nm: int(v) for nm, v in zip(leaves, pt)} + V = np.zeros((len(znames), len(fields)), dtype=np.int64) + col = {z: i for i, z in enumerate(znames)} + for j, f in enumerate(fields): + for k, e in f.items(): + x = eval_modq(e, env, P) + if x is None or k not in col: + return None + V[col[k], j] = x % P + 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) + out.append(None if not ok(o) else [bool(x) for x in np.atleast_1d(o["zero"])]) + return out + + +def cover(multi, result, kept, cores, rest=None): + """The directions of `result`, found on the conditions `kept`, on every other condition of `multi`. + + A direction is a symmetry of a condition whose output no coordinate of the support reaches, of every condition + where the direction is proportional to an exact scaling of the whole model, and where the lift of the closed form + is proven on the condition. + {"ok": True, "how"} where every direction holds on every condition; {"ok": False, "add"} with the conditions + where a direction is not shown; None where a direction has no closed form or no proof on `kept`. With `rest`, the + conditions start at rest, and `rest(conds, d)` proves the output identities of `d` at the resting states of the + conditions `conds` where a direction has no lift.""" + dropped = [c for c in range(len(multi["tapes"])) if c not in set(kept)] + how = {"support": 0, "scaling": 0, "lift": 0, "rest": 0} + dirs = result.get("non_identifiable") or [] + if int(result["rank"]) == int(result["dim"]) or not dropped: + return {"ok": True, "how": how} + if any(not d.get("vector") or not d.get("exact") for d in dirs): + return None + znames = list(multi["znames"]) + col = {z: i for i, z in enumerate(znames)} + fields = [_field(d) for d in dirs] + if any(not f or any(k not in col for k in f) for f in fields): + return None + reach = np.vstack([_reach(multi["tapes"][c]) for c in dropped]) + fixed = [x for x in multi["leaf_names"] if x not in set(znames)] + ws = None + pending = {} + for j, (d, f) in enumerate(zip(dirs, fields)): + hit = np.any(reach[:, [col[k] for k in f]], axis=1) + how["support"] += int(np.sum(~hit)) + if not np.any(hit): + continue + if _weights(d) is not None: + if ws is None: + ws = exact_scaling_set(multi, fixed) + if _proportional_scaling(d, ws, set(znames) - set(multi.get("z_state_names") or ())): + how["scaling"] += int(np.sum(hit)) + continue + pending[j] = [dropped[i] for i in np.nonzero(hit)[0]] + if not pending: + return {"ok": True, "how": how} + lifted = _lifted(multi, pending, dirs, cores, rest is not None) + left = {j: cs for j, cs in pending.items() if j not in lifted} + how["lift"] += sum(len(cs) for j, cs in pending.items() if j in lifted) + if not left: + return {"ok": True, "how": how} + if rest is not None: + add = set() + for j, cs in left.items(): + bad = _bisect(cs, lambda part: _holds(rest(part, dirs[j]))) + how["rest"] += len(cs) - len(bad) + add |= set(bad) + return {"ok": not add, "add": sorted(add), "how": how} + # the conditions where a direction without a lift on all of them leaves the kernel at a random point; a lift per + # condition for the others + conds = sorted(set().union(*left.values())) + checked = _annihilated(multi, conds, [fields[j] for j in left], int(result.get("lie_order_used") or 0), cores) + if checked is None: + return None + add, single = set(), {} + for ci, c in enumerate(conds): + for k, j in enumerate(left): + if c not in left[j]: + continue + if checked[ci] is None or not checked[ci][k]: + add.add(c) + else: + single.setdefault(j, []).append(c) + for j, cs in single.items(): + for c in cs[:_SINGLE]: + if _lifted(multi, {j: [c]}, dirs, cores): + how["lift"] += 1 + else: + add.add(c) + add |= set(cs[_SINGLE:]) + if add: + return {"ok": False, "add": sorted(add), "how": how} + return {"ok": True, "how": how} + + +def _holds(out): + """Whether a proof result is a success.""" + return isinstance(out, dict) and out.get("ok") is True + + +def _bisect(conds, proven, cap=_SINGLE): + """The conditions of `conds` where `proven(part)` fails on the singleton, by halving the parts that fail; past + `cap` failing parts, all conditions of the parts left.""" + bad, todo = [], [list(conds)] + while todo: + part = todo.pop() + if proven(part): + continue + if len(part) == 1: + bad += part + continue + if len(todo) + len(bad) >= cap: + bad += part + continue + todo += [part[:len(part) // 2], part[len(part) // 2:]] + return bad + + +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: + return out + sub = dict(multi, tapes=[multi["tapes"][c] for c in conds]) + pos = {c: i for i, c in enumerate(conds)} + try: + setup = field_setup(sub, [[i] for i in range(len(conds))], cores, fields=[{}]) + except Exception as exc: + swallow(exc, "selection proof") + return out + try: + light = restricted_setup(setup, [[i] for i in range(len(conds))], at_rest) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return out + + 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 [] + for vec in proven + representatives(d): + try: + ex = exact_direction(light, vec, chains, at_rest, known=known) + except SYMPY_FAILS as exc: + sympy_fail(exc) + continue + if ex.get("ok") is True: + return ex["fields"] + return None + + known, todo = [], list(pending) + # a pass over many directions runs in forked workers with the fields proven before it + if len(todo) >= _PAR_LIFTS and cores > 1: + got = process_map(lambda j: attempt(j, []), todo, cores, on_error=lambda j: None) + for j, f in zip(todo, got): + if f is not None: + out.add(j) + known.append(f) + todo = [j for j in todo if j not in out] + for j in todo: + f = attempt(j, known) + if f is not None: + out.add(j) + known.append(f) + return out diff --git a/src/symident/detection/perprime.py b/src/symident/detection/perprime.py index e29b8ad..c4412af 100644 --- a/src/symident/detection/perprime.py +++ b/src/symident/detection/perprime.py @@ -5,7 +5,7 @@ from .. import _core from ..gfp import PRIMES, invmod, mono_table, mulmod, null_residues, rat_recon from ..rexpr import sym_sort -from .closedform import expired, poly_string, simplify +from .closedform import poly_string, simplify from .relevance import direction_relevance from .sparse import _pivots_eq @@ -95,7 +95,6 @@ def _fallback(pool_next, znames, base_nv, reason): "type": "general", "closed_form": False, "reason": reason}} -_TIMEOUT = "reconstruction time budget (reconst_control(timeout=)) exceeded" def _lift_const(vals, prs): @@ -122,8 +121,6 @@ def nv(rp, p): support_cols = [support_cols[i] for i in keep] rel_by_entry = [rel_by_entry[i] for i in keep] relevant = sorted({x for r in rel_by_entry for x in r}) - if expired(ctrl): - return _fallback(pool_next, znames, base_nv, _TIMEOUT) def ex(v): return [x for x in v if x not in aux] @@ -167,8 +164,6 @@ def const_entry(col): def ensure_prime(j, need): p = PRIMES[j] while bank_u[j].shape[0] < need and not dead_p[j]: - if expired(ctrl): - break have = bank_u[j].shape[0] chunk = max(1, min(need - have + 4, 128)) uv = [] @@ -209,8 +204,6 @@ def ensure_prime(j, need): cols_i = [relevant.index(r) for r in reli] fitted = None for degree in range(ctrl["degree_cap"] + 1): - if expired(ctrl): - return _fallback(box["pool_next"], znames, base_nv, _TIMEOUT) mons = mono_table(len(reli), degree) need = 2 * mons.shape[0] - 1 + ctrl["sample_slack"] if need > ctrl["perprime_cap"]: diff --git a/src/symident/detection/rank.py b/src/symident/detection/rank.py index 66f23bd..b36b29f 100644 --- a/src/symident/detection/rank.py +++ b/src/symident/detection/rank.py @@ -29,9 +29,11 @@ def _next_order(rk, nt, nt_end, need, cols): 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): + 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.""" + `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.""" if rank_cap is None: rank_cap = nz block_call = block_call or [] @@ -60,8 +62,9 @@ def saturate_certify(kcall, n_leaves, nz, max_m=0, *, warm, set_caps, probe_bloc else: need_used = min(plateau_need, budget + 1) - def scan_nt(call1, point, Mtot, frm, need, label, lo0=0, prof1=None): + def scan_nt(call1, point, Mtot, frm, need, label, lo0=0, prof1=None, rel=0.0): lo0 = int(lo0) + need0 = need if prof1 is not None and Mtot == 0 and not _ok(prof1(point, P, 1)): # a chain with a moving boundary has no profile; the orders are scanned prof1 = None @@ -81,6 +84,10 @@ def scan_nt(call1, point, Mtot, frm, need, label, lo0=0, prof1=None): flat += 1 else: grew = Nt + if rel: + # a plateau of consecutive orders, growing with the order the rank last rose at + flat = 0 + need = max(need0, int(rel * grew)) if rk[Nt] >= nz or (flat >= need and Nt >= 2) or Nt > nz + 1 + lo0: stop = True break @@ -179,7 +186,9 @@ def saturate_nt(point, Mtot, from_orders=None): if point is None: return None if not per_block: - sb = scan_nt(kcall, point, Mtot, 1, need_used, "stacked", nt_min) + # 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) if sb is not None: sb["point"] = point return sb diff --git a/src/symident/detection/rationalize.py b/src/symident/detection/rationalize.py index 12c062f..09740e2 100644 --- a/src/symident/detection/rationalize.py +++ b/src/symident/detection/rationalize.py @@ -90,6 +90,91 @@ def _injective_forms(e): return out +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)] + + +def _constant_states(parts, coords): + """Substitutes, per segment, the value of a state without dynamics that a transcendental term reads and that + starts at a number and is set to numbers by the events: within a segment the state is that number.""" + out = [] + for part in parts: + segs = part["segments"] + f0 = segs[0]["f"] + ic = segs[0].get("ic") or {} + inside = set() + for seg in segs: + for e in list(seg["f"].values()) + list(seg["g"].values()): + for a in _transcendental(e): + inside |= {str(z) for z in a.free_symbols} + for x in [x for x in f0 if x in inside and x not in coords]: + if any(seg["f"][x] != 0 for seg in segs) or ic.get(x) is None or not ic[x].is_number: + continue + vals, cur = [], ic[x] + for j, seg in enumerate(segs): + for ev in seg.get("events") or [] if j else []: + if ev["var"] != x: + continue + v = ev["value"] + cur = v if ev["method"] == "replace" else cur + v if ev["method"] == "add" else cur * v + vals.append(cur) + if not all(v.is_number and v.is_real for v in vals): + continue + X = spy.Symbol(x) + for seg, v in zip(segs, vals): + seg["f"] = {z: (e.xreplace({X: v}) if z != x else e) for z, e in seg["f"].items()} + seg["g"] = {y: e.xreplace({X: v}) for y, e in seg["g"].items()} + out.append(x) + return out + + +def _reciprocal_log_params(exprs, cs): + """{theta: g} of the coordinates that enter only through exp(c/theta) with rational c, g the positive rational + gcd of these c: X = exp(g/theta) then enters with integer powers.""" + cand, bad = {}, set() + for e in exprs: + for at in e.atoms(spy.exp): + terms = spy.expand(at.args[0]).as_coefficients_dict() + for t, c in terms.items(): + th = 1 / t if t.is_Pow and t.exp == -1 and t.base in cs else None + if th is None or not c.is_Rational or len(terms) != 1: + bad |= at.args[0].free_symbols + continue + cand.setdefault(th, []).append(abs(c)) + out = {} + for th, cs_ in cand.items(): + if th in bad: + continue + num = spy.igcd(*[c.p for c in cs_]) if len(cs_) > 1 else cs_[0].p + out[th] = spy.Rational(num, spy.ilcm(*[c.q for c in cs_]) if len(cs_) > 1 else cs_[0].q) + # a coordinate read outside these terms stays + while out: + sub = _reciprocal_sub({th: (spy.Dummy(), g) for th, g in out.items()}) + left = set().union(*[sub(e).free_symbols for e in exprs]) + drop = [th for th in out if th in left] + if not drop: + break + for th in drop: + del out[th] + return out + + +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() + 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) + + 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 @@ -102,6 +187,11 @@ def rationalize(parts, coords, states): for d, k in _strings(parts): orig[(id(d), k)] = str(d[k]) 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"}) 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} @@ -118,6 +208,18 @@ def rationalize(parts, coords, states): 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: + sub = _reciprocal_sub({t: (t, g) for t, g in recip.items()}) + for d, k in _strings(parts): + d[k] = sub(d[k]) + 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}"}) # observables under an injective function: the function goes seen = {} for part in parts: @@ -167,12 +269,16 @@ def rationalize(parts, coords, states): for a, E in rates.items(): seg["f"][str(E)] = a * E if j == 0 and seg.get("ic") is not None: - free = any(v is None for v in seg["ic"].values()) + # the jets of an unknown input start free in a condition with a given start + free = any(v is None for k, v in seg["ic"].items() if k not in set(seg.get("inputs") or ())) 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}"}) + # 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: @@ -186,19 +292,27 @@ def rationalize(parts, coords, states): def to_given(e, logs): """An expression in the coordinates of the fiber, X = b^(theta/L) for the log coordinates, in theta.""" - sub = {spy.Symbol(t): b ** (spy.Symbol(t) / L) for t, (b, L) in logs.items()} + sub = {spy.Symbol(t): _fiber_coordinate(t, spec) for t, spec in logs.items()} return spy.powsimp(spy.sympify(e).xreplace(sub)) +def _fiber_coordinate(t, spec): + """X in the given coordinate t: b^(t/L), or exp(g/t) for a reciprocal one.""" + t = spy.Symbol(t) + return spy.exp(spec[1] / t) if len(spec) > 2 else spec[0] ** (t / spec[1]) + + def map_to_given(sig, logs): """{coordinate: image} of a map sigma of the fiber in the given coordinates: theta' = L log_b(sigma(X)).""" out = {} for s, e in sig.items(): img = to_given(e, logs) if str(s) in logs: - b, L = logs[str(s)] + b, L = logs[str(s)][:2] 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 = spy.expand(spy.simplify(img)).xreplace({v: k for k, v in pos.items()}) out[s] = img return out @@ -210,14 +324,13 @@ def relation_to_given(r, logs): if "<" in r or ">" in r: op = "<" if "<" in r else ">" lhs, rhs = r.split(op, 1) - if lhs.strip() in logs: - b, L = logs[lhs.strip()] + 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"{_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)) - if len(terms) == 2 and e.free_symbols and all(str(s) in logs for s in e.free_symbols): + if len(terms) == 2 and e.free_symbols and all(len(logs.get(str(s), ())) == 2 for s in e.free_symbols): a, b = sorted(terms, key=lambda t: t.could_extract_minus_sign()) b = -b if spy.Mul.make_args(a)[0].is_negative is not True and spy.Mul.make_args(b)[0].is_negative is not True: @@ -236,6 +349,5 @@ def report_given(out, logs): s["domain_conditions"] = [relation_to_given(r, logs) for r in s.get("domain_conditions") or []] info = out["info"] info["fundamental_domain"] = [relation_to_given(r, logs) for r in info.get("fundamental_domain") or []] - info["fiber_coordinates"] = {t: (f"exp({t})" if b == spy.E else f"{_str(b)}^{t}") if L == 1 else - f"{_str(b)}^({t}/{L})" for t, (b, L) in logs.items()} + info["fiber_coordinates"] = {t: _str(_fiber_coordinate(t, spec)) for t, spec in logs.items()} return out diff --git a/src/symident/detection/relax.py b/src/symident/detection/relax.py new file mode 100644 index 0000000..b2829a2 --- /dev/null +++ b/src/symident/detection/relax.py @@ -0,0 +1,456 @@ +"""The relaxed model of discrete(): every non-rational term of the states as a new state that starts at a number, +times or plus a new coordinate, the value of the term at the start (docs/method/global.rst, "Rational form of the +fiber").""" + +import random + +import sympy as spy + +from ..sym.domain import is_positive +from ..sym.parse import _RPrinter, model_sympify +from .startpow import leading, power_exponent + + +def _str(e): + return _RPrinter().doprint(e).replace("**", "^") + + +def _non_rational(a): + return isinstance(a, (spy.exp, spy.log)) or (a.is_Pow and not a.exp.is_Integer) + + +def _innermost(exprs): + """The non-rational subterms whose own arguments are rational, in a fixed order.""" + out = {} + for e in exprs: + for a in spy.postorder_traversal(e): + if _non_rational(a) and not any(_non_rational(b) for b in spy.preorder_traversal(a) if b is not a): + out.setdefault(a, None) + return sorted(out, key=spy.default_sort_key) + + +def _fresh(stem, taken): + k = 1 + while f"{stem}{k}" in taken: + k += 1 + taken.add(f"{stem}{k}") + return spy.Symbol(f"{stem}{k}") + + +def _monotone_in(w, c): + """Whether the value `w`, b^mu, exp(u) or log(b), is strictly monotone in the positive coordinate c with the + other coordinates held: mu free of c and b = c^(+-1) times a factor free of c, or u = a*c^(+-1) + d with a, d + free of c.""" + if isinstance(w, spy.log): + w = w.args[0] ** spy.Integer(2) + if isinstance(w, spy.exp): + u = spy.expand(w.args[0]) + for v in (c, 1 / c): + a = u.coeff(v) + if a != 0 and not a.has(c) and not (u - a * v).has(c): + return True + return False + if not w.is_Pow or w.exp.has(c): + return False + rest = spy.cancel(w.base / c) + if not rest.has(c): + return True + return not spy.cancel(w.base * c).has(c) + + +def _same_leaf(leaves, value): + """W^k of the leaf whose value is `value` or, for an exponential, an integer power k of it; else None.""" + for lf in leaves: + v, W = lf["value"], spy.Symbol(lf["name"]) + 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 + elif v == value: + return W + return None + + +def _log_states(f, g, pos): + """{x: (R, k)} of the positive states x that the model reads only through log(x), through the factor x of + f_x = x*R(log x, ...) and through observables x^k with an integer k: L = log x then solves L' = R.""" + out = {} + for x, e in f.items(): + if pos is not True and str(x) not in pos: + continue + L = spy.Dummy("L") + 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] + if any(v.has(x) for v in rest): + continue + out[x] = R + return out + + +def _start_power(x, al, B, f, g, tr, starts, states, ins, leaves, rewrites, taken, positive): + """(f, g, tr) with B = x^alpha of a state x at 0 as Z N, N = (x/c_x)^alpha and Z = c_x^alpha, c_x the leading + coefficient of x. Z goes where it cancels against a leaf c_x^(q alpha); else on the slice Z = 1 of the scaling + of Z and the leaves b^(q alpha) that keeps the model, each such leaf then (b/c_x)^(q alpha); else Z is a leaf + (docs/method/global.rst, "Rational form of the fiber").""" + f0 = {str(s): v.xreplace({B: spy.Integer(0)}) for s, v in f.items()} + ic = {str(s): starts.get(s, s) for s in f} + # a known input is a chain of jets with free starts: the leading coefficient must not read them + jsyms = set() + for u in sorted(ins, key=str): + names = [str(_fresh(f"si_j{u}_", taken)) for _ in range(12)] + f0[str(u)] = spy.Symbol(names[0]) + for a_, b_ in zip([str(u)] + names, names + [None]): + if b_ is None: + f0[a_] = spy.Integer(0) + ic[a_] = _fresh(f"si_j{a_}0_", taken) + jsyms.add(ic[a_]) + for a_, b_ in zip(names, names[1:]): + f0[a_] = spy.Symbol(b_) + k, c = leading(f0, ic, x, al) + 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") + Zs, Nn, lam = spy.Dummy("Z"), spy.Dummy("N"), spy.Dummy("lam", positive=True) + + def power_of(lf): + # (b, q) of a leaf b^(q*alpha) of the coordinates + v = lf["value"] + if lf["kind"] != "constant" or not v.is_Pow: + 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}} + + vals = {k_: v.xreplace(sub) for k_, v in exprs.items()} + # Z cancels in an expression where the cancelled form is free of it + vals = {k_: spy.cancel(v) if v.has(Zs) and not spy.cancel(v).has(Zs) else v for k_, v in vals.items()} + moved = {} + if any(v.has(Zs) for v in vals.values()): + # the scaling Z -> lam Z, b^(q alpha) -> lam^q b^(q alpha) of the leaves left + for lf in leaves: + bq = power_of(lf) + if bq is not None and spy.Symbol(lf["name"]) not in sub: + moved[spy.Symbol(lf["name"])] = (lf, bq) + scale = {Zs: lam * Zs, **{P: lam ** bq[1] * P for P, (_, bq) in moved.items()}} + if moved and all(spy.cancel(v.xreplace(scale) - v) == 0 for v in vals.values()): + for lf, (b, q) in moved.values(): + lf["value"] = spy.Pow(spy.cancel(b / c), q * al) + vals = {k_: v.xreplace({Zs: spy.Integer(1)}) for k_, v in vals.items()} + else: + moved = {} + 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) + 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} + for lf in leaves: + if lf["kind"] == "constant" and lf["value"] == 1: + gone.add(spy.Symbol(lf["name"])) + vals = {k_: v.xreplace({spy.Symbol(lf["name"]): spy.Integer(1)}) for k_, v in vals.items()} + leaves[:] = [lf for lf in leaves if spy.Symbol(lf["name"]) not in gone] + 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)}) + return f, g, tr + + +def terms_of_states(odes, observables): + """Whether a non-rational term of the model reads a state.""" + states = {spy.Symbol(x) for x in odes} + exprs = [model_sympify(str(v)) for v in list(odes.values()) + list(dict(observables).values())] + return any(a.free_symbols & states for e in exprs for a in spy.preorder_traversal(e) if _non_rational(a)) + + +def relax(odes, observables, trafo, coords, inputs=(), positive=True): + """The relaxed model as {"odes", "observables", "trafo", "leaves", "dropped", "positive", "rewrites"}. + + A term phi(psi) of the states (exp, log, a power with a non-integer exponent) is W*nu for exp and powers, W + nu + for log, with nu a new state that starts at 1 (0 for log), so that nu = exp(psi - psi0), (b/b0)^mu or + log(psi/psi0), and W = phi(psi0) a new coordinate. A term of the coordinates alone is a new coordinate P. A + coordinate that no equation reads afterwards and that one P or W determines on the positive reals is dropped. A + known input inside a term becomes a state with a known start and a new known input as rate. A ValueError names + a term that cannot be rewritten.""" + taken = {str(s) for s in coords} | set(odes) | set(observables) | set(inputs) + f = {spy.Symbol(x): model_sympify(v) for x, v in odes.items()} + g = {y: model_sympify(v) for y, v in observables.items()} + tr = {spy.Symbol(k): model_sympify(v) for k, v in (trafo or {}).items()} + for e in list(f.values()) + list(g.values()) + list(tr.values()): + taken |= {str(s) for s in e.free_symbols} + states = set(f) + ins = {spy.Symbol(u) for u in inputs} + time = spy.Symbol("time") + starts = {x: tr.get(x, x) for x in f} + params = {s: v for s, v in tr.items() if s not in states} + leaves, rewrites = [], [] + new_inputs, known = [], [] + cset, zpow = {spy.Symbol(c) for c in coords}, {} + # a positive state read only through log(x) and the factor x is L = log x with a rational rate + pos = True if positive is True else {str(p) for p in (positive or ())} + logx = _log_states(f, g, pos) if positive is not None else {} + if logx: + Ls = {x: _fresh("si_L", taken) for x in logx} + to_L = {spy.log(x): L for x, L in Ls.items()} + 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)}) + 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 = {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()} + states = set(f) + while True: + exprs = list(f.values()) + list(g.values()) + atoms = _innermost(exprs) + if not atoms: + break + a = atoms[0] + if a.is_Pow and not a.exp.is_Integer and a.exp.free_symbols & (states | ins): + # a state in the exponent: b^e = exp(e*log(b)) + new = spy.exp(a.exp * spy.log(a.base)) + f = {x: v.xreplace({a: new}) for x, v in f.items()} + g = {y: v.xreplace({a: new}) for y, v in g.items()} + continue + pe = power_exponent(a.exp, cset - states) if a.is_Pow and a.base in states - ins else None + if pe is not None and starts.get(a.base) == 0: + # a free power of a state at 0: B = x^alpha in place, Z = c_x^alpha after the loop + key = (a.base, pe[2]) + if key not in zpow: + zpow[key] = _fresh("si_B", taken) + new = a.base ** pe[0] * zpow[key] ** pe[1] + f = {x: v.xreplace({a: new}) for x, v in f.items()} + 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") + 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 + du, u0 = _fresh(f"si_d{u}_", taken), _fresh(f"si_{u}0_", taken) + f[u], tr[u], starts[u] = du, u0, u0 + states.add(u) + ins.discard(u) + new_inputs.append(str(du)) + known.append(str(u0)) + if time in reads: + raise ValueError(f"{_str(a)} reads the time") + if not reads & states: + # a term that equals the start of a leaf is that leaf + new = _same_leaf(leaves, a.xreplace(params)) + if new is None: + new = _fresh("si_P", taken) + leaves.append({"name": str(new), "kind": "constant", "value": a.xreplace(params)}) + else: + arg = a.args[0] if not a.is_Pow else a.base + dpsi = sum((spy.diff(arg, x) * f[x] for x in states & arg.free_symbols), spy.Integer(0)) + nu = _fresh("si_nu", taken) + W = _fresh("si_W", taken) + psi0 = arg.xreplace(starts).xreplace(params) + if isinstance(a, spy.exp): + f[nu], kind, w0 = nu * dpsi, "exp", spy.exp(psi0) + new = W * nu + elif isinstance(a, spy.log): + f[nu], kind, w0 = dpsi / arg, "log", spy.log(psi0) + new = W + nu + else: + if psi0 == 0: + raise ValueError(f"the base of {_str(a)} starts at 0") + f[nu], kind, w0 = a.exp * nu * dpsi / arg, "power", psi0 ** a.exp.xreplace(params) + new = W * nu + tr[nu] = spy.Integer(0) if kind == "log" else spy.Integer(1) + starts[nu] = tr[nu] + states.add(nu) + same = _same_leaf(leaves, w0) + if w0.is_number and w0.is_Rational: + new = new.xreplace({W: w0}) + elif same is not None: + 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])}) + 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(): + f, g, tr = _start_power(x, al, B, f, g, tr, starts, states, ins, leaves, rewrites, taken, positive) + # a start that holds a term of the coordinates, a resting state, reads the leaf of that term + for x in [x for x in tr if x in states]: + while True: + at = _innermost([tr[x]]) + if not at: + break + a = at[0] + if a.free_symbols & states: + raise ValueError(f"the start {_str(tr[x])} of {x} reads a state") + new = _same_leaf(leaves, a.xreplace(params)) + if new is None: + new = _fresh("si_P", taken) + leaves.append({"name": str(new), "kind": "constant", "value": a.xreplace(params)}) + tr[x] = tr[x].xreplace({a: new}) + for e in list(f.values()) + list(g.values()): + bad = next((a for a in spy.preorder_traversal(e) if a.is_Function), None) + if bad is not None: + raise ValueError(f"{_str(bad)} is no exponential, logarithm or power") + # the starts of the leaves in the coordinates of the model: a nested term reads the start of an inner leaf + back = {} + for lf in leaves: + lf["value"] = lf["value"].xreplace(back) + back[spy.Symbol(lf["name"])] = lf["value"] + used = set() + for e in list(f.values()) + list(g.values()) + list(tr.values()): + used |= {str(s) for s in e.free_symbols} + used |= {str(x) for x in f if x not in tr} + dropped = {} + for c in coords: + 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)] + if not hit: + 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") + 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 = [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} + + +def scalings_keep_leaves(symmetries, leaves, dropped): + """None if each orbit of the continuous directions of the relaxed model meets the starts of the leaves in a + 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() + for s in symmetries: + sup = set(s.get("support") or []) + if not sup & names: + continue + gen = s.get("generator") or {} + if s.get("level") != "exact": + return f"the direction on {', '.join(sorted(sup))} that moves a new coordinate is not exact" + if s.get("type") == "scaling": + rows.append(s.get("weights") or {}) + elif all(model_sympify(str(gen.get(n, 0))).is_number for n in sup & names): + # a translation of the leaves it moves, with a log leaf in place of the log of a scaled one + rows.append({n: gen.get(n, 0) for n in sup & names}) + else: + return f"a direction on {', '.join(sorted(sup))} moves a new coordinate neither by a scaling nor by a shift" + if sup & every: + 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)): + 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: + hit = set(s.get("support") or []) & still + if hit: + return f"a direction moves {', '.join(sorted(hit))}, read by the start of a new coordinate no scaling moves" + return None + + +def keeps_leaves(sigma, leaves, dropped): + """Whether a map sigma of the relaxed coordinates is a map of the model: on the starts of the leaves, the image of + each leaf W is the start of W at the image of the coordinates, sigma(W)(omega) = omega_W(sigma(theta)).""" + sub = {spy.Symbol(k): model_sympify(v) for k, v in sigma.items()} + on = {spy.Symbol(lf["name"]): lf["value"] for lf in leaves if lf["absorbs"] is None} + absorbed = {spy.Symbol(c): spy.Symbol(P) for c, P in dropped.items()} + img = {s: e.xreplace(on) for s, e in sub.items() if s not in on} + for lf in leaves: + if lf["absorbs"] is not None: + continue + # a coordinate the start reads through a constant term P is moved where P is + if any(P in sub for c, P in absorbed.items() if c in lf["value"].free_symbols): + return False + W = spy.Symbol(lf["name"]) + lhs = sub.get(W, W).xreplace(on) + rhs = lf["value"].xreplace(img) + if spy.simplify(spy.powsimp(lhs - rhs, force=True)) != 0: + return False + return True + + +def independent_leaves(leaves, coords, seed=0): + """Whether the Jacobian of the exponents of the leaves (psi0 of exp(psi0), mu*log(b0) of b0^mu, and log(psi0)) + in the coordinates has full rank at a random rational point, the logarithms of the bases read as new symbols.""" + rng = random.Random(seed) + cs = [spy.Symbol(c) for c in coords] + lam = {} + rows = [] + for lf in leaves: + if lf["absorbs"] is not None: + continue + w = lf["value"] + if isinstance(w, spy.exp): + u = w.args[0] + elif isinstance(w, spy.log): + u = w + elif w.is_Pow: + L = lam.setdefault(w.base, spy.Dummy("L")) + u = w.exp * L + else: + return False + rows.append(u) + if not rows: + return True + + def d(u, c): + out = spy.diff(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]) + return J.rank() == len(rows) diff --git a/src/symident/detection/relevance.py b/src/symident/detection/relevance.py index 94f56fc..88a5587 100644 --- a/src/symident/detection/relevance.py +++ b/src/symident/detection/relevance.py @@ -6,7 +6,6 @@ from .. import state from ..gfp import PRIMES, null_residues -from .closedform import expired from .sparse import _ints, _pivots_eq @@ -70,8 +69,6 @@ def build_shared_bank(union, need_pts, point0, pool, pool_next, kbatch, pivots, while len(points) < need_pts and tries < 30 * need_pts: if not points and tries >= min(2 * need_pts, 48): break - if ctrl is not None and expired(ctrl): - return {"ok": False, "pool_next": pool_next} chunk = max(1, min(need_pts - len(points) + 5, 30 * need_pts - tries)) if not points: chunk = min(chunk, 24) diff --git a/src/symident/detection/restchart.py b/src/symident/detection/restchart.py new file mode 100644 index 0000000..5625414 --- /dev/null +++ b/src/symident/detection/restchart.py @@ -0,0 +1,149 @@ +"""The resting chart of discrete() under equilibrate: the resting value of each state inside a transcendental term is +a new coordinate, and one coordinate per such state is solved from the balances in exchange (docs/method/global.rst, +"Rational form of the fiber").""" + +import random + +import sympy as spy + +from ..sym.parse import model_sympify +from .relax import _fresh, _non_rational, _str + + +def _atoms(e): + return [a for a in spy.preorder_traversal(e) if _non_rational(a)] + + +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} + try: + v = spy.cancel(e.xreplace(pt)) + except ZeroDivisionError: + return False + return v.is_number and v != 0 and v.is_finite + + +def _solve_linear(eqs, unknowns, syms, rng): + """The unique solution of equations linear in `unknowns` with a coefficient matrix that is invertible at a + random point, else None.""" + try: + A, b = spy.linear_eq_to_matrix(eqs, unknowns) + except (spy.polys.polyerrors.PolynomialError, ValueError): + return None + if any(c.has(*unknowns) for c in list(A) + list(b)): + return None + if not _nonzero_at(A.det(method="berkowitz"), syms, rng): + return None + return dict(zip(unknowns, A.LUsolve(b))) + + +def _triangular(bal, unknowns): + """{state: value} solving balances one at a time where a balance is linear in the only unknown left, or None.""" + sol, todo = {}, dict(bal) + while todo: + hit = None + for x, e in todo.items(): + e = spy.together(e.xreplace(sol)) + left = [u for u in unknowns if u not in sol and e.has(u)] + if len(left) == 1 and spy.Poly(spy.fraction(e)[0], left[0]).degree() == 1: + hit = (x, left[0], spy.fraction(e)[0]) + break + if hit is None: + return None if set(unknowns) - set(sol) else sol + x, u, num = hit + P = spy.Poly(num, u) + sol[u] = -P.coeff_monomial(1) / P.coeff_monomial(u) + del todo[x] + return sol if not set(unknowns) - set(sol) else None + + +def rest_chart(odes, observables, inputs, coords, positive, fixed=(), events=(), trafo=None): + """{"odes", "observables", "trafo", "events", "exchanged", "rest", "positive", "coordinates"}: the model on the + resting set in the chart where the resting value R_x of each state x inside a transcendental term is a + coordinate and a coordinate p, entering a balance linearly, is the solution of the balances. A ValueError + says why no chart is found.""" + rng = random.Random("rest chart") + # the trafo of the parameters, a section of a reduction, is applied first + tp = {spy.Symbol(k): model_sympify(str(v)) for k, v in (trafo or {}).items()} + f = {spy.Symbol(x): model_sympify(str(v)).xreplace(tp) for x, v in odes.items()} + g = {y: model_sympify(str(v)).xreplace(tp) for y, v in observables.items()} + events = [{**ev, "value": _str(model_sympify(str(ev["value"])).xreplace(tp))} for ev in events or []] + ins = {spy.Symbol(u) for u in inputs} + cs = {spy.Symbol(c) for c in coords} - set(f) + rhs = {x: e.xreplace({u: spy.Integer(0) for u in ins}) for x, e in f.items()} + start = {x: spy.Integer(0) for x in f if x in ins} + for x, e in rhs.items(): + if x not in start and (str(x) in coords or e == 0): + start[x] = x + U = [x for x in f if x not in start] + H = sorted({s for x in U for a in _atoms(rhs[x]) for s in a.free_symbols & set(U)}, key=str) + if not H: + raise ValueError("no resting state lies inside a transcendental term") + taken = {str(s) for e in list(f.values()) + list(g.values()) for s in e.free_symbols} | {str(x) for x in f} + R = {x: _fresh(f"si_{x}_rest", taken) for x in H} + held = {**start, **R} + dummies = {} + + def flat(e): + # each transcendental term at rest is one symbol, with the term at the resting values + e = e.xreplace(held) + for a in sorted(_atoms(e), key=lambda a: -spy.count_ops(a)): + if a.free_symbols & set(U): + raise ValueError(f"{_str(a)} reads a resting state that no transcendental term determines") + 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") + rest = [x for x in U if x not in H] + syms = set(cs) | set(R.values()) | set(dummies.values()) + sol = _triangular({x: bal[x] for x in rest}, rest) + if sol is None: + raise ValueError("the balances of " + ", ".join(map(str, rest)) + " are not solved one by one") + hb = [spy.fraction(spy.together(bal[x].xreplace(sol)))[0] for x in H] + pos = None if positive is True else {str(p) for p in (positive or ())} + 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] + 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))): + 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] + if not c: + break + pick.append(c[0]) + if len(pick) == len(hb): + exch = _solve_linear(hb, pick, syms, rng) + 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") + 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 + if pos is not None: + new_pos = sorted((pos - {str(p) for p in exch}) | {str(R[x]) for x in H if str(x) in pos}) + evs = [] + for ev in events or []: + 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]} diff --git a/src/symident/detection/sparse.py b/src/symident/detection/sparse.py index c5862c2..310d937 100644 --- a/src/symident/detection/sparse.py +++ b/src/symident/detection/sparse.py @@ -6,7 +6,7 @@ from .. import _core from ..gfp import PRIMES, mono_table, null_residues, rat_recon, sieve -from .closedform import expired, mono_string, poly_string +from .closedform import mono_string, poly_string def _ints(x): @@ -81,8 +81,6 @@ def sparse_entry(reli, support_col, f, point0, leaf_names, nt_used, kcall, pivot cur = [[1] * nvar for _ in range(np_)] have = 0 while True: - if expired(ctrl): - return None target = min(16 if have == 0 else 2 * have, max_len) pl, pv, slot = [], [], [] for pj in range(np_): @@ -94,8 +92,6 @@ def sparse_entry(reli, support_col, f, point0, leaf_names, nt_used, kcall, pivot pv.append(p) slot.append((pj, k)) cur[pj] = [c * b % p for c, b in zip(cur[pj], bases)] - if expired(ctrl): - return None res = kbatch(pl, pv, nt_used) for i, pt in enumerate(pl): rp, p = res[i], pv[i] @@ -188,8 +184,6 @@ def from_ray(rv, p, d_n, d_d): deg = None ray0 = ray_samples([u0], [P1], ctrl["general_deg_num"] + ctrl["general_deg_den"] + 4)[0] for tot in range(2, ctrl["general_deg_num"] + ctrl["general_deg_den"] + 1): - if expired(ctrl): - return None for a in range(max(1, tot - ctrl["general_deg_den"]), min(tot - 1, ctrl["general_deg_num"]) + 1): b_d = tot - a if b_d < 1 or b_d > ctrl["general_deg_den"]: @@ -212,8 +206,6 @@ def from_ray(rv, p, d_n, d_d): cur = [[1] * nvar for _ in range(np_)] have = 0 while True: - if expired(ctrl): - return None target = min(16 if have == 0 else 2 * have, max_len) u_l, p_v, slot = [], [], [] for pj in range(np_): @@ -223,8 +215,6 @@ def from_ray(rv, p, d_n, d_d): p_v.append(p) slot.append((pj, k)) cur[pj] = [c * b % p for c, b in zip(cur[pj], bases)] - if expired(ctrl): - return None rays = ray_samples(u_l, p_v, d_n + d_d + 4) for i in range(len(u_l)): e = from_ray(rays[i], p_v[i], d_n, d_d) diff --git a/src/symident/detection/startpow.py b/src/symident/detection/startpow.py new file mode 100644 index 0000000..e04feb7 --- /dev/null +++ b/src/symident/detection/startpow.py @@ -0,0 +1,343 @@ +"""Free powers x^alpha of a state that starts at 0 in discrete(): the series in t and the layers S^m of +docs/method/global.rst, "Rational form of the fiber", with the normalized power N = (x / c_x)^alpha as a state +and the leading coefficient c_x of x a jet.""" + +import random +from fractions import Fraction + +import sympy as spy + +from ..sym.domain import is_positive + +# the highest order at which the leading coefficient of the base is searched +_ORDER_CAP = 12 + + +def power_exponent(e, cs): + """(c0, c, alpha) of an exponent c0 + c*alpha with integers c0 >= 0, c > 0 and a coordinate alpha, else None.""" + syms = e.free_symbols + if len(syms) != 1 or not syms <= set(cs): + return None + a = next(iter(syms)) + try: + P = spy.Poly(e, a) + except spy.PolynomialError: + return None + if P.degree() != 1: + return None + c, c0 = P.coeff_monomial(a), P.coeff_monomial(1) + if not (c.is_Integer and c > 0 and c0.is_Integer and c0 >= 0): + return None + return int(c0), int(c), a + + +def start_powers(exprs, zero_states, cs): + """{(x, alpha)} of the powers x^(c0 + c*alpha) in `exprs` with x among `zero_states`.""" + out = set() + for e in exprs: + for pw in spy.sympify(e).atoms(spy.Pow): + if pw.base in zero_states: + pe = power_exponent(pw.exp, cs) + if pe is not None: + out.add((pw.base, pe[2])) + return out + + +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 + pe = power_exponent(pw.exp, {alpha}) + 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) + + +def leading(f, ic, x, alpha): + """(k, c): the order k of the first Taylor coefficient of the state x that is not zero, and that coefficient + 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()}}]} + 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] + 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) + if k is None: + raise ValueError(f"{x} has no Taylor coefficient other than 0 up to order {_ORDER_CAP}") + # nonzero at a point is nonzero as a function; the coefficients below k vanish identically + F, *gens = spy.field(",".join(str(s) for s in syms), spy.QQ) if syms else (None,) + one = F.one if F is not None else Fraction(1) + ser._outputs(list(gens), k, 0, one, one * 0) + if any(v != 0 for v in ser.states0[ib][:k]): + raise ValueError(f"the Taylor coefficients of {x} below order {k} do not vanish identically") + c = ser.states0[ib][k] + return k, spy.sympify(c.as_expr() if hasattr(c, "as_expr") else spy.Rational(c.numerator, c.denominator)) + + +def definite(e, positive): + """Whether e, a rational function, has one sign on the domain: numerator and denominator positive or negative + by the declared signs.""" + num, den = spy.fraction(spy.cancel(spy.together(e))) + return all(is_positive(spy.expand(t), positive) or is_positive(spy.expand(-t), positive) for t in (num, den)) + + +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} + for part in parts: + segs = part["segments"] + seg = segs[0] + ic = seg.get("ic") + if len(segs) > 1 or ic is None or any(v is None for v in ic.values()): + continue + zero = {spy.Symbol(x) for x, v in ic.items() if spy.sympify(v) == 0} + found = start_powers(list(seg["f"].values()) + list(seg["g"].values()), zero, cs) + if len(found) != 1: + continue + ((x, alpha),) = found + try: + k, c = leading(seg["f"], ic, x, alpha) + except ValueError: + continue + N, Z = spy.Symbol(_fresh("si_N", taken)), spy.Dummy("Z") + cZ = {} + + def unit(e): + # c_x^(w*alpha) is Z^w + def repl(pw): + q = spy.cancel(pw.exp / alpha) + if not q.is_Integer: + return pw + if spy.cancel(pw.base - c) == 0: + 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(): + e = unit(substitute(v, x, alpha, N, Z)) + if c == 1: + e = e.xreplace({Z: spy.Integer(1)}) + if e.has(Z): + e = spy.cancel(e) + cZ[(d, key)] = e.has(Z) + new[(d, key)] = e + if any(cZ.values()): + continue + for (d, key), e in new.items(): + seg[d][key] = e + seg["f"][str(N)] = spy.Integer(0) + ic[str(N)] = spy.Integer(0) + part["spow"] = {"N": str(N), "state": str(x), "alpha": str(alpha), "k": k, "leading": str(c)} + return parts + + +def _fresh(stem, taken): + k = 1 + while f"{stem}{k}" in taken: + k += 1 + taken.add(f"{stem}{k}") + return f"{stem}{k}" + + +def _reads(polys, ns): + """The states that the polynomials `polys` read.""" + return {j for P in polys for m in P for j in range(ns) if m[j]} + + +def lam(n, m, k, alpha, one): + """lambda_{n,m} = n - k*m + k*m*alpha: the derivative of the term of index n and layer m.""" + return (n - k * m) * one + (k * m) * alpha + + +def valuations(F, G, ns, iN, known): + """(v, vy): per state and per observable a lower bound on n - k*m over the terms of layer m >= 1, None where + no such term exists: N has 0, a state one more than the least it reads, an observable the least it reads.""" + rd = [_reads(F[i], ns) for i in range(ns)] + v = [None] * ns + v[iN] = 0 + changed = True + while changed: + changed = False + for i in range(ns): + if i == iN or i in known: + continue + lo = [v[j] for j in rd[i] if v[j] is not None] + if lo and (v[i] is None or min(lo) + 1 < v[i]): + v[i] = min(lo) + 1 + changed = True + vy = [] + for M, E in G: + lo = [v[j] for j in _reads((M, E), ns) if v[j] is not None] + vy.append(min(lo) if lo else None) + return v, vy + + +def needs(F, G, ns, sp, orders, known): + """The highest index of each state that the outputs up to `orders` read: an observable reads the states at + the order of the observable, the equation of index n of a state reads the right-hand side at index n - 1, and + N reads the base at the same index.""" + need = [0] * ns + for (M, E), n in zip(G, orders): + for j in _reads((M, E), ns): + need[j] = max(need[j], n) + changed = True + while changed: + changed = False + for i in range(ns): + src = {sp["base"]} if i == sp["N"] else set() if i in known else _reads(F[i], ns) + lo = need[i] if i == sp["N"] else need[i] - 1 + for j in src: + if need[j] < lo: + need[j], changed = lo, True + return need + + +def layered_flow(F, xs, params, order, o, z, skip, sp, alpha): + """The series of the states of a part with a normalized power, xs[i][n] the layers of index n, from + 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} + Q = [o] + c = None + for n in range(order + 1): + if n == k: + c = xs[ib][k].c[0] + if c == 0: + return False + if n >= k: + j = n - k + while len(Q) <= j: + q = len(Q) + acc = sum((xs[ib][k + i] * (alpha * i + (i - q) * one) * Q[q - i] for i in range(1, q + 1)), z) + Q.append(acc / (q * c)) + xs[iN][n] = _Eps([zero] + Q[j].c[:-1]) + else: + xs[iN][n] = z + if n == order: + break + for i in dx: + N, D = F[i] + nser = _ser_poly(N, xs, params, n, o, z) + dser = _ser_poly(D, xs, params, n, o, z) + if _lead(dser[0]) == 0: + return False + rest = sum((dser[l_] * dx[i][n - l_] for l_ in range(1, n + 1)), z) + 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)]) + return True + + +def layered_equations(F, xs, params, need, o, z, skip, sp, alpha, Q, add_eq, add_sat, limit): + """The equations of the prolonged model of a part with a normalized power up to the index `need` of each state: + 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] + add_sat(c) + for q in range(1, len(Q)): + acc = sum((xs[ib][k + i] * (alpha * i + (i - q) * one) * Q[q - i] for i in range(1, q + 1)), z) + add_eq(Q[q] * (q * c) - acc) + for n in range(len(xs[iN])): + xs[iN][n] = _Eps([z.c[0]] + Q[n - k].c[:-1]) if k <= n < k + len(Q) else z + for i, (N, D) in enumerate(F): + if i in skip or i == iN: + continue + top = need[i] + nser = _ser_poly(N, xs, params, top - 1, o, z, limit) if top else [] + dser = _ser_poly(D, xs, params, top - 1, o, z, limit) if top else [] + dx = [_Eps([lam(n + 1, m, k, alpha, one) * xs[i][n + 1].c[m] for m in range(L)]) for n in range(top)] + for n in range(top): + add_eq(sum((dser[l_] * dx[n - l_] for l_ in range(0, n + 1)), z) - nser[n]) + add_sat(_ser_poly(D, xs, params, 0, o, z, limit)[0]) + + +def proof(series, pi, positive): + """{"premises", "k", "row", ...}: the conditions under which every point of the fiber in the domain has the + exponent alpha of the point (docs/method/global.rst, "Rational form of the fiber"), checked exactly: + 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] + k, ib = sp["k"], sp["base"] + premises = [] + out = {"premises": premises} + names = [str(s) for s in series.cs] + F, *gens = spy.field(",".join(names), spy.QQ) + val = dict(zip(series.cs, gens)) + alpha = val[series.cs[sp["alpha_index"]]] + params = [val[s] for s in series.params] + rows = [r for r, v in enumerate(sp["vy"]) if v is not None] + if not rows: + raise ValueError(f"no observable reads the power of {sp['state']}") + r = min(rows, key=lambda r: sp["vy"][r]) + n1 = sp["vy"][r] + k + order = max(n1, k) + one, zero = F.one, F.zero + o, z = _Eps([one, zero]), _Eps([zero, zero]) + kser = series._known_series(pi, order) + xs = [] + for i, (_, num, den) in enumerate(seg["x0"]): + if i in kser: + xs.append([o * c for c in kser[i]]) + continue + x0 = _eval(num, gens, zero) / _eval(den, gens, zero) + xs.append([o * x0] + [z] * order) + if not layered_flow(seg["F"], xs, params, order, o, z, set(kser), sp, alpha): + raise ValueError("the series of the model has a pole at the start") + c = xs[ib][k].c[0] + M, E = seg["G"][r] + mser = _ser_poly(M, xs, params, n1, o, z) + eser = _ser_poly(E, xs, params, n1, o, z) + y = [] + for n in range(n1 + 1): + 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)}) + 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") + return out + + +def _row(series, pi, r): + """The index among the labels of the series of observable r of the first segment of part pi.""" + i = 0 + for pj, part in enumerate(series.parts): + for seg in part["segs"]: + if pj == pi and seg is part["segs"][0]: + return i + r + i += len(seg["labels"]) + return r diff --git a/src/symident/detection/uinputs.py b/src/symident/detection/uinputs.py new file mode 100644 index 0000000..c90508b --- /dev/null +++ b/src/symident/detection/uinputs.py @@ -0,0 +1,276 @@ +"""Unknown inputs in the count of discrete symmetries: jet chains with free starts, unknowns of the fiber that are no +coordinates, and the verified count with them (docs/method/conditions.rst, "Unknown and known inputs").""" + +import math + +import sympy as spy + +from .. import session +from ..gfp import PRIMES +from ..rexpr import get_symbols +from ..sym.parse import model_sympify + + +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) + f, jets = _input_jets(f, unknown, length, taken) + of = {x: [w, k] for w, ns in jets.items() for k, x in enumerate(ns)} + return f, dict(ic, **{x: None for x in of}), of + + +def _chains(seg): + """{input: {jet symbol: order}} of the chains of the unknown inputs of a segment.""" + out = {} + for n, (w, k) in (seg.get("input_of") or {}).items(): + out.setdefault(w, {})[spy.Symbol(n)] = int(k) + return out + + +def relative_degrees(series, cap): + """Per observable row of the series {input: r}, r the least order whose Lie derivative of the observable reads a + jet of the input, by symbolic derivatives over Q up to `cap`; an input not read up to `cap` is left out. The + derivative of order r + m reads jets up to order m and the jet of order m with the coefficient of the input in + the derivative of order r, which is not zero.""" + have = getattr(series, "_reldeg", None) + if have is not None and have[0] >= cap: + return have[1] + out = [] + for part in series.raw_parts: + seg = part["segments"][0] + chains = _chains(seg) + F = {spy.Symbol(k): model_sympify(str(v)) for k, v in seg["f"].items()} + for h in seg["g"].values(): + e, r = spy.cancel(model_sympify(str(h))), {} + for k in range(cap + 1): + fs = e.free_symbols + for w, c in chains.items(): + if w not in r and fs & set(c): + r[w] = k + if len(r) == len(chains) or k == cap: + break + e = spy.cancel(sum((spy.diff(e, x) * F[x] for x in fs if x in F), spy.Integer(0))) + out.append(r) + series._reldeg = (cap, out) + return out + + +def unread_jets(series, orders): + """The (part, state) of the jets of unknown inputs above the orders that the output coefficients up to `orders` + read: the coefficient of order n of an observable of relative degree r reads the jets up to n - r.""" + rd = relative_degrees(series, max(orders)) + top = {} + for r, n in zip(rd, orders): + for w, k in r.items(): + top[w] = max(top.get(w, -1), int(n) - k) + out = set() + for pi, part in enumerate(series.raw_parts): + seg = part["segments"][0] + idx = {x: i for i, x in enumerate(seg["f"])} + for name, (w, k) in (seg.get("input_of") or {}).items(): + if int(k) > top.get(w, -1): + out.add((pi, idx[name])) + return out + + +def _rank_mod(rows, p): + """The rank of the integer matrix `rows` modulo p.""" + a = [list(r) for r in rows] + rank, ncol = 0, len(a[0]) if a else 0 + for c in range(ncol): + piv = next((i for i in range(rank, len(a)) if a[i][c] % p), None) + if piv is None: + continue + a[rank], a[piv] = a[piv], a[rank] + inv = pow(a[rank][c], -1, p) + a[rank] = [x * inv % p for x in a[rank]] + for i in range(len(a)): + if i != rank and a[i][c] % p: + f = a[i][c] + a[i] = [(x - f * y) % p for x, y in zip(a[i], a[rank])] + rank += 1 + return rank + + +def isolated(fib, p): + """(ok, jets): whether the output coefficients up to the orders of the fiber have a Jacobian in the coordinates and + 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] + n, q = len(series.cs), len(free) + rng = session.current().rng("input jets", tuple(series.coords)) + m = n + q + 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)}) + try: + ys = series._outputs(cv, fib.order, 0, _Dual(1, [0] * m, p), _Dual(0, [0] * m, p)) + except ZeroDivisionError: + ys = None + finally: + series.input_values = old + if ys is None: + return False, None + rows = [list(y[k][0].d) for y, top in zip(ys, fib.orders) for k in range(top + 1)] + return _rank_mod(rows, p) == m, q + + +def _degrees(fib): + """The total degrees in (theta, input jets, u) of the fiber equations, as discrete._fiber_degrees, with the drawn + 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 + zero = unread_jets(series, fib.orders) + series.input_values = {key: Deg.const(A, 0) if key in zero else Deg(A, 1) for key in series.inputs} + try: + outs = series._outputs([Deg(A, 1) for _ in series.cs], fib.order, 0, Deg.const(A, 1), Deg.const(A, 0)) + except ZeroDivisionError: + outs = None + finally: + series.input_values = old + if outs is None: + return None + vals = [[y[k][0] for k in range(n + 1)] for y, n in zip(outs, fib.orders)] + dq, nums = common([v for row in vals for v in row]) + it = iter(nums) + bnum = [[next(it) for _ in row] for row in vals] + degs = [_sparse_deg(P) for P in fib.static] + [1 + sum(_sparse_deg(f) for f in fib.sat)] + degs += [2 * max(_sparse_deg(_sparse(n)), _sparse_deg(_sparse(d))) for n, d in series.pins] + for (E, M), b, n in zip(fib.outs, bnum, fib.orders): + for k in range(n + 1): + terms = [_sparse_deg(E[l_][0]) + b[k - l_] for l_ in range(k + 1) if E[l_][0] and b[k - l_] is not None] + if M[k][0]: + terms.append(_sparse_deg(M[k][0]) + dq) + if terms: + degs.append(max(terms)) + return degs + + +def count_certificate(fib, k, out): + """discrete.count_certificate() for a model with unknown inputs: the jets of the inputs at the point drawn with + 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") + return out + degs = _degrees(fib) + if degs is None: + out["why"] = "the Taylor coefficients have a pole" + return out + D = math.prod(max(1, int(d)) for d in degs) + nu = len(fib.allnames) + 1 + out["bezout"] = D + deg = (nu + 2 * D) * D + bits = max(_MIN_BITS, math.ceil(math.log2(deg) - math.log2(_VERIFIED_AIM))) + if bits > _VERIFIED_BITS: + out["why"] = f"the point would need coordinates of {bits} bits for a bound below {_VERIFIED_AIM:g}" + 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} + 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} + try: + k2 = q_count(fib, pt) + finally: + series.input_values = old + out["count"] = k2 + out["input_jets"] = nread + if not k2: + out["why"] = f"no finite count over Q at the random integer point of {bits} bits" + return out + if k2 != k: + out["why"] = f"the count over Q at a random integer point is {k2}, not {k}" + return out + out["bound"] = 2.0 ** (math.log2(deg) - bits) + return out + + +def preserved(fib, sig, points=2, deeper=0): + """discrete.output_preserved() for a model with unknown inputs: at random rational points theta, the equations of + the fiber up to `deeper` orders higher, modulo a prime, with the coordinates at sigma(theta), have a solution in + 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) + for _ in range(points): + pt = {s: spy.Rational(rng.randint(1, 97), rng.randint(1, 13)) for s in fib.syms} + try: + img = [_modp_rational(sig.get(s, s).xreplace(pt), p) for s in fib.syms] + sysd = deep.system(pt, p, extra=[{((i, 1),): 1, (): (-c) % p} for i, c in enumerate(img)]) + except (ZeroDivisionError, TypeError): + return False + if sysd is None: + return False + for block in sysd["blocks"]: + if not _gb_count(block["names"], p, block["eqs"], 60.0): + return False + return True + + +def input_state_map(parts, sig, states): + """[map] of the states and the unknown inputs that proves sigma, or None: phi takes a state that starts at a + coordinate named like the state to the image of that coordinate and keeps the others, and psi, the value of each + input, is solved from F(phi(x), sigma(theta), psi) = Dphi(x) F(x, theta, w) and h(phi(x), sigma(theta), psi) = + 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] + of = seg.get("input_of") or {} + W = [spy.Symbol(n) for n, (w, k) in of.items() if int(k) == 0] + X = [spy.Symbol(x) for x in states if x in seg["f"]] + try: + F = {spy.Symbol(k): model_sympify(str(v)) for k, v in seg["f"].items()} + H = [model_sympify(str(h)) for h in seg["g"].values()] + ic = {spy.Symbol(k): model_sympify(str(v)) for k, v in seg["ic"].items() if v is not None} + high = {spy.Symbol(n) for n, (w, k) in of.items() if int(k) > 0} + if any(F[x].free_symbols & high for x in X) or any(h.free_symbols & high for h in H): + # 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} + 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] + eqs += [h.xreplace(img) - h for h in H] + eqs = [spy.numer(spy.together(e)) for e in eqs] + if any(e != 0 and spy.Poly(e, *psi).total_degree() > 1 for e in eqs): + return None + sol = spy.linsolve(eqs, psi) + if not sol or len(sol.args) != 1 or sol.args[0].free_symbols & set(psi): + return None + sub = dict(zip(psi, sol.args[0])) + 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: + return None + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + out = {str(x): str(e) for x, e in phi.items() if e != x} + out.update({str(w): str(spy.cancel(sub[d])) for w, d in zip(W, psi) if spy.cancel(sub[d] - w) != 0}) + return [out] diff --git a/src/symident/detection/verify.py b/src/symident/detection/verify.py index 986e8e2..ddfe632 100644 --- a/src/symident/detection/verify.py +++ b/src/symident/detection/verify.py @@ -65,12 +65,54 @@ def verify_in_nullspace(entry, f, znames, leaf_names, point0, nt_used, kcall, po return False +def verify_batch(entries, anchors, znames, leaf_names, n_point, nt_used, batch_fn, nz, tries=6, need=2): + """verify_in_nullspace of several closed forms at the same fresh seeded points, each point one pass of + `batch_fn(point, q, Nt, V)` over every condition for all of them: per entry True or False, None where an + entry does not evaluate on the leaves (checked alone).""" + 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())] + passed = {i: 0 for i in todo} + off = set() + for k in range(tries): + live = [i for i in todo if out[i] is None and i not in off] + if not live: + break + pt = uniform_point(n_point, q, session.current().seed("verify kernel batch", k)) + env = {nm: int(pt[j]) for j, nm in enumerate(leaf_names)} + V = np.zeros((nz, len(live)), dtype=np.int64) + for col, i in enumerate(live): + V[anchors[i], col] = 1 + for nm, ex in entries[i]["vector"].items(): + got = eval_modq(ex, env, q) + if got is None: + off.add(i) + break + V[znames.index(nm), col] = got % q + res = batch_fn(pt, q, int(nt_used), V) + if res is None: + continue + for col, i in enumerate(live): + if i in off: + continue + if not res[col]: + out[i] = False + continue + passed[i] += 1 + if passed[i] >= need: + out[i] = True + session.note("draws", k + 1) + for i in todo: + if out[i] is None and i not in off: + out[i] = False + return out + + def _in_nullspace_at(entry, f, znames, leaf_names, pt, nt_used, kcall, nz, dir_call, q, cols=None, env_fn=None): """The check of verify_in_nullspace() at one point: True, False, "partial" when only the entries it can evaluate pass, or None where the kernel does not exist.""" - rq = kcall(pt, q, int(nt_used)) - if not rq.get("ok"): - return None env = {nm: int(pt[i]) for i, nm in enumerate(leaf_names)} if env_fn is not None: # the states at the point are the resting states the kernel was taken at @@ -95,13 +137,17 @@ def _in_nullspace_at(entry, f, znames, leaf_names, pt, nt_used, kcall, nz, dir_c known[col] = False else: v[col] = got % q - free = _free_cols(rq, nz) - if not free: - return False + # with every entry known, the direction is in the kernel where it annihilates every row if dir_call is not None and known.all(): ok = dir_call(pt, q, int(nt_used), v) if ok is not None: return bool(ok) + rq = kcall(pt, q, int(nt_used)) + if not rq.get("ok"): + return None + free = _free_cols(rq, nz) + if not free: + return False basis = np.stack([null_residues(rq, fcol, q) for fcol in free]) % q if known.all() or all(known[c] for c in free): recon = np.zeros(nz, dtype=np.int64) diff --git a/src/symident/detection/work.py b/src/symident/detection/work.py new file mode 100644 index 0000000..2330e3c --- /dev/null +++ b/src/symident/detection/work.py @@ -0,0 +1,253 @@ +"""Work limits: every search and count stops at a cap on a number of steps, points, terms or unknowns, so that a +result is the same on every machine. Nothing in the package stops on a clock.""" + +import contextlib +import math +import os +import re +import subprocess +import threading + +# the address space of one call of msolve: past it the call fails instead of the process that waits for it +MSOLVE_MEMORY = 8 << 30 + + +class Meter: + """Units of work spent against a cap; `what` names the stage, `unit` the units. A meter made by share() spends + on the parent as well and is over where either is.""" + + def __init__(self, what, cap, unit, parent=None): + self.what, self.cap, self.unit, self.parent = what, cap, unit, parent + self.spent = 0 + + def spend(self, n=1): + """Adds n units; whether the meter is over the cap afterwards.""" + self.spent += n + if self.parent is not None: + self.parent.spend(n) + return self.over + + @property + def over(self): + return self.spent > self.cap or (self.parent is not None and self.parent.over) + + def share(self, what, cap, unit=None): + """A meter of at most `cap` units of this one.""" + return Meter(what, cap, unit or self.unit, self) + + def reason(self): + """The cap that ended the stage, as text.""" + m = self + while m.parent is not None and not m.spent > m.cap: + m = m.parent + return f"{m.what} reached the cap of {_num(m.cap)} {m.unit}" + + +def unlimited(what="", unit="units"): + return Meter(what, math.inf, unit) + + +def _num(x): + return "infinitely many" if x == math.inf else f"{int(x):,}" if float(x).is_integer() else f"{x:g}" + + +@contextlib.contextmanager +def msolve_memory(gib): + """The address space of one call of msolve within the block, in GiB; None takes the switch MSOLVE_GB, else keeps + the current one.""" + global MSOLVE_MEMORY + 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)) + try: + yield + finally: + MSOLVE_MEMORY = old + + +def _limiter(memory): + """A function that sets the address space `memory` in a child process before it runs the command, at most the + hard limit of this process; None where the platform has none.""" + try: + import resource + except ImportError: + return None + if not memory or not hasattr(resource, "RLIMIT_AS"): + return None + + def apply(): + try: + top = resource.getrlimit(resource.RLIMIT_AS)[1] + lim = int(memory) if top == resource.RLIM_INFINITY else min(int(memory), top) + resource.setrlimit(resource.RLIMIT_AS, (lim, lim)) + except (OSError, ValueError): + pass + return apply + + +def run(cmd, input=None, text=False, memory=None): + """subprocess.run(cmd, capture_output=True), with at most `memory` bytes of address space for the process.""" + return subprocess.run(cmd, input=input, capture_output=True, text=text, preexec_fn=_limiter(memory)) + + +# ---- the caps --------------------------------------------------------------------------------- + +# 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_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_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, + # terms of a polynomial of the elimination of the states + "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, + # 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, + # 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, + # 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, +} + + +@contextlib.contextmanager +def caps(**kw): + """The caps `kw` (keys of CAPS) within the block; None keeps a cap.""" + bad = sorted(set(kw) - set(CAPS)) + if bad: + raise KeyError(bad[0]) + old = dict(CAPS) + CAPS.update({k: v for k, v in kw.items() if v is not None}) + try: + yield + finally: + CAPS.clear() + CAPS.update(old) + + +_LOCAL = threading.local() + + +def cap(name): + """The cap `name` in force in this thread: an override of local_caps(), else CAPS.""" + return getattr(_LOCAL, "caps", {}).get(name, CAPS[name]) + + +@contextlib.contextmanager +def local_caps(**kw): + """The caps `kw` within the block in this thread only, as threads of one count share CAPS.""" + old = dict(getattr(_LOCAL, "caps", {})) + _LOCAL.caps = {**old, **kw} + try: + yield + finally: + _LOCAL.caps = old + + +@contextlib.contextmanager +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")}): + yield + + +def msolve_size(names, eqs): + """(unknowns, terms) of the msolve input `eqs` (texts) in `names`.""" + terms = 0 + for e in eqs: + s = str(e).replace(" ", "") + terms += 1 + sum(1 for i, ch in enumerate(s) if ch in "+-" and i and s[i - 1] not in "^*eE") + return len(names), terms + + +def msolve_too_large(names, eqs): + """Why the system `eqs` in `names` is past the caps of msolve on the size of the input, None where it is within + them.""" + n, t = msolve_size(names, eqs) + nu, nt = cap("msolve_unknowns"), cap("msolve_terms") + if n > nu: + return f"a system of {n} unknowns, past the cap of {nu} unknowns of msolve" + if t > nt: + return f"a system of {t:,} terms, past the cap of {nt:,} terms of msolve" + return None + + +# the matrix of a round of F4 in the output of msolve -v 2, rows x columns and density, written before the linear +# algebra of the round +_MATRIX = re.compile(rb"(\d+) x (\d+)\s+([\d.]+)%") + + +def run_msolve(cmd, text=True): + """work.run() of an msolve command, with the address space MSOLVE_MEMORY. The nonzero entries of the matrices of + the F4 rounds (rows times columns times density, from the output of msolve) count against the cap + msolve_entries: the process ends at the first matrix past it, before the linear algebra of that matrix, and the + result has returncode 1 and `capped` the reason. The count of a finished call decides as well, so the outcome + does not depend on when the output is read.""" + most = cap("msolve_entries") + proc = subprocess.Popen(list(cmd) + ["-v", "2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, + preexec_fn=_limiter(MSOLVE_MEMORY)) + out = [] + reader = threading.Thread(target=lambda: out.append(proc.stdout.read())) + reader.start() + total, buf, done = 0, b"", 0 + fd = proc.stderr.fileno() + while True: + chunk = os.read(fd, 1 << 16) + if not chunk: + break + buf += chunk + for m in _MATRIX.finditer(buf, done): + total += int(m.group(1)) * int(m.group(2)) * float(m.group(3)) / 100 + done = m.end() + if total > most: + proc.kill() + break + proc.stderr.close() + proc.wait() + reader.join() + stdout, stderr = out[0] if out else b"", buf + if text: + stdout, stderr = stdout.decode(errors="replace"), stderr.decode(errors="replace") + if total > most: + r = subprocess.CompletedProcess(cmd, 1, stdout, stderr) + r.capped = f"msolve reached the cap msolve_entries of {int(most):,} nonzero entries of the matrices of F4" + else: + r = subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr) + r.capped = None + r.entries = total + return r + + +# ---- the work counter of the searches over GF(p) ----------------------------------------------- + +# entries of the matrices whose kernels or echelon forms the searches compute, since the start of the process +_TICKS = [0] + + +def ticks(): + """The entries of the matrices over GF(p) reduced so far in this process, the clock of the searches.""" + return _TICKS[0] + + +def tick(shape): + """Counts a matrix of the given shape, or a number of entries.""" + _TICKS[0] += int(shape[0]) * int(shape[1]) if isinstance(shape, tuple) else int(shape) diff --git a/src/symident/install.py b/src/symident/install.py index 761a303..b8ad48f 100644 --- a/src/symident/install.py +++ b/src/symident/install.py @@ -44,7 +44,7 @@ def msolve_check(path): 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, timeout=60) + capture_output=True) except (OSError, subprocess.SubprocessError): return None if r.returncode != 0 or not os.path.exists(fo): @@ -54,7 +54,7 @@ def msolve_check(path): if not out.startswith("[0,[65521,2,3,") or "[36,0,65514,1]" not in out: return None try: - v = subprocess.run([path, "-V"], capture_output=True, text=True, timeout=30).stdout.strip() + v = subprocess.run([path, "-V"], capture_output=True, text=True).stdout.strip() except (OSError, subprocess.SubprocessError): v = "" return v or "unknown" diff --git a/src/symident/options.py b/src/symident/options.py index 1029788..224033f 100644 --- a/src/symident/options.py +++ b/src/symident/options.py @@ -1,13 +1,11 @@ """Settings of the observability engine.""" -import math - 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, timeout=math.inf, seed=0, exact_proof=True, + 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. @@ -16,7 +14,9 @@ def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse= relevance_cap : int Coordinates in one entry for the dense fit; wider entries use sparse interpolation. relevance_cap_dir : int - Coordinates in one direction; a wider one is reported by the support. + Coordinates in one direction; a wider one is reported by the support. The narrow route, which samples + the kernel on the support of the direction alone, bounds each entry only where the model has no event + gaps, resting states or unknown inputs. relevance_cap_sparse : int Coordinates in one entry for the sparse fit; a wider entry is reported by the support of the direction. degree_cap : int @@ -49,9 +49,6 @@ def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse= Whether directions still open are fitted along parameter lines as a last route. homotopy_degree : int Total degree bound of the entries fitted by the homotopy route. - timeout : float - Time limit of the reconstruction in seconds; unfinished directions are reported - by their support. seed : int Seed of the random choices: sample points and the order of trials. The same seed and model give the same result. @@ -74,7 +71,7 @@ def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse= 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 timeout > 0 and degree_cap_max >= 0 and exact_work_cap > 0 + 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), @@ -86,7 +83,6 @@ def reconst_control(relevance_cap=6, relevance_cap_dir=24, relevance_cap_sparse= "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), - "timeout": float(timeout), "seed": int(seed), + "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/petab.py b/src/symident/petab.py index a1c086d..5c80203 100644 --- a/src/symident/petab.py +++ b/src/symident/petab.py @@ -495,6 +495,35 @@ def _start(t): return -math.inf if t.strip().lower() == "-inf" else float(t) +def _at_inf(t): + return str(t).strip().lower() in ("inf", "+inf") + + +def _resting(exps, of_row, rows, is_state): + """`exps` with each experiment that starts without a preequilibration, in one period, and whose measurements are + all at t = inf read at rest under the condition of that period, when every other experiment starts with a + preequilibration; and the names of those experiments.""" + 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"]))] + 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) + return exps, [] + out = dict(exps) + for e in rest: + t, c = exps[e][0] + # the parameters keep their values after the rest, so that no period changes them + out[e] = [("-inf", c), (t, {k: v for k, v in c.items() if k not in is_state})] + return out, rest + + def _periods_v2(tabs): """Experiments as {name: [(start, {target: value}), ...]} from the v2 experiment table.""" cond = {} @@ -513,6 +542,23 @@ def _periods_v2(tabs): return exps, of_row +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"]]) + + +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()}) + return totals + + def read_petab(path): """A :class:`Model` from a PEtab problem. @@ -527,11 +573,12 @@ def read_petab(path): One condition per experiment (v1: per pair of preequilibration and simulation condition) with measurements. The estimated parameters stay symbols; every other parameter takes the nominal or SBML value. ``Model.equilibrate`` is set when every - experiment starts with a preequilibration, and ``Model.reduce_cq`` when the - preequilibrated network has conserved totals. ``Model.positive`` holds the estimated - parameters of the model on a log scale or with a positive lower bound. ``m.petab`` - lists the experiments, the estimated parameters, the fixed values, the renamed ids and, - under ``without_effect``, the estimated parameters that no remaining term holds. + experiment starts with a preequilibration or is a readout at rest, and + ``Model.reduce_cq`` when the preequilibrated network has conserved totals. + ``Model.positive`` holds the estimated parameters of the model on a log scale or with a + positive lower bound. ``m.petab`` lists the experiments, the estimated parameters, the + fixed values, the renamed ids, under ``without_effect`` the estimated parameters that no + remaining term holds and under ``at_rest`` the experiments read at rest. Raises ------ @@ -568,6 +615,14 @@ def read_petab(path): between two expressions at a time that every experiment fixes becomes a step state, off during a preequilibration, that an event switches on at that time or at the start. + An experiment in one period without a preequilibration whose measurements are all at time + ``inf`` is a readout at rest: the system starts from the values of the condition, rests + under that condition, and only the resting values of the observables enter. The reading + assumes that a resting state exists and is the one the experiment reaches. An experiment + with a finite measurement time is a trajectory; so is every experiment when one + of them starts without a preequilibration and is not a readout at rest, with a warning, + since all conditions start alike. + A parameter value that names another parameter, such as an initial assignment, takes the value of that parameter in each experiment. States that start at 0 in every experiment, that no event sets and whose rates vanish where all of them are 0 leave the model. @@ -603,6 +658,7 @@ def read_petab(path): odes[k], initial[k] = "0", value.pop(k) states.append(k) is_state = set(states) + 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; " @@ -636,8 +692,7 @@ def val(expr): net = None totals = None if net is not None and all(pre): - from .detection.cq import conserved_totals - totals = conserved_totals(net["stoichiometry"], net["species"]) or None + totals = _retotal(net, [], []) trafos, events, starts = [], [], [] for i, per in enumerate(exps.values()): first = per[0][1] @@ -737,10 +792,7 @@ def val(expr): 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): - 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()}) + 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 # stay 0, also through a preequilibration that starts from these values: they leave the model hit = {e["var"] for e in events} @@ -761,15 +813,9 @@ def val(expr): tr.pop(x, None) x0.pop(x, None) if net is not None: - cols = [j for j, x in enumerate(net["species"]) if x not in nil] - net = 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, zero) for r in net["rates"]]) + net = _drop_species(net, zero) if all(pre): - 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()}) + totals = _retotal(net, trafos, starts) 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) @@ -780,15 +826,9 @@ def val(expr): observables = [{k: _sub(f, still) for k, f in o.items()} for o in observables] events = [dict(e, value=_sub(str(e["value"]), still)) for e in events] if net is not None: - cols = [j for j, x in enumerate(net["species"]) if x not in still] - net = 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, still) for r in net["rates"]]) + net = _drop_species(net, still) if all(pre): - 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()}) + totals = _retotal(net, trafos, starts) if all(pre): # a state without dynamics stays at the initial value through the preequilibration for tr, x0 in zip(trafos, starts): @@ -843,5 +883,5 @@ def val(expr): "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} + "without_effect": without, "at_rest": at_rest} return m diff --git a/src/symident/reduction/absorb.py b/src/symident/reduction/absorb.py new file mode 100644 index 0000000..b5a2533 --- /dev/null +++ b/src/symident/reduction/absorb.py @@ -0,0 +1,281 @@ +"""Directions of a model with unknown inputs: the exact proofs that the inputs absorb them (docs/method/reduction.rst, +"Unknown inputs").""" + +import copy + +import sympy as spy + +from ..errors import SYMPY_FAILS, sympy_fail +from ..rexpr import sym_sort +from ..sym.parse import model_sympify +from .sign import set_positive, sgn + + +def _model(model, settings): + """{"f", "h", "inputs", "known", "ics", "sym", "parse"} of a model with one condition in sympy, or None where the + 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"): + return None + pos = settings.get("positive", True) + texts = [str(v) for v in model.odes.values()] + [str(v) for v in dict(obs).values()] + ids = {str(s) for t in texts for s in model_sympify(t).free_symbols} | set(model.odes) + tr = {str(k): str(v) for k, v in dict(model.trafo or {}).items()} + ids |= {str(s) for v in tr.values() for s in model_sympify(v).free_symbols} + declared = set(ids) if pos is True else set() if pos is False else {str(p) for p in pos} + sym = {n: spy.Symbol(n, positive=True) if n in declared else spy.Symbol(n) for n in ids} + + 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] + known = [sym.get(u, spy.Symbol(u)) for u in list(model.known_inputs or []) + list(model.inputs or [])] + ics = {} + for x in model.odes: + v = tr.get(x, x) + ics[sym[x]] = None if v == x and x not in set(model.fixed or []) else parse(v) + return {"f": f, "h": h, "inputs": inputs, "known": known, "ics": ics, "sym": sym, "parse": parse} + + +def _zero(e): + """Whether `e` is zero, by cancellation and, for non-rational terms, by sympy's simplification.""" + try: + z = spy.cancel(spy.together(e)) + if z == 0: + return True + if z.is_rational_function(): + return False + return spy.simplify(spy.expand_power_base(spy.powsimp(z))) == 0 + except SYMPY_FAILS as exc: + sympy_fail(exc) + return False + + +def _total(e, m): + """The time derivative of `e` along the model `m` for a function of the states and coordinates.""" + return sum((spy.diff(e, x) * fx for x, fx in m["f"].items()), spy.Integer(0)) + + +def inversion(m): + """The inversion of the unknown inputs from the first derivatives of the observables, or None: as many + 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): + return None + try: + M = spy.Matrix([[spy.diff(_total(e, m), wj) for wj in w] for e in h]) + det = spy.factor(spy.cancel(M.det(method="berkowitz"))) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + if _zero(det): + return None + return {"determinant": str(det).replace("**", "^"), "signed": sgn(det) != 0} + + +def _ok_part(e, free): + """Whether `e` reads only the symbols in `free`.""" + return {str(s) for s in e.free_symbols} <= free + + +def lift(gen, m, coords): + """The pointwise lift of the direction `gen`: (params, states, inputs) with xi_theta on the parameters only, + xi_x on the parameters and states, xi_w solved from the identities, or None where no such lift holds.""" + states = [str(x) for x in m["f"]] + params = [c for c in coords if c not in set(states)] + sym = m["sym"] + G = {} + try: + for k, v in gen.items(): + G[sym.get(k, spy.Symbol(k))] = m["parse"](str(v)) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + P = [sym.get(p, spy.Symbol(p)) for p in params] + X = list(m["f"]) + fixed_syms = {str(s) for s in P} + varying = {str(x) for x in X} | {str(w) for w in m["inputs"]} | {str(u) for u in m["known"]} | {"time"} + pc = [p for p in P if p in G and G[p] != 0] + if not pc or any(k not in set(P) | set(X) and v != 0 for k, v in G.items()): + return None + # a direction is determined up to a factor: the first parameter component free of the varying symbols as + # one, where the others then are + for piv in [None] + pc: + c = spy.Integer(1) if piv is None else G[piv] + try: + H = {k: spy.cancel(v / c) for k, v in G.items()} + except SYMPY_FAILS as exc: + sympy_fail(exc) + continue + if all(not ({str(s) for s in H[p].free_symbols} & varying) for p in pc): + break + else: + return None + xi_p = {p: H.get(p, spy.Integer(0)) for p in P} + xi_x = {x: H.get(x, spy.Integer(0)) for x in X} + if any(not _ok_part(e, fixed_syms | {str(x) for x in X}) for e in xi_x.values()): + return None + Xi = [spy.Dummy(f"xi_{w}") for w in m["inputs"]] + V = {**xi_p, **xi_x, **dict(zip(m["inputs"], Xi))} + + 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] + sol = spy.linsolve([spy.numer(e) for e in eqs], Xi) if Xi else None + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + if Xi: + if not sol or len(sol.args) != 1: + return None + vals = [v.xreplace({d: 0 for d in Xi}) for v in sol.args[0]] + sub = dict(zip(Xi, vals)) + else: + sub = {} + if not all(_zero(e.xreplace(sub)) for e in eqs): + return None + for x, e in m["ics"].items(): + # a given initial value moves with the parameters it reads + if e is None: + continue + at = {y: v for y, v in m["ics"].items() if v is not None} + if not _zero(xi_x[x].xreplace(at) - sum((spy.diff(e, p) * xi_p[p] for p in P), spy.Integer(0))): + return None + + 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)}} + + +def _reads(gen, names): + """Whether a component of the generator `gen` reads one of `names`.""" + for v in gen.values(): + try: + if {str(s) for s in model_sympify(str(v)).free_symbols} & names: + return True + except SYMPY_FAILS as exc: + sympy_fail(exc) + return True + return False + + +def prepare(raw, model): + """(raw, notes): the detection `raw` of a model with unknown inputs with each direction that the inputs absorb + proven by the inversion of the inputs or by a pointwise lift, the generator of a lift restricted to the + 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"): + return raw, {} + settings = info.get("settings") or {} + coords = [str(c) for c in info.get("coordinates") or []] + jets = {j for js in (ui.get("jets") or {}).values() for j in js} + raw = copy.deepcopy(raw) + pos = settings.get("positive", True) + old = set_positive(None if pos is True else [] if pos is False else [str(p) for p in pos]) + try: + m = _model(model, settings) + inv = inversion(m) if m is not None else None + notes = {} + for i, d in enumerate(raw["symmetries"]): + gen = d.get("generator") + if gen is None: + continue + d.setdefault("kind", orbit_kind(d)) + ch = d.get("input_change") + # an input change without a closed form counts as a change + moves_input = ch is None or any(str(v).strip() not in ("0", "0.0") for v in ch.values()) + if m is None: + if moves_input: + d["input_refusal"] = "setting" + if d.get("type") == "scaling": + d["type"], d["weights"] = "general", None + continue + if inv is not None and not _reads(gen, jets): + notes[i] = {"proof": "inversion", **inv} + d["input_proof"] = "inversion" + continue + lf = lift(gen, m, coords) + if lf is not None and not any(v != "0" for v in lf["inputs"].values()) and not moves_input: + # a symmetry of the model that keeps the inputs + continue + if lf is None: + if moves_input or _reads(gen, jets | set(model.odes)): + d["input_refusal"] = True + if d.get("type") == "scaling": + d["type"], d["weights"] = "general", None + continue + notes[i] = {"proof": "lift", "lift": lf} + d["input_proof"] = "lift" + d["generator"] = dict(lf["params"]) + 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"]): + d["weights"] = w + else: + d["type"], d["weights"] = "general", None + return raw, notes + finally: + set_positive(old) + + +def condition(note, inputs, positive): + """The condition under which the section of a direction the inputs absorb gives the output of a point.""" + if positive is True: + dom = ", ".join(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") + + +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 []))} + info = raw.get("info") or {} + inputs = list((info.get("unknown_inputs") or {}).get("names") or []) + pos = (info.get("settings") or {}).get("positive", True) + of = {labels[i]: n for i, n in notes.items() if i in labels} + for b in red.get("blocks") or []: + mine = [of[l] for l in b.get("labels") or [] if l in of] + 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)} + 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")) + 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") + b["certificates"] = list(b.get("certificates") or []) + certs diff --git a/src/symident/reduction/blocks.py b/src/symident/reduction/blocks.py index e812456..3fd4d4b 100644 --- a/src/symident/reduction/blocks.py +++ b/src/symident/reduction/blocks.py @@ -354,22 +354,32 @@ def _axis_signed(v, reduced, originals): def _input_absorbed(d, prefer): """The reason a direction of a model with unknown inputs has no chart in the parameters, or None.""" unknown = (prefer or {}).get("unknown_inputs") or {} - if not unknown or d.get("generator") is None: + if not unknown or d.get("generator") is None or d.get("input_proof"): return None varying = set((prefer or {}).get("states") or ()) | {j for js in unknown.values() for j in js} comps = [str(v) for v in d["generator"].values()] used = {x for x in red_locals(comps)} hit = sym_sort(used & varying) - if not hit: + if not hit and not d.get("input_refusal"): return None moved = [c for c, v in d["generator"].items() if str(v).strip() not in ("0", "0.0")] inputs = sym_sort([w for w, js in unknown.items() if set(js) & (set(moved) | used)]) params = sym_sort([c for c in moved if c not in varying]) w = ", ".join(inputs) or "the unknown inputs" 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") + 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} {'is' if len(params) == 1 else 'are'} non-identifiable because {w} " + f"has no chart for it; {p} {verb} non-identifiable because {w} " f"{'absorbs' if len(inputs) == 1 else 'absorb'} the change") diff --git a/src/symident/reduction/core.py b/src/symident/reduction/core.py index 976694d..e18b99f 100644 --- a/src/symident/reduction/core.py +++ b/src/symident/reduction/core.py @@ -2,7 +2,6 @@ import math import re -import time import warnings import numpy as np @@ -189,8 +188,8 @@ def back(x, solve_for=None): # candidate sections the search of one block may try WORK_CAP = 4000 -# seconds the section search of one block may take by default -REDUCE_TIMEOUT = 600 +# the positive transversals tried for scaling pins inside the curved support +REBASE_CHOICES = 4 def model_structure(obj, coords): @@ -559,11 +558,17 @@ def _signed(res): return any(b.get("sign_conditions") for b in res.get("blocks") or []) +def _partial(res): + """Whether a block of the reduction covers part of the orbits only.""" + return any(b.get("coverage") == "partial" for b in res.get("blocks") or []) + + def _chart_rank(res): - """Sort key of a reduction: level, directions removed, no sign conditions, rational trafo; ties keep build order.""" + """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), not _rational_chart(res)) + _signed(res), _partial(res), not _rational_chart(res)) def _outside_coordinates(sol, b, coords, states): @@ -626,8 +631,56 @@ def run(**opts): return best +def _rebased(syms, idx, blocks): + """`syms` with the directions `idx` combined with the scalings to leave every scaling pin unmoved, or None. + + 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: + gen = syms[i].get("generator") + if not gen: + continue + hits = [b for b in scal if any(str(gen.get(t, "0")).strip() not in ("0", "0.0") for t in b["transversal"])] + if not hits: + continue + try: + loc = red_locals(list(gen) + [str(v) for v in gen.values()] + [c for b in hits for c in b["Wcols"]]) + G = {k: red_sympify(str(v).replace("^", "**"), loc) for k, v in gen.items()} + for b in hits: + W, cols, T = b["Wres"], b["Wcols"], b["transversal"] + A = spy.Matrix([[int(W[r, cols.index(t)]) for r in range(W.shape[0])] for t in T]) + lam = A.LUsolve(spy.Matrix([G.get(t, spy.Integer(0)) / spy.Symbol(t) for t in T])) + for j, c in enumerate(cols): + w = sum(lam[r] * int(W[r, j]) for r in range(W.shape[0])) + if w != 0: + G[c] = G.get(c, spy.Integer(0)) - w * spy.Symbol(c) + G = {k: spy.cancel(spy.together(e)) for k, e in G.items()} + G = {k: e for k, e in G.items() if e != 0} + if not G: + return None + den = spy.Integer(1) + for e in G.values(): + den = spy.lcm(den, spy.fraction(e)[1]) + num = {k: spy.expand(spy.cancel(e * den)) for k, e in G.items()} + g = spy.Integer(0) + for e in num.values(): + g = spy.gcd(g, e) + num = {k: spy.cancel(e / g) for k, e in num.items()} + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + gstr = {k: str(e).replace("**", "^") for k, e in num.items()} + d = {k: v for k, v in syms[i].items() if k not in ("complete_generator", "state_components", "display")} + d.update(generator=gstr, support=sym_sort(list(gstr)), factor="1", state_components=None) + out[i] = d + return out + + def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d_exp=2, separable_=True, - zero_compatibility=False, timeout=REDUCE_TIMEOUT, work_cap=WORK_CAP): + 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) @@ -641,7 +694,7 @@ def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d 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_dl = DOMAIN["deadline"] + 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; " @@ -664,7 +717,7 @@ def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d d_poly=d_poly, d_darboux=d_darboux, d_exp=d_exp, separable_=separable_, zero_compatibility=zero_compatibility, - timeout=timeout, work_cap=work_cap) + work_cap=work_cap) finally: DOMAIN["no_roots"] = old_nr return log_back(res, lc) @@ -682,7 +735,7 @@ def _symmetry_reduction(obj, fixed=None, positive=True, d_poly=3, d_darboux=2, d positive=pos2 if pos2 else False, d_poly=d_poly, d_darboux=d_darboux, d_exp=d_exp, separable_=separable_, zero_compatibility=zero_compatibility, - timeout=timeout, work_cap=work_cap) + work_cap=work_cap) finally: DOMAIN["no_roots"] = old_nr return exp_back(res, ec) @@ -754,13 +807,38 @@ def scaling_blocks(dm): if dm["kept"] and any(b["status"] not in ("reduced", "fixed") for b in blocks): dm = demote(False) blocks = scaling_blocks(dm) + syms = o["syms"] + 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": []} + best = None + for skip in range(REBASE_CHOICES): + with state.options(transversal_skip=skip or None): + alt = scaling_blocks(dm_in) + if not all(b["status"] in ("reduced", "fixed") and b.get("coverage") != "partial" for b in alt): + break + if best is not None and [b.get("pins") for b in alt] == [b.get("pins") for b in best[0]]: + break + reb = _rebased(syms, curved_idx0, alt) + if reb is None: + continue + # the pins that leave the shortest curved generators + size = sum(len(str(reb[i].get("generator"))) for i in curved_idx0) + if best is None or size < best[2]: + best = (alt, reb, size) + if best is not None: + dm, blocks, syms = dm_in, best[0], best[1] + elif state.get("reduce_pin_inside"): + syms = _rebased(syms, curved_idx0, blocks) or syms curved_idx = sorted(curved_idx0 + [wr["rows"][r] for r in dm["demoted"]]) scal_pins = {} for b in blocks: if b["type"] == "scaling" and b.get("pins"): scal_pins.update(b["pins"]) if curved_idx: - blocks += curved(o["syms"], curved_idx, o["labels"], fixed, d_poly, d_darboux, d_exp, + 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: @@ -775,7 +853,7 @@ def scaling_blocks(dm): session.note("limits", f"invariants of {', '.join(b['labels'])}: {c}") inv_start = 0 dens = None - gen_of = dict(zip(o["labels"], o["syms"])) + gen_of = dict(zip(o["labels"], syms)) for b in blocks: if b["type"] != "curved" or not b.get("invariants") or b.get("status") == "reduced": continue @@ -783,7 +861,6 @@ def scaling_blocks(dm): continue if dens is None: dens = model_denominators(obj["info"].get("model_exprs") or []) - DOMAIN["deadline"] = time.monotonic() + timeout if math.isfinite(timeout) else None DOMAIN["work"], DOMAIN["work_cap"] = 0, work_cap try: sol = face_section(b, scal_pins, dens) @@ -826,9 +903,6 @@ def scaling_blocks(dm): 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") - elif DOMAIN["deadline"] is not None and time.monotonic() > DOMAIN["deadline"]: - session.note("limits", f"section search of {', '.join(b['labels'])}: reduce(timeout={timeout}) " - "reached") if sol.get("solved"): foreign = _outside_coordinates(sol, b, coords, (obj.get("info") or {}).get("model_rhs") or {}) if foreign: @@ -874,13 +948,18 @@ def scaling_blocks(dm): b["gauge_note"] = "; ".join(notes) b["new_parameters"] = sol.get("meaning") b["status"] = "reduced" - certs = ["solved exactly: each invariant becomes a fresh q_ parameter"] + 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()})") 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") @@ -926,4 +1005,5 @@ def scaling_blocks(dm): return red_result(obj, blocks, trafo, coords, fixed, settings) finally: set_positive(old_pos) - DOMAIN["deadline"] = old_dl + # the work cap of this call ends with it + DOMAIN["work"], DOMAIN["work_cap"] = old_work diff --git a/src/symident/reduction/expr.py b/src/symident/reduction/expr.py index cd5231a..f55f624 100644 --- a/src/symident/reduction/expr.py +++ b/src/symident/reduction/expr.py @@ -229,6 +229,45 @@ def vrow(pr): return {"preps": out_preps, "labels_of": labels_of, "combos": combos} +RADICAL_NODES = 3000 + + +# a discriminant is tested for a square only below this size +SQUARE_NODES = 400 + + +def _nodes_above(e, cap=None): + """Whether `e` has more than `cap` (RADICAL_NODES) nodes.""" + cap = RADICAL_NODES if cap is None else cap + return any(n > cap for n, _ in enumerate(spy.preorder_traversal(e))) + + +def _radical_heavy(e): + """Whether `e` holds a radical and more than RADICAL_NODES nodes.""" + return any(not a.exp.is_Integer for a in e.atoms(spy.Pow)) and _nodes_above(e) + + +def _low_roots(c): + """The roots of the linear or quadratic polynomial with coefficients `c`, highest first, by the formulas.""" + if len(c) == 2: + return [spy.cancel(-c[1] / c[0])] + a, b, d = c + disc = spy.expand(b**2 - 4 * a * d) + if disc == 0: + return [spy.cancel(-b / (2 * a))] + if _nodes_above(disc, SQUARE_NODES): + r = spy.sqrt(disc) + return [(-b + r) / (2 * a), (-b - r) / (2 * a)] + k, fl = spy.sqf_list(disc) + odd = spy.Mul(*[f for f, m in fl if m % 2]) + if k < 0: + # a negative content stays under the root with the odd part: no imaginary unit for a real radicand + k, odd = -k, spy.expand(-odd) + # a square discriminant gives rational roots + r = spy.sqrt(k) * spy.Mul(*[f ** (m // 2) for f, m in fl]) * spy.sqrt(odd) + return [(-b + r) / (2 * a), (-b - r) / (2 * a)] + + def roots_in(e, v, info=None): """Roots in `v` of the linear and quadratic numerator factors of `e`; else `info["complete"]` is False. @@ -238,8 +277,23 @@ def roots_in(e, v, info=None): sv = spy.Symbol(v) try: num = spy.fraction(spy.together(e))[0] + if _radical_heavy(num): + # factoring a large polynomial over a radical has no bound on time + if info is not None: + info["complete"] = False + return [] rad = {a: spy.Dummy() for a in num.atoms(spy.Pow) if not a.exp.is_Integer and not a.has(sv)} - fl = spy.factor_list(num.xreplace(rad), sv) + num = num.xreplace(rad) + # a factorization is needed only past degree 2, and only below a bounded size + pn = spy.Poly(num, sv) + if pn.degree() <= 2: + fl = (1, [(pn, 1)]) + elif _nodes_above(num): + if info is not None: + info["complete"] = False + return [] + else: + fl = spy.factor_list(num, sv) back = {d: a for a, d in rad.items()} except SYMPY_FAILS as exc: sympy_fail(exc) @@ -250,11 +304,12 @@ def roots_in(e, v, info=None): for fm in fl[1]: f = fm[0] try: - dg = int(spy.Poly(f, sv).degree()) + pf = f if isinstance(f, spy.Poly) else spy.Poly(f, sv) + dg = int(pf.degree()) if dg > 2: raise ValueError("degree above 2") if dg >= 1: - out += [r.xreplace(back) for r in spy.solve(f, sv)] + out += [r.xreplace(back) for r in _low_roots(pf.all_coeffs())] except SYMPY_FAILS + (ValueError,) as exc: if not isinstance(exc, ValueError): sympy_fail(exc) @@ -289,7 +344,7 @@ def first_subsets(n, k, m): def tri_solve(sys_, vars_, info=None): """Triangular elimination of the equations; `info["complete"]` is False when a branch may be missing. - Stops, with the branches incomplete, once the work budget or the deadline of the section search is spent.""" + Stops, with the branches incomplete, once the work cap of the section search is spent.""" from .sign import budget_spent if not vars_: return [{}] @@ -323,10 +378,25 @@ def tri_solve(sys_, vars_, info=None): if info is not None: info["complete"] = False continue + if any(_radical_heavy(e) for e in rest): + if info is not None: + info["complete"] = False + continue for s in tri_solve(rest, [x for x in vars_ if x != v], info): s = dict(s) - s[v] = spy.cancel(r.subs([(spy.Symbol(k), x) for k, x in s.items()])) if s else r + e = r.subs([(spy.Symbol(k), x) for k, x in s.items()]) if s else r + if s and _radical_heavy(e): + # canceling a large expression over a radical has no bound on time: the branch counts as + # missing + if info is not None: + info["complete"] = False + continue + s[v] = spy.cancel(e) if s else r out.append(s) + if budget_spent(): + if info is not None: + info["complete"] = False + break if out: return out # no branch is complete only when an equation is a nonzero constant diff --git a/src/symident/reduction/scaling.py b/src/symident/reduction/scaling.py index 1646cf2..4ce0808 100644 --- a/src/symident/reduction/scaling.py +++ b/src/symident/reduction/scaling.py @@ -133,6 +133,13 @@ def certify_transversal(W, cols, T): return Mr +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)} + + def transversal(Wres, cols, fixed, allowed=None): """A certified transversal, the family of valid transversals and the survivor meanings.""" k = Wres.shape[0] @@ -144,11 +151,14 @@ def transversal(Wres, cols, fixed, allowed=None): if not k: return out occ = {c: int(np.sum(Wres[:, cols.index(c)] != 0)) for c in supp} - ordc = sorted(supp, key=lambda c: (occ[c], cols.index(c))) + signed = _signed_coordinates(supp) + # a scaling keeps the sign of a coordinate, so a pin on a positive one meets every orbit + ordc = sorted(supp, key=lambda c: (c in signed, occ[c], cols.index(c))) enumerate_ = len(supp) <= 30 and math.comb(len(supp), k) <= 200 if enumerate_: combos = [list(c) for c in itertools.combinations(supp, k)] adm = [T for T in combos if rank_modp(Wres[:, [cols.index(t) for t in T]]) == k] + adm.sort(key=lambda T: len(set(T) & signed)) out["choices"] = adm # reduce() asks for a later certified transversal when it collects alternative trafos skip = int(state.get("transversal_skip") or 0) diff --git a/src/symident/reduction/sections.py b/src/symident/reduction/sections.py index 9b3fded..082af19 100644 --- a/src/symident/reduction/sections.py +++ b/src/symident/reduction/sections.py @@ -13,7 +13,7 @@ from .darboux import apply_x from .expr import free_syms, red_locals, red_sympify, tri_solve from .scaling import mono_string -from .sign import DOMAIN, is_real, num_sign, positive_set, set_positive, sgn, sgn_real, time_up +from .sign import DOMAIN, is_real, num_sign, positive_set, set_positive, sgn, sgn_real, work_up def mono_parts(m): @@ -190,6 +190,49 @@ def section_monotone(pr, preps, xi_of, loc, pts): return row +def split_products(invariants, support): + """Balances u*v = 1 for an invariant A - B with A, B of one sign, u a positive coordinate of A and v one of B. + + The orbits leave the domain where A or B vanishes, by the sign of the invariant; u*v tends to 0 at both exits.""" + pos = positive_set() + sup = [v for v in support if pos is None or v in set(pos)] + out = [] + for Ie in invariants: + try: + terms = spy.Add.make_args(spy.expand(spy.fraction(spy.together(Ie))[0])) + except SYMPY_FAILS as exc: + sympy_fail(exc) + continue + if len(terms) != 2 or sgn(terms[0]) * sgn(terms[1]) != -1: + continue + own = [[v for v in sup if spy.Symbol(v) in t.free_symbols] for t in terms] + for u in own[0]: + for v in own[1]: + pr = ["*".join(sym_sort([u, v])), "1"] + if u != v and pr not in out: + out.append(pr) + return out + + +def section_jacobian(prs, preps, xi_of, loc): + """Whether the balance ratios `prs`, as many as the generators, have a Jacobian along them of one sign.""" + if len(prs) != len(preps) or not prs: + return False + rows = [] + for pr in prs: + 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))]) + try: + det = spy.expand(spy.Matrix(rows).det(method="berkowitz")) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return False + return not det.is_zero and sgn(det) != 0 + + def _monomial_section(pairs, sym): """The positive points with m1 = m2 for each pair of Laurent monomials as theta0 * u^K, or None.""" rows, cs, names = [], [], [] @@ -253,7 +296,12 @@ def own(e): def _vanishes(e): - return spy.cancel(e) == 0 or spy.simplify(e) == 0 + 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} + return (bool(rads) and spy.cancel(e.xreplace(rads)) == 0) or spy.simplify(e) == 0 def _linear_section(pairs): @@ -784,7 +832,7 @@ def zero_ok(sub): conditional = [] pos = positive_set() for s in itertools.combinations(range(len(z_cand)), r): - if time_up(): + if work_up(): break Z = [z_ord[i] for i in s] sub_z = [(spy.Symbol(v), spy.Integer(0)) for v in Z] diff --git a/src/symident/reduction/sign.py b/src/symident/reduction/sign.py index 24fd52c..f9c1dbc 100644 --- a/src/symident/reduction/sign.py +++ b/src/symident/reduction/sign.py @@ -3,7 +3,6 @@ import contextlib import math import re -import time import warnings from fractions import Fraction @@ -165,7 +164,7 @@ def positive_set_of(positive, coords): return [p for p in positive if p in set(coords)] -DOMAIN = {"positive": None, "real_carriers": [], "no_roots": False, "sgn_cache": None, "deadline": None, +DOMAIN = {"positive": None, "real_carriers": [], "no_roots": False, "sgn_cache": None, "bounds": []} @@ -340,19 +339,16 @@ def _absorb_exact(expts, cf): def budget_spent(): - """Whether the work budget or the deadline of the section search is spent, without spending a unit.""" - cap, d = DOMAIN.get("work_cap"), DOMAIN["deadline"] - return (cap is not None and DOMAIN.get("work", 0) > cap) or (d is not None and time.monotonic() > d) + """Whether the work cap of the section search is spent, without spending a unit.""" + cap = DOMAIN.get("work_cap") + return cap is not None and DOMAIN.get("work", 0) > cap -def time_up(): - """Whether the work budget of the section search, one unit per call, or the deadline of the search is spent.""" +def work_up(): + """Whether the work cap of the section search is spent, one unit per call.""" DOMAIN["work"] = DOMAIN.get("work", 0) + 1 cap = DOMAIN.get("work_cap") - if cap is not None and DOMAIN["work"] > cap: - return True - d = DOMAIN["deadline"] - return d is not None and time.monotonic() > d + return cap is not None and DOMAIN["work"] > cap def sgn(pp, depth=0): diff --git a/src/symident/reduction/solve.py b/src/symident/reduction/solve.py index ef6fe45..efd5c1d 100644 --- a/src/symident/reduction/solve.py +++ b/src/symident/reduction/solve.py @@ -12,7 +12,7 @@ from ..errors import SYMPY_FAILS, sympy_fail from ..gfp import Pool from ..rexpr import sym_sort -from .expr import free_syms, red_locals, red_sympify, tri_solve +from .expr import _nodes_above, free_syms, red_locals, red_sympify, tri_solve from .invariants import certified_rank from .sections import ( inv_summands, @@ -20,7 +20,9 @@ orbits_reach, section_cands, section_injective, + section_jacobian, section_monotone, + split_products, ) from .sign import ( DOMAIN, @@ -39,9 +41,9 @@ sgn, shift_fix, shifted_meaning, - time_up, translates, translation_gauge, + work_up, ) @@ -78,6 +80,32 @@ def _negative(entries): return any(sgn(e) == -1 for e in entries) +# the size of a system that the unbounded sympy solver may still take when the triangular elimination misses a branch +SMALL_SOLVE_DEGREE, SMALL_SOLVE_NODES = 4, 120 + + +def _carrier_branches(eqs, carriers, bezout): + """The carriers solved from `eqs` by triangular elimination, bounded by the work budget; None when it fails. + + A system small in degree and size goes to the sympy solver when the elimination misses a branch.""" + info = {"complete": True} + try: + out = tri_solve(eqs, list(carriers), info) + except SYMPY_FAILS as exc: + sympy_fail(exc) + out, info["complete"] = [], False + out = [d for d in out if len(d) == len(carriers)] + if info["complete"] and out: + return out + if bezout > SMALL_SOLVE_DEGREE or any(_nodes_above(e, SMALL_SOLVE_NODES) for e in eqs): + return out or None + try: + return [_str_keys(d) for d in spy.solve(eqs, [spy.Symbol(v) for v in carriers], dict=True)] + except SYMPY_FAILS as exc: + sympy_fail(exc) + return out or None + + def _str_keys(d): return {str(k): v for k, v in d.items()} @@ -94,7 +122,7 @@ def solve_invariants(b, pins, coords=(), inv_start=0, prefer_real=False, split_p def _memo_solve(b, pins, coords, inv_start, prefer_real, split_pair, gens, signed_ok): args = (b, pins, coords, inv_start, prefer_real, split_pair, gens, signed_ok) ses = state.get("session") - if ses is None or DOMAIN["deadline"] is not None: + if ses is None: return _solve_invariants(*args) # the alternative reparametrizations of one reduction search equal blocks again; the work spent is replayed try: @@ -199,6 +227,63 @@ def power_ok(frac, v): DOMAIN["real_carriers"] = old_rc +def _section_chart(support, unknowns, es, pairs, tmp_n, inv_n, Ies, pins, pinned): + """The section, met once by every orbit, parametrized by the coordinates of the section where the balances solve + rationally. + + 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: + sympy_fail(exc) + return None + if param is None: + return None + solved = {str(k): v for k, v in param.items()} + free = [v for v in unknowns if v not in solved] + if len(free) != len(inv_n) or set(solved) - set(unknowns): + return None + pos = positive_set() + sub = {spy.Symbol(v): spy.Symbol(q) for v, q in zip(free, inv_n)} + ent = {} + for v, e in solved.items(): + # in the free coordinates, which keep their declared signs as new parameters + e = spy.cancel(e) + if (pos is None or v in set(pos)) and sgn(e) != 1: + return None + ent[v] = str(e.xreplace(sub)).replace("**", "^") + 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)}} + + +def _split_sets(Ies, b, gauge0, cands, tried, own_of, touches): + """Sets of balances with a split product among them, untried so far, whose Jacobian along the generators has + one sign.""" + preps = b.get("preps") + if preps is None or len(preps) != len(gauge0) or len(gauge0) > 2: + return [] + 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] + 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]) + xi_of = [{v: red_sympify(x, loc) for v, x in g["comps"].items()} for g in preps] + return [st for st in sets if section_jacobian(st, preps, xi_of, loc)] + + +# the sets of balances with a split product checked for a Jacobian of one sign +SPLIT_SETS = 20 + + def _carrier_choices(adm, support, first, cap=8): """Carrier matchings that leave different coordinates of `support` as gauge, `first` first, at most `cap`.""" out = [first] @@ -229,11 +314,7 @@ def _solve_invariants_inner(b, pins, coords, Ies, inv_n, carriers, tmp_n, real_t 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 - try: - sol_carr = [_str_keys(d) for d in spy.solve(eqs, [spy.Symbol(v) for v in carriers], dict=True)] - except SYMPY_FAILS as exc: - sympy_fail(exc) - sol_carr = None + sol_carr = _carrier_branches(eqs, carriers, bezout) gauge_all = [v for v in b["support"] if v not in carriers] reach = [] @@ -280,7 +361,7 @@ 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 time_up(): + if best_root is not None or work_up(): break pinned1 = [v for v in gauge_all if v not in gauge0] pins = dict(pins_in, **{v: pin_val(v) for v in pinned1}) @@ -431,9 +512,10 @@ def sec_positive(st): 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") - for st in sets[:n_try]: + jac_sets = _split_sets(Ies, b, gauge0, cands, sets[:n_try], own_of, touches) + for st in sets[:n_try] + jac_sets: for order in ("carriers", "sections"): - if best_root is not None or time_up(): + if best_root is not None or work_up(): continue if order == "sections" and not carr_br: continue @@ -508,7 +590,8 @@ def sec_positive(st): sympy_fail(exc) secs.append(f"{pr[0]} = {pr[1]}") cand["section"] = secs + [f"{v} = {pins[v]}" for v in pinned1] - cand["monotone"] = b.get("preps") is not None + 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["meaning"] = shifted_meaning(b["invariants"], inv_n, tmp_n, sh) @@ -523,6 +606,13 @@ def sec_positive(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) + if sc is not None: + cand.update(sc) + return cand if not partial and not has_root: return cand if not partial and best_root is None: @@ -641,8 +731,8 @@ def to_inv(v): return best if signed is not None: return signed - if time_up(): - out["reason"] = "the section search stopped at reduce(work_cap=) or reduce(timeout=)" + if work_up(): + out["reason"] = "the section search stopped at reduce(work_cap=)" return out tried = "" if any("exp(" in s for s in b["invariants"]): diff --git a/src/symident/report.py b/src/symident/report.py index e4bbb71..a89f6e2 100644 --- a/src/symident/report.py +++ b/src/symident/report.py @@ -220,13 +220,35 @@ def global_lines(res, width=None): return ["", _wrap(f"Global: not analyzed, {info['unsupported']}", "", width)] 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 {info.get('order')}" + (f", gap order {info['gap_order']}" if info.get("gap_order") 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)] + 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 "")) + 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)) + 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)) 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 \ @@ -297,6 +319,10 @@ def summary_lines(res, verbose=False, width=None): if info.get("conditions") and info["conditions"] > 1: 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'])") sw = info.get("switching") if sw: comp.append("switches: " + ", ".join( @@ -598,7 +624,8 @@ def reduction_lines(x, width=None, detail_call=DETAIL_CALL): 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_zero_lines(x, width) + branch_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 @@ -614,6 +641,22 @@ def reduction_lines(x, width=None, detail_call=DETAIL_CALL): return out +def red_input_lines(x, width=None): + """Per reduced block that unknown inputs absorb: the inputs, the proof and the condition of the section.""" + groups = {} + for b in x.get("blocks") or []: + ui = b.get("inputs") + 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) + 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()] + return ["", "Unknown inputs:"] + out if out else [] + + def branch_lines(x, width=None): """The branches of a discrete symmetry: per side of its fixed set the coordinate it solves, the chosen one marked; the boundary once.""" @@ -658,7 +701,8 @@ def reduction_summary_lines(x, verbose=False, width=None, detailed=False, detail 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_zero_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"]: diff --git a/src/symident/rjson.py b/src/symident/rjson.py index 070ee06..9e1f456 100644 --- a/src/symident/rjson.py +++ b/src/symident/rjson.py @@ -121,8 +121,6 @@ def reduce_json(obj, args, env=None): a = json.loads(args) if args else {} kw = {} for k, v in a.items(): - if k == "timeout" and v == "Inf": - v = math.inf kw["separable_" if k == "separable" else k] = v if kw.get("positive") is None: kw["positive"] = detection_positive(o) diff --git a/src/symident/session.py b/src/symident/session.py index 2bf6f9f..a7227d0 100644 --- a/src/symident/session.py +++ b/src/symident/session.py @@ -1,4 +1,4 @@ -"""The state one detection shares across nested analyses: seed, reconstruction deadline, limits that fired.""" +"""The state one detection shares across nested analyses: seed and limits that fired.""" import contextlib import hashlib @@ -13,7 +13,6 @@ class Session: def __init__(self, seed=0, model=""): self.root = hashlib.blake2b(f"{int(seed)}\0{model}".encode(), digest_size=16).digest() - self.deadline = None # draws: per passing kernel check, the number of points it drew self.notes = {"limits": [], "errors": [], "branches": [], "draws": []} self.control = None diff --git a/src/symident/state.py b/src/symident/state.py index d89b07c..1e8f337 100644 --- a/src/symident/state.py +++ b/src/symident/state.py @@ -82,13 +82,21 @@ def switches(**kw): "NOGROUP": ("route", "no translation groups in the narrow route"), "NOFWDSEED": ("route", "no forward seed of the resting states"), "NODIAG": ("route", "no diagonal start: resting conditions continued from the forward one only"), + "NOSHARED": ("route", "a tape per condition also where the conditions differ only in the values of symbols"), + "NOSELECT": ("route", "every condition analyzed, also where many conditions add nothing to the rank"), "LIEPLATEAU": ("number", "orders the rank stays flat before the saturation ends (3)"), "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)"), - "DIRECTSECS": ("number", "seconds msolve may take for the direct kernel (120)"), "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"), "MSOLVE_VERSION": ("install", "msolve version install_msolve() builds"), diff --git a/src/symident/sym/continuation.py b/src/symident/sym/continuation.py index ec6c113..9dd9a25 100644 --- a/src/symident/sym/continuation.py +++ b/src/symident/sym/continuation.py @@ -131,4 +131,3 @@ def ser_of(terms): '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 new file mode 100644 index 0000000..91f79bd --- /dev/null +++ b/src/symident/sym/degrees.py @@ -0,0 +1,110 @@ +"""Degrees of the Taylor coefficients of the observables in the coordinates, from the recursion of the series run +on degree bounds instead of values (docs/method/global.rst, "The verified count").""" + +from fractions import Fraction + + +class Atoms: + """The factors of the denominators, each with a degree bound; one factor per object divided by.""" + + def __init__(self): + self.deg, self._divisors = [], {} + + def divisor(self, x): + if id(x) not in self._divisors: + self.deg.append(x.dn) + self._divisors[id(x)] = (len(self.deg) - 1, x) + return self._divisors[id(x)][0] + + def of(self, den): + """The degree of the product of the factors with the exponents in `den`.""" + return sum(e * self.deg[a] for a, e in den.items()) + + +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): + self.A, self.dn, self.den, self.c = A, dn, dict(den or {}), c + + @classmethod + def const(cls, A, x): + return cls(A, 0, None, Fraction(x)) + + def _of(self, x): + return x if isinstance(x, Deg) else Deg.const(self.A, x) + + def __add__(self, x): + x = self._of(x) + if self.c is not None and x.c is not None: + return Deg.const(self.A, self.c + x.c) + if self.c == 0: + return x + if x.c == 0: + return self + L = {a: max(self.den.get(a, 0), x.den.get(a, 0)) for a in set(self.den) | set(x.den)} + da = self.A.of({a: e - self.den.get(a, 0) for a, e in L.items()}) + db = self.A.of({a: e - x.den.get(a, 0) for a, e in L.items()}) + return Deg(self.A, max(self.dn + da, x.dn + db), L) + + __radd__ = __add__ + + def __neg__(self): + return Deg(self.A, self.dn, self.den, None if self.c is None else -self.c) + + def __sub__(self, x): + return self + (-self._of(x)) + + def __rsub__(self, x): + return self._of(x) - self + + def __mul__(self, x): + x = self._of(x) + if self.c is not None and x.c is not None: + return Deg.const(self.A, self.c * x.c) + if self.c == 0 or x.c == 0: + return Deg.const(self.A, 0) + den = dict(self.den) + for a, e in x.den.items(): + den[a] = den.get(a, 0) + e + return Deg(self.A, self.dn + x.dn, den) + + __rmul__ = __mul__ + + def __truediv__(self, x): + x = self._of(x) + if x.c is not None: + if x.c == 0: + raise ZeroDivisionError("division by zero") + return self * Deg.const(self.A, 1 / x.c) + # 1/x: the factors of the denominator of x over the numerator of x, a new factor + return self * Deg(self.A, self.A.of(x.den), {self.A.divisor(x): 1}) + + def __rtruediv__(self, x): + return self._of(x) / self + + def __pow__(self, e): + out = Deg.const(self.A, 1) + for _ in range(int(e)): + out = out * self + return out + + def __eq__(self, x): + if isinstance(x, (int, Fraction)) and x == 0: + return self.c == 0 + return NotImplemented + + __hash__ = None + + +def common(values): + """(deg q, [deg of each numerator over q]): the lcm q of the denominators of `values` (Deg).""" + A = values[0].A if values else Atoms() + L = {} + 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] diff --git a/src/symident/sym/exact.py b/src/symident/sym/exact.py index 192a648..0f489ee 100644 --- a/src/symident/sym/exact.py +++ b/src/symident/sym/exact.py @@ -184,12 +184,16 @@ def parts(x): return e.func(*[_split_powers(a, atoms) for a in e.args]) +# the regimes of many conditions repeat an identity: each distinct one is decided once +@functools.lru_cache(maxsize=1 << 14) def _zero(e): """True or False when `e` cancels to zero or not over Q; None past the caps or where it is open. A nonzero value modulo a prime shows it nonzero; a numerator that expands to zero shows it zero. Powers with symbolic exponents and exponentials are split into powers of independent atoms first, so that x**(2*n) and x**n meet as a square.""" + if e == 0: + return True if spy.count_ops(e) > SIZE_CAP: return None if _nonzero_at_a_point(e): @@ -226,6 +230,12 @@ def _zero_split(e): return True if not v else (None if opaque else False) +@functools.lru_cache(maxsize=1 << 16) +def _free(e): + """The free symbols of `e`, read once per expression: the equations of a regime meet every check.""" + return frozenset(e.free_symbols) + + class _Field: """A field as SymPy expressions with the derivation of the field.""" @@ -234,7 +244,8 @@ def __init__(self, field): def __call__(self, e): """Y(e): the derivative of `e` along the field.""" - return sum((v * spy.diff(e, k) for k, v in self.c.items() if k in e.free_symbols), spy.Integer(0)) + fs = _free(e) + return sum((v * spy.diff(e, k) for k, v in self.c.items() if k in fs), spy.Integer(0)) def at(self, s): """The component on the symbol `s`.""" @@ -249,14 +260,23 @@ def _rhs(lines): return out +@functools.lru_cache(maxsize=1 << 14) +def _rhs_of(lines): + """_rhs() of a tuple of lines, parsed once: the regimes of many conditions repeat in every check.""" + return _rhs(lines) + + def regime_identities(regime, field, skip=()): - """(label, expression) of [Y, F] per state but `skip` and per constant coordinate, and Y(h) per observable.""" + """(label, expression) of [Y, F] per state but `skip` and per constant coordinate, and Y(h) per observable. + + A state off the field whose equation holds no coordinate of the field has the identity 0 = 0 and is left out.""" Y = _Field(field) - F = _rhs(regime["f"]) + F = _rhs_of(tuple(str(x) for x in regime["f"])) + moved = {k for k, v in Y.c.items() if v != 0} skip = {spy.Symbol(str(x)) for x in skip} out = [] for x, fx in F.items(): - if x in 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), @@ -268,7 +288,8 @@ def regime_identities(regime, field, skip=()): spy.Integer(0)))) for line in regime["g"]: h = _expr(str(line).split("=", 1)[1]) if "=" in str(line) else _expr(str(line)) - out.append((f"Y({h})", Y(h))) + if h.free_symbols & moved: + out.append((f"Y({h})", Y(h))) return out @@ -462,6 +483,10 @@ def _implicit_lift(Y, xs, sol): return dict(zip(xs, J.LUsolve(rhs))) +# states past which no linear lift xi = G x is solved for: G has their square of unknowns +_LINEAR_LIFT_CAP = 64 + + def linear_lift(field, regime, ic_lines, states): """`field` with state components xi = G x for a regime linear in the states, or None. @@ -473,12 +498,19 @@ def linear_lift(field, regime, ic_lines, states): if not xs or any(x in Y.c for x in xs): return None n = len(xs) - G = spy.Matrix(n, n, lambda i, j: spy.Symbol(f"_g{i}_{j}")) try: - M = spy.Matrix([[spy.diff(F[a], b) for b in xs] for a in xs]) - if any(_zero(F[a] - sum((M[i, j] * xs[j] for j in range(n)), spy.Integer(0))) is not True - for i, a in enumerate(xs)): + # the Jacobian row by row, each equation checked linear before the next: a nonlinear one ends the search + col = {x: j for j, x in enumerate(xs)} + M = spy.zeros(n, n) + for i, a in enumerate(xs): + on = F[a].free_symbols & set(xs) + for b in on: + M[i, col[b]] = spy.diff(F[a], b) + if _zero(F[a] - sum((M[i, col[b]] * b for b in on), spy.Integer(0))) is not True: + return None + if n > _LINEAR_LIFT_CAP: return None + G = spy.Matrix(n, n, lambda i, j: spy.Symbol(f"_g{i}_{j}")) eqs = list(spy.Matrix([[Y(M[i, j]) for j in range(n)] for i in range(n)]) + M * G - G * M) xi = G * spy.Matrix(xs) for line in regime["g"]: diff --git a/src/symident/sym/msolve.py b/src/symident/sym/msolve.py index 0d9f552..fccc269 100644 --- a/src/symident/sym/msolve.py +++ b/src/symident/sym/msolve.py @@ -10,7 +10,6 @@ from ..install import find_msolve from .gfpoly import _dp_coeffs, _dp_subst_rat, _dp_value, _gf_roots, note_branch -_MSOLVE_TIMEOUT = 600 _MSOLVE_THREADS = 1 @@ -18,17 +17,6 @@ class MsolveMissingError(RuntimeError): """Raised when the msolve executable is not available.""" -@contextlib.contextmanager -def msolve_timeout(seconds): - """Time limit of one msolve call in seconds within the block.""" - global _MSOLVE_TIMEOUT - old, _MSOLVE_TIMEOUT = _MSOLVE_TIMEOUT, seconds - try: - yield - finally: - _MSOLVE_TIMEOUT = old - - @contextlib.contextmanager def msolve_threads(n): """Threads of one msolve call within the block, for a call that runs alone.""" @@ -79,10 +67,12 @@ def _const_reduce(dps, nv, p): def _msolve_points(polys, vars_idx, p): - """Interior points of `polys` over GF(p) as a list of {index: value}, or a fail-dict.""" + """Interior points of `polys` over GF(p) as a list of {index: value}, or a fail-dict, also for a system past the + caps of msolve (detection.work.CAPS).""" import ast - import subprocess import tempfile + + from ..detection import work names = {i: "x%d" % i for i in vars_idx} def pstr(d): @@ -94,16 +84,18 @@ def pstr(d): eqs = [pstr(d) for d in polys] + ["w*" + "*".join(names[i] for i in vars_idx) + "-1"] vs = [names[i] for i in vars_idx] + ["w"] + 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} 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: fh.write(", ".join(vs) + "\n" + str(p) + "\n" + ",\n".join(eqs) + "\n") - try: - r = subprocess.run([_msolve_binary(), "-f", fi, "-o", fo, "-P", "1", "-t", str(_MSOLVE_THREADS)], - capture_output=True, text=True, timeout=_MSOLVE_TIMEOUT) - except subprocess.TimeoutExpired: - session.note("limits", f"msolve: a resting state was not solved within {_MSOLVE_TIMEOUT:g} s") - raise + 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} txt = "" if os.path.exists(fo): with open(fo) as fh: diff --git a/src/symident/sym/numfield.py b/src/symident/sym/numfield.py new file mode 100644 index 0000000..c5c40ad --- /dev/null +++ b/src/symident/sym/numfield.py @@ -0,0 +1,198 @@ +"""Exact arithmetic in a number field Q[s]/(W(s)), W monic over Z, and the cycle types of the Frobenius elements of +the splitting field of a polynomial over it at primes of degree one (Dedekind).""" + +import math +from fractions import Fraction + +import sympy as spy +from sympy.polys.domains import ZZ +from sympy.polys.galoistools import gf_ddf_zassenhaus, gf_diff, gf_gcd, gf_monic + + +class NumberField: + """Q[s]/(W(s)) for a monic irreducible W over Z; elements are tuples of Fractions, the coefficients of + 1, s, ..., s^(d-1).""" + + def __init__(self, w): + """`w`: the integer coefficients of an irreducible polynomial in t, lowest degree first; s = lc(w) t makes it + monic over Z.""" + w = [int(c) for c in w] + while len(w) > 1 and w[-1] == 0: + w.pop() + self.d = len(w) - 1 + self.lc = w[-1] + # W(s) = lc^(d-1) w(s / lc) + self.W = [c * self.lc ** (self.d - 1 - k) for k, c in enumerate(w[:-1])] + [1] if self.d else [1] + self.zero = (Fraction(0),) * max(self.d, 1) + self.one = (Fraction(1),) + (Fraction(0),) * (max(self.d, 1) - 1) + + def __repr__(self): + if self.d <= 1: + return "Q" + terms = [f"{c}*s^{k}" if k > 1 else f"{c}*s" if k == 1 else str(c) for k, c in enumerate(self.W) if c] + return "Q[s]/(" + " + ".join(reversed(terms)).replace("+ -", "- ") + ")" + + def rational(self, c): + return (Fraction(c),) + (Fraction(0),) * (max(self.d, 1) - 1) + + def from_t(self, coeffs): + """The element of a polynomial in t (lowest degree first), with t = s / lc.""" + acc = [Fraction(0)] * max(len(coeffs), 1) + for k, c in enumerate(coeffs): + acc[k] = Fraction(c) / Fraction(self.lc) ** k + return self._reduce(acc) + + def _reduce(self, a): + d = self.d + if d == 0: + return (Fraction(a[0]) if a else Fraction(0),) + 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)),) + a = list(a) + [Fraction(0)] * max(0, d - len(a)) + for k in range(len(a) - 1, d - 1, -1): + c = a[k] + if c: + for j in range(d): + a[k - d + j] -= c * self.W[j] + a[k] = Fraction(0) + return tuple(a[:d]) + + def add(self, a, b): + return tuple(x + y for x, y in zip(a, b)) + + def sub(self, a, b): + return tuple(x - y for x, y in zip(a, b)) + + def neg(self, a): + return tuple(-x for x in a) + + def scale(self, a, c): + return tuple(x * c for x in a) + + def mul(self, a, b): + if len(a) == 1: + return (a[0] * b[0],) + out = [Fraction(0)] * (len(a) + len(b) - 1) + for i, x in enumerate(a): + if x: + for j, y in enumerate(b): + if y: + out[i + j] += x * y + return self._reduce(out) + + def inv(self, a): + if not any(a): + raise ZeroDivisionError("inverse of zero in a number field") + if len(a) == 1: + return (1 / a[0],) + s = spy.Symbol("s") + A = spy.Poly(list(reversed([spy.Rational(x.numerator, x.denominator) for x in a])), s, domain="QQ") + W = spy.Poly(list(reversed(self.W)), s, domain="QQ") + r = A.invert(W).all_coeffs() + return self._reduce([Fraction(int(c.p), int(c.q)) for c in reversed(r)]) + + def is_zero(self, a): + return not any(a) + + def residue(self, a, p, tau): + """The image of `a` modulo the prime (p, s - tau); None where p divides a denominator.""" + acc = 0 + for c in reversed(a): + if c.denominator % p == 0: + return None + acc = (acc * tau + c.numerator * pow(c.denominator, -1, p)) % p + return acc + + def primes_of_degree_one(self, p): + """The roots tau of W modulo p, one prime (p, s - tau) of degree one each, where W is square-free modulo p + (so p is unramified in the field); [] otherwise.""" + if self.d <= 1: + return [0] + Wp = [c % p for c in reversed(self.W)] + if gf_gcd(Wp, gf_diff(Wp, p, ZZ), p, ZZ) != [1]: + return [] + return _roots_mod(self.W, 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 + + +def charpoly(K, A): + """The coefficients of det(z I - A) over the number field K, highest degree first, by Faddeev and LeVerrier: only + products in K and divisions by integers.""" + n = len(A) + c = [K.one] + M = [[K.zero] * n for _ in range(n)] + for k in range(1, n + 1): + # M_k = A M_{k-1} + c_{k-1} I, c_k = -tr(A M_k) / k + AM = [[_dot(K, A[i], [M[r][j] for r in range(n)]) for j in range(n)] for i in range(n)] + M = [[K.add(AM[i][j], c[-1]) if i == j else AM[i][j] for j in range(n)] for i in range(n)] + tr = K.zero + for i in range(n): + tr = K.add(tr, _dot(K, A[i], [M[r][i] for r in range(n)])) + c.append(K.scale(tr, Fraction(-1, k))) + return c + + +def charpoly_mod(A, p): + """The coefficients of det(z I - A) over GF(p), highest degree first, for an integer matrix A and p above the + size of A (Faddeev and LeVerrier).""" + n = len(A) + c = [1] + M = [[0] * n for _ in range(n)] + for k in range(1, n + 1): + AM = [[sum(A[i][r] * M[r][j] for r in range(n)) % p for j in range(n)] for i in range(n)] + M = [[(AM[i][j] + c[-1]) % p if i == j else AM[i][j] for j in range(n)] for i in range(n)] + tr = sum(A[i][r] * M[r][i] for i in range(n) for r in range(n)) % p + c.append(-tr * pow(k, -1, p) % p) + return c + + +def _dot(K, row, col): + acc = K.zero + for a, b in zip(row, col): + if any(a) and any(b): + acc = K.add(acc, K.mul(a, b)) + return acc + + +def cycle_type(coeffs, p): + """The degrees of the irreducible factors over GF(p) of a monic polynomial (coefficients mod p, highest degree + first), in decreasing order; None where it is not square-free modulo p.""" + f = gf_monic([int(c) % p for c in coeffs], p, ZZ)[1] + if len(f) <= 2: + return [1] * (len(f) - 1) + if gf_gcd(f, gf_diff(f, p, ZZ), p, ZZ) != [1]: + return None + out = [] + for g, d in gf_ddf_zassenhaus(f, p, ZZ): + out += [int(d)] * ((len(g) - 1) // int(d)) + return sorted(out, reverse=True) + + +def order_of(ctype): + """The order of a permutation of this cycle type.""" + return math.lcm(*ctype) if ctype else 1 + + +def rank_over_q(vectors): + """The rank of a list of rational vectors over Q, by exact elimination.""" + rows = [list(v) for v in vectors] + rank, cols = 0, len(rows[0]) if rows else 0 + for c in range(cols): + piv = next((i for i in range(rank, len(rows)) if rows[i][c]), None) + if piv is None: + continue + rows[rank], rows[piv] = rows[piv], rows[rank] + for i in range(len(rows)): + if i != rank and rows[i][c]: + f = rows[i][c] / rows[rank][c] + rows[i] = [x - f * y for x, y in zip(rows[i], rows[rank])] + rank += 1 + return rank diff --git a/src/symident/sym/restcheck.py b/src/symident/sym/restcheck.py index 034c037..0eac0f8 100644 --- a/src/symident/sym/restcheck.py +++ b/src/symident/sym/restcheck.py @@ -1,48 +1,48 @@ """Whether the resting balances have a solution, and one in the declared domain, at random parameter values.""" +import math import os import re -import subprocess import tempfile from fractions import Fraction import sympy as spy from .. import session -from ..errors import SYMPY_FAILS, InputError +from ..errors import SYMPY_FAILS, InputError, sympy_fail from .parse import _make_local_parse -# the check runs on systems up to this many resting states, each msolve call up to this many seconds +# the check runs on systems up to this many resting states, each msolve call within the short caps of work.CAPS _MAX_STATES = 12 -_TIMEOUT = 10.0 _POINTS = 3 -def _run_msolve(names, eqs, timeout): - """The parsed msolve output over Q for `eqs` in `names`, or None on failure or timeout.""" +def _run_msolve(names, eqs): + """The parsed msolve output over Q for `eqs` in `names`, or None on failure or past the short caps of msolve + (work.quick_msolve()).""" + from ..detection import work from .msolve import MsolveMissingError, _msolve_binary try: exe = _msolve_binary() except MsolveMissingError: return None - 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: - fh.write(",".join(names) + "\n0\n" + ",\n".join(eqs) + "\n") - try: - r = subprocess.run([exe, "-f", fi, "-o", fo, "-t", "1"], capture_output=True, text=True, - timeout=timeout) - except subprocess.TimeoutExpired: + with work.quick_msolve(): + if work.msolve_too_large(names, eqs): return None - if r.returncode != 0 or not os.path.exists(fo): - return None - with open(fo) as fh: - txt = fh.read().strip().rstrip(":") + 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: + fh.write(",".join(names) + "\n0\n" + ",\n".join(eqs) + "\n") + r = work.run_msolve([exe, "-f", fi, "-o", fo, "-t", "1"]) + if r.returncode != 0 or not os.path.exists(fo): + return None + with open(fo) as fh: + txt = fh.read().strip().rstrip(":") if not txt: return None - txt = re.sub(r"(-?\d+)\s*/\s*2\^(\d+)", r"Fraction(\1, 2**\2)", txt) + from ..detection.discrete import parse_rational try: - return eval(txt, {"Fraction": Fraction, "__builtins__": {}}) + return parse_rational(txt) except (SyntaxError, ValueError, TypeError, NameError): return None @@ -82,7 +82,92 @@ def _positive_names(positive): return {str(p) for p in positive if re.fullmatch(r"[A-Za-z_.][A-Za-z0-9_.]*", str(p))} -def rest_check(multi, zero_of, positive, points=_POINTS, timeout=_TIMEOUT): +def _cleared(e, gens): + """The numerator and the denominator of `e` as polynomials in `gens` with coprime integer coefficients.""" + num, den = spy.fraction(spy.together(e)) + out = [] + for q in (num, den): + P = spy.Poly(spy.expand(q), *gens, domain="QQ") + if P.is_zero: + out.append(P) + continue + _, P = P.clear_denoms(convert=True) + out.append(P.primitive()[1]) + return out + + +def modular_decision(eqs, unknowns, pos, rng, draws=_POINTS): + """{"exists", "bound", "draws"} of the resting balances `eqs` in `unknowns` over Q(theta) + (docs/method/conditions.rst, "Resting states"): "proven" where a simple point modulo the count prime at an integer + point lifts by Hensel's lemma, "no" with the probability `bound` of a resting state for generic parameter values + where none exists modulo the prime at every point drawn, else "open".""" + 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] + th = sorted(set().union(*[e.free_symbols for e in eqs]) - set(xs), key=str) + gens = th + xs + nums, dens = [], [] + for e in eqs: + n, d = _cleared(e, gens) + if not n.is_zero: + nums.append(n) + if not d.is_ground: + dens.append(d) + deg_theta = [n.total_degree() for n in nums] + [1 + sum(d.total_degree() for d in dens)] + 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 + Dt = math.prod(max(1, int(d)) for d in deg_theta) + bound, verdicts = 1.0, [] + for _ in range(draws): + at = {} + for s in th: + v = rng.randint(1, M) + at[s] = spy.Integer(-v if not (pos is True or str(s) in pos) and rng.random() < 0.5 else v) + polys = [spy.Poly(n.as_expr().xreplace(at).xreplace(ren), *[spy.Symbol(x) for x in names]) for n in nums] + den = spy.prod([d.as_expr().xreplace(at).xreplace(ren) for d in dens]) if dens else spy.Integer(1) + if den == 0: + verdicts.append("open") + continue + w = spy.Poly(spy.Symbol("si_w") * den - 1, *[spy.Symbol(x) for x in names], spy.Symbol("si_w")) + whole = all(not q.is_zero for q in polys) + polys = [q for q in polys if not q.is_zero] + if any(q.is_ground for q in polys): + # a nonzero constant balance: no solution at this point over the complex numbers + bound *= Dt / M + verdicts.append("no") + continue + p = PRIMES[0] + text = [str(q.as_expr()).replace("**", "^").replace(" ", "") for q in polys + [w]] + dims = [] + with work.quick_msolve(): + k = _gb_count(names, p, text, names, exact=True, dims=dims) + if k == 0: + # none modulo p; the empty set over Q at the point decides, without a bad prime + data = _run_msolve(names + ["si_w"], text) + if data is not None and data[0] == -1: + bound *= Dt / M + 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]): + # as many distinct values as the dimension of the quotient, no equation zero modulo p: every point is simple + verdicts.append("proven") + else: + verdicts.append("open") + if "proven" in verdicts: + return {"exists": "proven", "bound": None, "draws": verdicts} + if verdicts and all(v == "no" for v in verdicts): + return {"exists": "no", "bound": bound if bound < 1 else None, "draws": verdicts} + return {"exists": "open", "bound": None, "draws": verdicts} + + +def rest_check(multi, zero_of, positive, points=_POINTS): """{"points", "consistent", "in_domain", "undecided", "checked"} of the resting balances at random parameter values: an InputError where the balances have no solution over the complex numbers at any of them.""" systems = _systems(multi, zero_of) @@ -96,7 +181,8 @@ def rest_check(multi, zero_of, positive, points=_POINTS, timeout=_TIMEOUT): 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"} + "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" @@ -138,7 +224,7 @@ def rest_check(multi, zero_of, positive, points=_POINTS, timeout=_TIMEOUT): names = names + ["xw"] # msolve reads expanded polynomials without spaces polys = [str(spy.expand(q)).replace("**", "^").replace(" ", "") for q in polys] - data = _run_msolve(names, polys, timeout) + data = _run_msolve(names, polys) if data is None: from .msolve import MsolveMissingError, _msolve_binary try: @@ -172,13 +258,26 @@ def rest_check(multi, zero_of, positive, points=_POINTS, timeout=_TIMEOUT): report["in_domain"] += 1 elif "out" not in states: report["undecided"] += 1 - if report["points"] and not report["consistent"]: + try: + decisions = [modular_decision(eqs, unknowns, pos, rng) for eqs, unknowns in systems] + except SYMPY_FAILS + (ValueError,) as exc: + sympy_fail(exc) + decisions = [] + 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 + 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") + 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, " - "so the model has no resting state for generic parameters; check the right-hand sides, " - "the inputs at rest and the conserved totals") + 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/scaling.py b/src/symident/sym/scaling.py index 7a9cedb..1f55439 100644 --- a/src/symident/sym/scaling.py +++ b/src/symident/sym/scaling.py @@ -129,6 +129,20 @@ def rec(e): return rec(_hyp_to_exp(expr)), exps +def _power_atoms(exprs, states, frozen): + """{x**e: fresh symbol} for powers of a coordinate x with a non-numeric exponent e free of the states; under a + scaling such a power has the weight e times the weight of x.""" + out = {} + for e in exprs: + for at in spy.sympify(e).atoms(spy.Pow): + if at in out or at.exp.is_number or not at.base.is_Symbol or str(at.base) in frozen: + continue + if at.exp.free_symbols & states: + continue + out[at] = spy.Symbol('_P%d_%s' % (len(out), at.base)) + return out + + def _scaling_rows(diff_equations, obs_functions, m, zvars, logs=False, seen=None): """(rows, skipped): sparse monomial-exponent rows of one (f, g) system for the scaling kernel.""" skipped = 0 @@ -214,7 +228,7 @@ def _weighted_degree(e, w): return w.get(str(e), 0) if e.is_Add: ds = [_weighted_degree(a, w) for a in e.args] - return ds[0] if None not in ds and len(set(ds)) == 1 else None + return ds[0] if None not in ds and len({spy.expand(d) for d in ds}) == 1 else None if e.is_Mul: tot = 0 for a in e.args: @@ -228,14 +242,18 @@ def _weighted_degree(e, w): db = _weighted_degree(b, w) if x.is_Number: return None if db is None else db * x - return 0 if db == 0 and _weighted_degree(x, w) == 0 else None + # (lam^d b)^x = lam^(d x) b^x for lam > 0 on the principal branch + return None if db is None or _weighted_degree(x, w) != 0 else spy.expand(db * x) if e.args: return 0 if all(_weighted_degree(a, w) == 0 for a in e.args) else None return None -def verify_scalings(scalings, tapes): - """One bool per scaling: whether it leaves every tape's equations, observables, values and events invariant.""" +def verify_scalings(scalings, tapes, shifts=()): + """One bool per scaling: whether it leaves every tape's equations, observables, values and events invariant. + + Weights may be symbolic in coordinates the scaling leaves fixed. A coordinate in `shifts` (the logarithm of a + 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', [])) @@ -269,15 +287,24 @@ def split(line): checks = list(dict.fromkeys(checks)) syms = [{str(x) for x in e.free_symbols} for e, _ in checks] out = [] + shifts = set(shifts) for sc in scalings: - w = {str(k): spy.Rational(str(v)) for k, v in dict(sc).items()} + w = {str(k): spy.sympify(parse(str(v))) for k, v in dict(sc).items()} sup = {k for k, v in w.items() if v != 0} - ok = True + moved = sup & shifts + ok = all(not ({str(x) for x in w[k].free_symbols} & sup) for k in sup) for (e, target), es in zip(checks, syms): + if not ok: + break if e == 0: # zero has every weight continue + if es & moved: + if target in moved and e.is_Symbol and str(e) == target: + continue + ok = False + break d = _weighted_degree(e, w) if es & sup else 0 - if d is None or d != (w.get(target, 0) if target else 0): + 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' % @@ -323,7 +350,7 @@ def _scaling_gens_recast(gens, znames, nz, recast): # 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['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 @@ -440,8 +467,9 @@ def scaling_symmetries_per_condition(per_cond_model, per_cond_obs, inputs=None, def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=None, - recast=None, logs=False, extra_model=None, extra_obs=None): - """Scaling symmetries common to every condition; `inputs` and `fixed` do not scale.""" + 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] per_cond_obs = [_as_list(o) for o in per_cond_obs] extra_model = [_as_list(m) for m in (extra_model or [[] for _ in per_cond_model])] @@ -489,10 +517,22 @@ 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 {} + 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()] 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 _as_list(recast): + 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): @@ -530,19 +570,26 @@ def scaling_symmetries_multi(per_cond_model, per_cond_obs, inputs=None, fixed=No 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} for j in range(nz): - if znames[j] in fixedset: + if znames[j] in fixedset or znames[j] in in_exp: row = [0] * nz row[j] = 1 dense.append(row) gens = _scaling_gens(dense, nz) # the integer kernel treats each recast E as free; recover the symbolic-weight scalings - recast = _as_list(recast) if recast: physical = _scaling_gens_recast(gens, znames, nz, recast) non_id = _scaling_nonid(physical, znames, nz) else: non_id = _scaling_nonid(gens, znames, nz) + 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': znames, 'skipped': skipped} + '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 new file mode 100644 index 0000000..f92915c --- /dev/null +++ b/src/symident/sym/shared.py @@ -0,0 +1,437 @@ +"""One tape for conditions that differ only in the values of symbols: the model is compiled once over +placeholders, and each condition gives the placeholders as leaf values (a number or another leaf).""" + +import collections +import re +from fractions import Fraction + +import numpy as np +import sympy as spy + +from ..errors import SYMPY_FAILS, sympy_fail + +_NUM = re.compile(r"^\(?\s*(-?\d+)\s*(?:/\s*(\d+))?\s*\)?$") +_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") +_LINE_KEYS = ("model_lines", "obs_lines", "ver_ic", "jet_f", "jet_g", "jet_ic") + + +def _value(v): + """A substitution value as a Fraction or a symbol name, None for anything else.""" + v = str(v).strip() + m = _NUM.match(v) + if m: + return Fraction(int(m.group(1)), int(m.group(2) or 1)) + return v if _SYM.match(v) else None + + +def _text(v): + return v if isinstance(v, str) else "(%d/%d)" % (v.numerator, v.denominator) + + +class _Zeroed: + """The symbols of an expression after the placeholders that are 0 vanish, as SymPy evaluates a product with a + factor 0 and a sum with a term 0.""" + + def __init__(self, e, ph): + self.tree = self._node(e, ph) + + def _node(self, e, ph): + if e.is_Symbol: + return ("p", str(e)) if str(e) in ph else ("s", str(e)) + if e.is_Number: + return ("z",) if e == 0 else ("c",) + if e.is_Add or e.is_Mul: + return ("+" if e.is_Add else "*", [self._node(x, ph) for x in e.args]) + if e.is_Pow and e.exp.is_Integer and e.exp > 0: + return ("*", [self._node(e.base, ph)]) + # any other function keeps every symbol, also of a zero placeholder + return ("f", sorted(str(s) for s in e.free_symbols)) + + 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": + return {n[1]} + if k == "p": + v = val[n[1]] + if isinstance(v, str): + return {v} + return None if v == 0 else set() + if k == "z": + return None + 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))} + parts = [go(x) for x in n[1]] + if k == "*": + if any(p is None for p in parts): + return None + 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) + + +def _eligible(kw): + """Whether the conditions differ only in the values of symbols and nothing in them needs a tape per condition.""" + K = len(kw.get("condition_subs") or []) + if K < 2 or kw.get("equilibrate") or kw.get("joint_steady_state") or kw.get("forcings"): + return False + if any(kw.get("seg_equilibrate") or []) or kw.get("condition_chain") is not None: + return False + if any(kw.get("condition_events") or []) or any(kw.get("condition_t0_events") or []): + return False + if kw.get("condition_times") is not None and any(t is not None for t in kw["condition_times"]): + return False + if any(dict(d or {}) for d in (kw.get("condition_rest_subs") or [])): + return False + if kw.get("held_state_params") or kw.get("joint_fixed_states"): + return False + ic0 = [dict(d) for d in (kw.get("condition_ic0") or [])] + return len(ic0) == K and all(d == ic0[0] for d in ic0) + + +def shared_tape_compile(compile_fn, kw): + """compile_fn(**kw) as one compile of the model over placeholders, the tape of each condition holding the + values of the placeholders as the leaves it sets; None where the conditions do not allow it.""" + if not _eligible(kw): + return None + subs = [{str(k): str(v) for k, v in dict(d).items()} for d in kw["condition_subs"]] + K = len(subs) + keys = sorted(set().union(*subs)) + vals = {} + for k in keys: + col = [_value(d.get(k, k)) for d in subs] + if any(v is None for v in col): + return None + vals[k] = col + varying = [k for k in keys if len(set(vals[k])) > 1] + observation = list(kw.get("observation") or []) + cobs = list(kw.get("condition_obs") or []) + obs = [list(cobs[c]) if c < len(cobs) and cobs[c] is not None else observation for c in range(K)] + if len({len(o) for o in obs}) != 1: + return None + model = [str(x) for x in (kw.get("model") or [])] + states = {line.split("=", 1)[0].strip() for line in model} + ov = _observable_values(obs) + if ov is None: + return None + obs_val, obs_ids = ov + if any(a in states or a in vals for a in obs_ids): + return None + if not varying and not obs_ids: + return None + taken = set(_IDENT.findall("\n".join(model + [x for o in obs for x in o]))) | set(keys) + for k in keys: + taken |= {v for v in vals[k] if isinstance(v, str)} + ph = {} + for k in varying + obs_ids: + nm = k + "_sv" + while nm in taken: + nm += "_" + taken.add(nm) + ph[k] = nm + # the value of each placeholder per condition + pval = [{ph[k]: vals[k][c] for k in varying} for c in range(K)] + for c in range(K): + for a in obs_ids: + pval[c][ph[a]] = obs_val[c].get(a, a) + value_syms = sorted({v for d in pval for v in d.values() if isinstance(v, str)}) + if any(v in states for v in value_syms): + return None + # a value that is itself substituted in the condition would be substituted again + for c in range(K): + 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) + out = compile_fn(**kw1) + if not out.get("ok") or len(out.get("tapes") or []) != 1: + return None + if out.get("exp_relation") or out.get("power_recast") or out.get("recast_transient") or out.get("log_params"): + return None + tpl = out["tapes"][0] + op = np.asarray(tpl["op"], dtype=np.int64) + if np.any(op > 3) or tpl.get("ic_seed") is not None or tpl.get("constraint_model") is not None: + return None + nl, ns = int(out["n_leaves"]), int(out["n_states"]) + slot = {nm: i for i, nm in enumerate(out["leaf_names"])} + if any(v not in slot for v in value_syms): + return None + used = [nm for nm in sorted(ph.values()) if nm in slot] + if not _reciprocals_free_of(tpl, nl + ns, nl, {slot[nm] for nm in used}): + return None + parsed = _template_exprs(tpl) + if parsed is None: + return None + phs = set(ph.values()) + f_tr = {x: _Zeroed(e, phs) for x, e in parsed["f"].items()} + g_tr = [_Zeroed(e, phs) for e in parsed["g"]] + ic_tr = {x: _Zeroed(e, phs) for x, e in parsed["ic"].items()} + znames = list(out["znames"]) + pat = re.compile(r"\b(" + "|".join(sorted(map(re.escape, used), key=len, reverse=True)) + r")\b") if used else None + tapes, seen = [], set() + for c in range(K): + val = pval[c] + t = dict(tpl) + t["leaf_slot"] = [slot[nm] for nm in used] + t["leaf_src"] = [slot[val[nm]] if isinstance(val[nm], str) else -1 for nm in used] + t["leaf_num"] = ["0" if isinstance(val[nm], str) else str(val[nm].numerator) for nm in used] + t["leaf_den"] = ["1" if isinstance(val[nm], str) else str(val[nm].denominator) for nm in used] + if pat is not None: + txt = {nm: _text(val[nm]) for nm in used} + + 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]) + reach, syms = _reach(f_tr, g_tr, ic_tr, val) + seen |= syms + t["lie_reach"] = [int(reach.get(nm, -1)) for nm in znames] + tapes.append(t) + # a coordinate that every condition drops is no coordinate, as in a compile per condition + keep = [i for i, nm in enumerate(znames) if nm in seen] + if len(keep) < len(znames): + out["znames"] = [znames[i] for i in keep] + out["z_slots"] = [out["z_slots"][i] for i in keep] + for t in tapes: + t["lie_reach"] = [t["lie_reach"][i] for i in keep] + out["tapes"] = tapes + out["shared_tape"] = True + sg = _scaling_groups(tpl, [{nm: pval[c][nm] for nm in used} for c in range(K)]) + if sg is not None: + groups, canon = sg + out["scaling_groups"] = groups + # per group the lines with a nonzero number at 1 where no two terms meet: the same monomials and + # degrees, and lines that repeat between the groups + out["scaling_tapes"] = [] + for g, cv in zip(groups, canon): + t = {k: v for k, v in tapes[g[0]].items() if k.startswith("ver_")} + if pat is not None: + txt = {nm: _text(cv[nm]) for nm in used} + for key in ("model_lines", "obs_lines", "ver_ic"): + if tpl.get(key) is not None: + t[key] = [pat.sub(lambda m: txt[m.group(0)], str(x)) for x in tpl[key]] + out["scaling_tapes"].append(t) + return out + + +def _observable_values(obs): + """(per condition {identifier: value}, the identifiers) of the identifiers in which the observables `obs` of the + conditions differ, None where the observables are not one template.""" + tmpl = [(_IDENT.split(line), _IDENT.findall(line)) for line in obs[0]] + obs_val = [{} for _ in obs] + for c, lines in enumerate(obs): + for li, line in enumerate(lines): + seps, ids = _IDENT.split(line), _IDENT.findall(line) + if seps != tmpl[li][0] or len(ids) != len(tmpl[li][1]): + return None + for a, b in zip(tmpl[li][1], ids): + if a != b and obs_val[c].setdefault(a, b) != b: + return None + obs_ids = sorted(set().union(*[set(d) for d in obs_val])) + # every occurrence of an identifier that differs takes the value of the condition + for c, lines in enumerate(obs): + for li, line in enumerate(lines): + for a, b in zip(tmpl[li][1], _IDENT.findall(line)): + if a in obs_ids and b != obs_val[c].get(a, a): + return None + return obs_val, obs_ids + + +def _scaling_groups(tpl, pval): + """(groups, canonical values): the conditions whose expressions have the same monomials, None where unexpanded.""" + # no placeholder enters a denominator, so a value 0 drops a term, a symbol renames a factor and terms that meet + # add: equal zero patterns, symbols and vanishing sums give equal monomials and equal scaling rows + try: + exprs = [] + for key in ("model_lines", "obs_lines", "ver_ic"): + for line in tpl.get(key) or []: + num = spy.expand(spy.fraction(spy.together(spy.sympify(str(line).split("=", 1)[1])))[0]) + exprs.append(num) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + phs = set().union(*[set(v) for v in pval]) if pval else set() + terms = [] + for ei, num in enumerate(exprs): + for t in spy.Add.make_args(num): + c, rest = t.as_coeff_Mul() + pw = rest.as_powers_dict() + if not any(str(b) in phs for b in pw): + 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()})) + if any(c is None for _, c, _ in terms): + return None + # the terms of every expression without placeholders, which a renamed term may meet + plain = set() + for ei, num in enumerate(exprs): + for t in spy.Add.make_args(num): + _, rest = t.as_coeff_Mul() + pw = rest.as_powers_dict() + if not any(str(b) in phs for b in pw): + plain.add((ei, tuple(sorted((str(b), str(e)) for b, e in pw.items())))) + + 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): + pat = pattern(val) + if pat not in meets: + # the monomials of the terms after renaming, with a term at 0 left out; those that two terms share + mon = {} + for ti, (ei, _, pw) in enumerate(terms): + if any(isinstance(val.get(b), Fraction) and val[b] == 0 for b in pw): + continue + m = {} + for b, e in pw.items(): + v = val.get(b, b) + if isinstance(v, Fraction): + continue + m[v] = m.get(v, 0) + e + key = (ei, tuple(sorted((b, str(e)) for b, e in m.items()))) + mon.setdefault(key, []).append(ti) + meets[pat] = [(k, ts) for k, ts in mon.items() if len(ts) > 1 or k in plain] + vanish = [] + for gi, (k, ts) in enumerate(meets[pat]): + if k in plain: + # a sum with a term free of placeholders, whose coefficient is not kept: the values set the group + vanish.append((gi, tuple(str(val[b]) for ti in ts for b in terms[ti][2] if b in val))) + continue + tot = Fraction(0) + for ti in ts: + x = terms[ti][1] + for b, e in terms[ti][2].items(): + v = val.get(b) + if isinstance(v, Fraction): + 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()} + out.setdefault(key, []).append(c) + return list(out.values()), [canon[k] for k in out] + + +def _reciprocals_free_of(tpl, base, nl, slots): + """Whether no reciprocal of the tape reads a value that depends on the leaves `slots`.""" + dep = np.zeros(base + len(tpl["op"]), dtype=bool) + for s in slots: + dep[s] = True + ops, a, b = list(tpl["op"]), list(tpl["a"]), list(tpl["b"]) + for i, o in enumerate(ops): + if o == 0: + continue + if o == 3: + if dep[a[i]]: + return False + continue + dep[base + i] = bool(dep[a[i]] or (o in (1, 2) and dep[b[i]])) + ic_ops = list(tpl.get("ic_op") or []) + icd = np.zeros(nl + len(ic_ops), dtype=bool) + for s in slots: + icd[s] = True + for i, o in enumerate(ic_ops): + ai, bi = tpl["ic_a"][i], tpl["ic_b"][i] + if o == 0: + continue + if o != 1 and o != 2 and icd[ai]: + return False + icd[nl + i] = bool(icd[ai] or (o in (1, 2) and icd[bi])) + return True + + +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 []] + if not g: + g = list(rhs(tpl.get("obs_lines")).values()) + ic = rhs(tpl.get("jet_ic") or tpl.get("ver_ic")) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + return {"f": f, "g": g, "ic": ic} + + +def _reach(f_tr, g_tr, ic_tr, val): + """(_lie_reach of one condition, the symbols of the expressions of the condition) with the placeholders at + `val`.""" + rhs = {x: (tr.symbols(val) or set()) for x, tr in f_tr.items()} + syms = set().union(*rhs.values()) if rhs else set() + dist = {} + queue = collections.deque() + for tr in g_tr: + s = tr.symbols(val) or set() + syms |= s + for x in sorted(s): + if x not in dist: + dist[x] = 0 + queue.append(x) + while queue: + u = queue.popleft() + for s in rhs.get(u, ()): + if s not in dist: + dist[s] = dist[u] + 1 + queue.append(s) + out = dict(dist) + for x, tr in ic_tr.items(): + s = tr.symbols(val) or set() + syms |= s + if x in dist: + for y in s: + if dist[x] < out.get(y, 10 ** 9): + out[y] = dist[x] + return out, syms + + +def kernel_tapes(tapes): + """The tapes for a kernel call: a tape that holds the same kernel arrays as an earlier one names that one as + `base` and gives only the leaves it sets.""" + tapes = list(tapes) + if not any("leaf_slot" in t for t in tapes): + return tapes + first, out = {}, [] + for i, t in enumerate(tapes): + if "leaf_slot" not in t: + out.append(t) + continue + key = tuple(id(t.get(k)) for k in _KERNEL_KEYS) + j = first.get(key) + if j is None: + 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"]}) + return out diff --git a/src/symident/sym/supportlift.py b/src/symident/sym/supportlift.py new file mode 100644 index 0000000..9484c8d --- /dev/null +++ b/src/symident/sym/supportlift.py @@ -0,0 +1,381 @@ +"""State components of a parameter direction on the states it reaches, solved modulo a prime. + +The identities [Y, F] = 0, Y(h) = 0 and xi(x0) = Y(x0) of a field Y are linear in the state components. +An ansatz of components on a support of states, grown along the readers of the states, is solved at a +random point modulo a prime; the components are then read over Q and proven by the identities.""" + +import random + +import numpy as np +import sympy as spy +from sympy.polys.matrices import DomainMatrix + +from ..errors import SYMPY_FAILS, InapplicableError, sympy_fail +from ..gfp import PRIMES, rref_modp +from .exact import _expr, _rhs, _rhs_of +from .linalg import _rational_reconstruct + +# steps of growth of the support along the readers of the states in it, and the states past which no lift is +# sought +_GROWTH = 6 +_SUPPORT_CAP = 200 +# unknowns of one linear system +_UNKNOWN_CAP = 600 +# sample points beyond the unknowns of an identity, so that the samples fix the identity +_EXTRA_POINTS = 4 +# states of the support up to which quadratic components are tried +_QUADRATIC_STATES = 12 +# unknowns up to which the solution is solved over the rational functions of the parameters +_SYMBOLIC_UNKNOWNS = 8 + + +def _inverse(a, p): + """Elementwise inverse of the residues `a` modulo p.""" + if np.any(a % p == 0): + raise ZeroDivisionError("a pole at the sample point") + out, b, e = np.ones_like(a), a % p, p - 2 + while e: + if e & 1: + out = out * b % p + b = b * b % p + e >>= 1 + return out + + +class _Residues: + """Values modulo p of rational expressions at n points; states vary per point, other symbols hold one value.""" + + def __init__(self, states, n, p, seed, high=None): + self.states, self.n, self.p = states, n, p + self.rng = random.Random(seed) + self.high = high or p + self.vals, self.memo = {}, {} + + def symbol(self, s): + v = self.vals.get(s) + if v is None: + k = self.n if s in self.states else 1 + draw = [self.rng.randrange(2, self.high) for _ in range(k)] + v = np.array(draw * (self.n if k == 1 else 1), dtype=np.int64) % self.p + self.vals[s] = v + return v + + def __call__(self, e): + r = self.memo.get(e) + if r is not None: + return r + p, n = self.p, self.n + if e.is_Rational: + if int(e.q) % p == 0: + raise ZeroDivisionError("a denominator divisible by the prime") + r = np.full(n, int(e.p) % p * pow(int(e.q), -1, p) % p, dtype=np.int64) + elif e.is_Symbol: + r = self.symbol(e) + elif e.is_Add or e.is_Mul: + r = np.zeros(n, dtype=np.int64) if e.is_Add else np.ones(n, dtype=np.int64) + for a in e.args: + r = (r + self(a)) % p if e.is_Add else r * self(a) % p + elif e.is_Pow and e.exp.is_Integer: + b, k = self(e.base), int(e.exp) + if k < 0: + b, k = _inverse(b, p), -k + r = np.ones(n, dtype=np.int64) + while k: + if k & 1: + r = r * b % p + b = b * b % p + k >>= 1 + else: + raise InapplicableError(f"not rational: {e}") + self.memo[e] = r + return r + + +def _ansatz(S, reads, readers, level): + """Monomials, as tuples of (state, exponent), of the component of each state of the support: a constant and + the state itself, at level 1 the states of the support next to it, at level 2 their products.""" + out = {} + for i in sorted(S, key=str): + near = sorted(((reads[i] | readers.get(i, set())) & S) - {i}, key=str) + ms = [(), ((i, 1),)] + if level >= 1: + 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:]] + out[i] = list(dict.fromkeys(ms)) + return out + + +class _Problem: + """The identities of a lift with parameter components `theta` on the states of the regime `F`.""" + + def __init__(self, theta, F, obs, x0): + self.theta, self.F, self.obs, self.x0 = theta, F, obs, x0 + self.moved = set(theta) + self.reads = {x: f.free_symbols for x, f in F.items()} + self.readers = {} + for x, r in self.reads.items(): + for s in r & F.keys(): + self.readers.setdefault(s, set()).add(x) + self.diffs = {} + + def d(self, e, s): + key = (e, s) + if key not in self.diffs: + self.diffs[key] = spy.diff(e, s) + return self.diffs[key] + + def identities(self, S): + """(kind, state, expression, the states of S it reads): [Y, F] per state of S or reading S or a parameter + moved, Y(h) per output reading them, and the start of each state of S with an initial value.""" + out, touched = [], S | self.moved + for l, f in self.F.items(): + if l in S or self.reads[l] & touched: + out.append(("F", l, f, self.reads[l] & S)) + for h in self.obs: + if h.free_symbols & touched: + out.append(("h", None, h, h.free_symbols & S)) + for i in sorted(S, key=str): + if i in self.x0: + out.append(("x0", i, self.x0[i], {i})) + return out + + def _at_x0(self, m): + """The monomial m at the start, None where a state of m has no initial value.""" + if any(j not in self.x0 for j, _ in m): + return None + return spy.Mul(*[self.x0[j] ** e for j, e in m]) + + def _theta_part(self, f, V): + """Y(f) of the parameter components at the points of V.""" + p = V.p + out = np.zeros(V.n, dtype=np.int64) + for s in f.free_symbols & self.moved: + out = (out + V(self.theta[s]) * V(self.d(f, s))) % p + return out + + def rows(self, S, mons, cols, V): + """(identity, {column: values at the points of V}, right-hand side) over the unknowns `cols`.""" + p, n = V.p, V.n + mval = {} + + def mono(m): + if m not in mval: + r = np.ones(n, dtype=np.int64) + for j, e in m: + for _ in range(e): + r = r * V(j) % p + mval[m] = r + return mval[m] + + def flux(m): + r = np.zeros(n, dtype=np.int64) + 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 + block = {} + if kind == "x0": + at = [self._at_x0(m) for m in mons[l]] + if any(v is None for v in at): + continue + for m, v in zip(mons[l], at): + if (l, m) in cols: + block[cols[(l, m)]] = V(v) + out.append((ident, block, self._theta_part(f, V))) + continue + for i in ins: + Ji = V(self.d(f, i)) + for m in mons[i]: + if (i, m) in cols: + block[cols[(i, m)]] = Ji * mono(m) % p + if kind == "F" and l in S: + for m in mons[l]: + if (l, m) in cols and m: + k = cols[(l, m)] + block[k] = (block.get(k, 0) - flux(m)) % p + out.append((ident, block, (-self._theta_part(f, V)) % p)) + return out + + def solve(self, S, mons, p, seed): + """The solution with free unknowns 0 as {(state, monomial): residue} and the point of the samples; None + where no solution exists.""" + 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) + V = _Residues(set(self.F), width + _EXTRA_POINTS, p, seed) + blocks = [] + for ident, block, b in self.rows(S, mons, cols, V): + if not block: + if np.any(b % p): + return None, V + continue + ks = sorted(block) + M = np.stack([block[k] for k in ks] + [b], axis=1) % p + rr = rref_modp(M[:1] if ident[0] == "x0" else M, p) + 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] + 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"]]] + 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 + + def factors(self): + """Functions of the parameters by which the lift may change: the lift of c Y is c times the lift of Y.""" + out = [spy.Integer(1)] + den = spy.Integer(1) + for s, e in self.theta.items(): + out += [e, e / s] + den = spy.lcm(den, spy.fraction(spy.together(e))[1]) + return list(dict.fromkeys(out + [1 / den])) + + def exact(self, S, mons, sol, V1): + """The solution over Q: a number times one of the factors where the quotient does not change with the + parameters, read from two primes, else an exact solve of the unknowns found; None where neither reads it.""" + keys = sorted(sol, key=str) + p1, p2 = PRIMES[0], PRIMES[1] + other, V2 = self.solve(S, mons, p1, 2) + second, V3 = self.solve(S, mons, p2, 3) + if other is not None and second is not None and set(other) == set(sol) == set(second): + for c in self.factors(): + try: + a1, a2, a3 = (int(V(c)[0]) for V in (V1, V2, V3)) + except SYMPY_FAILS as exc: + sympy_fail(exc) + continue + if not (a1 % p1 and a2 % p1 and a3 % p2): + continue + k1 = {u: sol[u] * pow(a1, -1, p1) % p1 for u in keys} + if k1 != {u: other[u] * pow(a2, -1, p1) % p1 for u in keys}: + continue + 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) + if q is None: + break + out[u] = q * c + else: + return out + return self.symbolic(S, mons, keys) if len(keys) <= _SYMBOLIC_UNKNOWNS else None + + def symbolic(self, S, mons, keys): + """The unknowns `keys` over Q(theta) from as many independent identities at points with small states.""" + K = len(keys) + cols = {u: k for k, u in enumerate(keys)} + p = PRIMES[0] + V = _Residues(set(self.F), K + _EXTRA_POINTS, p, 5, high=1000) + rows = [] + for ident, block, b in self.rows(S, mons, cols, V): + for t in range(1 if ident[0] == "x0" else V.n): + v = np.zeros(K + 1, dtype=np.int64) + for k, col in block.items(): + v[k] = col[t] + v[K] = b[t] + rows.append((ident, t, v)) + if not rows: + return None + rr = rref_modp(np.stack([v[:K] for _, _, v in rows], axis=1), p) + if rr["rank"] < K: + return None + Ms, bs = [], [] + for c in rr["piv"][:K]: + ident, t, _ = rows[int(c)] + sub = {s: spy.Integer(int(v[t])) for s, v in V.vals.items() if s in V.states} + Ms.append([self._entry(ident, u, sub) for u in keys]) + bs.append(self._rhs(ident, sub)) + try: + dA = DomainMatrix.from_Matrix(spy.Matrix(Ms).row_join(spy.Matrix(bs))).to_field() + sol = dA.extract(list(range(K)), list(range(K))).lu_solve(dA.extract(list(range(K)), [K])).to_Matrix() + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + return {u: spy.cancel(sol[k]) for k, u in enumerate(keys)} + + def _entry(self, ident, u, sub): + """The coefficient of the unknown u = (state, monomial) in the identity, at the states `sub`.""" + kind, l, f, _ = ident + 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]) + 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)) + return e.xreplace(sub) + + def _rhs(self, ident, sub): + """The right-hand side of the identity, at the states `sub`.""" + kind, _, f, _ = ident + y = sum((self.theta[s] * self.d(f, s) for s in f.free_symbols & self.moved), spy.Integer(0)) + return y if kind == "x0" else -y.xreplace(sub) + + +def support_lift(field, regime, ic_lines, states): + """`field` with state components on the states the direction reaches, or None. + + The support starts at the states whose equation, start or output reads a parameter moved and grows by + the states reading it; the components are polynomials of degree at most two in the states of the support. + The identities of the lift decide it.""" + sts = {spy.Symbol(str(x)) for x in states} + try: + F = {x: f for x, f in _rhs_of(tuple(str(line) for line in regime["f"])).items() if x in sts} + theta = {spy.Symbol(str(k)): _expr(str(v)) for k, v in dict(field).items()} + theta = {k: v for k, v in theta.items() if v != 0} + obs = [_expr(str(line).split("=", 1)[1] if "=" in str(line) else str(line)) for line in regime["g"]] + x0 = {x: e for x, e in _rhs(ic_lines).items() if x in F} + 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()): + 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)} + S |= {x for h in obs if h.free_symbols & pb.moved for x in h.free_symbols & set(F)} + try: + for _ in range(_GROWTH): + for level in (0, 1, 2): + if level == 2 and len(S) > _QUADRATIC_STATES: + break + mons = _ansatz(S, pb.reads, pb.readers, level) + if sum(len(v) for v in mons.values()) > _UNKNOWN_CAP: + break + sol, V = pb.solve(S, mons, PRIMES[0], 1) + if sol is None: + continue + vals = pb.exact(S, mons, sol, V) if sol else None + return None if vals is None else _lifted(field, vals) + grow = set().union(*(pb.readers.get(s, set()) for s in S)) - S + if not grow or len(S | grow) > _SUPPORT_CAP: + return None + S |= grow + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + + +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]) + out = dict(field) + for i, e in comp.items(): + if e != 0: + out[str(i)] = str(e) + return out diff --git a/src/symident/sym/tape.py b/src/symident/sym/tape.py index 9acc195..b150b4f 100644 --- a/src/symident/sym/tape.py +++ b/src/symident/sym/tape.py @@ -2,6 +2,7 @@ import sympy as spy +from .. import state from ..errors import SYMPY_FAILS, sympy_fail from .charts import ( _apply_power_recast, @@ -43,6 +44,7 @@ pre_state, pre_state_name, ) +from .shared import shared_tape_compile from .steady import _FORCE_CONSTRAINT_SEED # Opcodes for the flat tape consumed by the C++ kernel (cpp/kernel.cpp). Integer powers @@ -361,6 +363,18 @@ def compile_observability_tape_multi(model, observation, condition_subs, conditi 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)) + if shared is not None: + return shared _s = _str_memo() model = _as_list(model) observation = _as_list(observation) diff --git a/tests/spec_util.py b/tests/spec_util.py index c001f74..da07b75 100644 --- a/tests/spec_util.py +++ b/tests/spec_util.py @@ -33,7 +33,7 @@ def kwargs_of(spec): 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")} + if k not in ("certifyPoly", "certifyPolyDeg", "timeout")} kw["control"] = reconst_control(**c) return kw @@ -73,13 +73,11 @@ def kw_of(a): # the specs pass arguments the reduction no longer has if k == "verbose": continue - if isinstance(v, list) and len(v) == 1 and k in ("d_poly", "d_darboux", "d_exp", "timeout"): + # the reduction has no time limit + if k == "timeout": + continue + if isinstance(v, list) and len(v) == 1 and k in ("d_poly", "d_darboux", "d_exp"): v = v[0] - if k == "timeout" and v == "Inf": - v = math.inf - # a time limit this short stops the section search; zero stops it on any machine - if k == "timeout" and isinstance(v, (int, float)) and v < 1: - v = 0 if k in ("fixed", "positive") and isinstance(v, list) and v and isinstance(v[0], bool): v = v[0] kw[k] = v diff --git a/tests/test_certificates.py b/tests/test_certificates.py index 93720c0..97ba44d 100644 --- a/tests/test_certificates.py +++ b/tests/test_certificates.py @@ -272,3 +272,42 @@ def skip_first(*a, **k): # three pairs among three draws, one among two kernel = [r.info["bound"]["probability"] - r.info["order_bound"] for r in (r0, r1)] assert kernel[0] > 0 and kernel[1] == pytest.approx(3 * kernel[0], rel=1e-6) + + +def _has_msolve(): + from symident.sym.msolve import MsolveMissingError, _msolve_binary + try: + _msolve_binary() + except MsolveMissingError: + return False + return True + + +needs_msolve = pytest.mark.skipif(not _has_msolve(), reason="needs msolve") + + +@needs_msolve +def test_a_simple_resting_point_modulo_a_prime_proves_the_resting_state(): + m = si.Model({"x": "k1 - k2*x*z", "z": "k3 - k4*z"}, {"y": "s*x"}) + rest = si.detect(m, equilibrate=True).info["resting"] + assert rest["exists"] == "proven" and rest["bound"] is None + + +@needs_msolve +def test_balances_without_a_resting_state_raise_with_an_error_bound(): + import random + + import sympy as spy + + 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"): + si.detect(m, equilibrate=True) + k1, k2, k3, k4, z = spy.symbols("k1 k2 k3 k4 z") + out = modular_decision([k1 - k2 * z, k3 - k4 * z], ["x", "z"], True, random.Random(1)) + assert out["exists"] == "no" and out["draws"] == ["no"] * 3 and 0 < out["bound"] < 1 + # a balance identically zero leaves a resting set of positive dimension: no simple point + out = modular_decision([k3 - k4 * z, spy.Integer(0) * z], ["x", "z"], True, random.Random(1)) + assert out["exists"] == "open" diff --git a/tests/test_detect.py b/tests/test_detect.py index 23202ba..54acb42 100644 --- a/tests/test_detect.py +++ b/tests/test_detect.py @@ -353,6 +353,18 @@ def test_only_drained_species_rest_at_zero(): assert set(_zero_states(rx["stoichiometry"], rx["species"], rx["rates"], [])[0]) == {"A", "B"} +def test_a_reversible_net_rate_drains_neither_side(): + # a reaction whose net rate has terms of both signs runs both ways and 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"}) + 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 @@ -1176,6 +1188,27 @@ def test_stacked_rank_proven_by_fields(): assert gd.gauge == ["K"] +def test_stacked_narrowing_reads_off_and_closes_columns_without_rows(monkeypatch): + # many conditions: the narrow route reads a cover of them; a state no output reads leaves columns without rows + f = {"x": "k1*u - k2*x", "w": "k3*x - k4*w", "z": "k5*x - k6*z"} + g = {"y": "s*x + o1 + o2", "yz": "z"} + cg = {"rows": [f"c{i}" for i in range(20)], "cols": {"u": list(range(1, 21))}} + monkeypatch.setenv("SYMIDENT_NOJET", "1") + with state.options(stacked_min=0): + res = detect(f, g, conditions=cg, reconstruct=True) + routes = {d.get("route") for d in res.symmetries} + assert {"narrow (a column without rows)", "narrow read-off (constant)"} <= routes + assert res.info["rank_status"]["status"] == "proven" + 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) + assert sorted(map(str, par.symmetries)) == sorted(map(str, res.symmetries)) + assert par.info["rank_status"]["status"] == "proven" + + def test_constant_state_events_per_segment(): rx = network(("", "R", "kR"), ("R", "", "dR*R"), ("", "G", "kG*R*(b + u)"), ("G", "", "dG*G"), ("", "u", "0")) diff --git a/tests/test_determinism.py b/tests/test_determinism.py index af94c6f..0beadf0 100644 --- a/tests/test_determinism.py +++ b/tests/test_determinism.py @@ -88,18 +88,11 @@ def _detect(**kw): return d -def test_a_time_limit_that_does_not_fire_changes_nothing(): +def test_the_reconstruction_takes_no_time_limit(): import symident as si - plain = _detect() - limited = _detect(control=si.reconst_control(timeout=1e6)) - assert plain["info"]["limits"] == limited["info"]["limits"] == [] - assert plain["symmetries"] == limited["symmetries"] - - -def test_a_time_limit_that_fires_is_reported(): - import symident as si - d = _detect(control=si.reconst_control(timeout=1e-9)) - assert any(lim.startswith("timeout") for lim in d["info"]["limits"]) + with pytest.raises(TypeError): + si.reconst_control(timeout=10) + assert "timeout" not in si.reconst_control() def test_the_jet_route_stops_at_its_work_limit(): diff --git a/tests/test_discrete.py b/tests/test_discrete.py index ae717ee..5d81edb 100644 --- a/tests/test_discrete.py +++ b/tests/test_discrete.py @@ -1,5 +1,8 @@ """Discrete symmetries: the other points of the domain with the output of a generic one.""" +import math +from fractions import Fraction + import pytest import sympy as spy @@ -67,11 +70,12 @@ 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, discrete={"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"] - assert info["count"] == 2 and info["fundamental_domain"] == [] + assert info["count"] == 2 and info["fundamental_domain"] == [] and info["count_domain"] == 1 assert all(c["real"] == 2 and c["in_domain"] == 1 for c in info["counts"]) @@ -112,7 +116,8 @@ def test_a_square_outside_the_domain_leaves_the_model_globally_identifiable(): "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) - out = r.discrete(points=2) + # 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) (s,) = out["symmetries"] assert s["changes"] == ["alpha"] and same(s["map"]["alpha"], "-alpha") assert s["level"] == "exact" and s["preserves_domain"] is False @@ -121,13 +126,75 @@ def test_a_square_outside_the_domain_leaves_the_model_globally_identifiable(): assert all(c["real"] == 2 and c["in_domain"] == 1 for c in info["counts"]) +def _stage_toy(monkeypatch, d): + """A block in x0, x1, x2 with the stage x0 + x1 = 0, 4 x0 x1 + d = 0 and x2 = x0, and the calls of + _stage_points as (p, found).""" + 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}] + calls, orig = [], discrete._stage_points + + 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 + + +def test_a_block_that_msolve_counts_at_once_is_not_split_into_stages(monkeypatch): + discrete, fib, polys, calls = _stage_toy(monkeypatch, 4) + assert discrete._staged_count(fib, [0, 1, 2], polys, [], discrete.PRIMES[0]) == 2 + assert calls == [] + + +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 + + 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 + # the block at once within an eighth of the cap, then the stage and the rest within the whole cap + assert caps[0] == 100 and calls == [(discrete.PRIMES[0], True)] + + +def test_a_stage_with_points_outside_gf_p_is_not_solved_over_q(monkeypatch): + discrete, fib, polys, calls = _stage_toy(monkeypatch, 0) + p = discrete.PRIMES[0] + # d a non-residue modulo p: the points of the stage, x0 = +-sqrt(d)/2, lie outside GF(p) and Q + polys[1][()] = next(d for d in range(2, 100) if pow(d, (p - 1) // 2, p) == p - 1) + seen, orig = set(), discrete._block_count + + def first_fails(fib_, idx, polys_, sat, p_): + # the first count at once of a block over Q fails, as on a block too large for it + if p_ == 0 and tuple(idx) not in seen: + 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)] + + 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)"} m = si.Model(f, {"y4": "x4"}, known_inputs=["u1", "x1", "x2", "x3"]) - out = si.detect(m, cores=1).discrete(points=1) + 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) (s,) = out["symmetries"] assert same(s["map"]["p22"], "-p22") and s["preserves_domain"] is False info = out["info"] @@ -174,6 +241,7 @@ def test_an_estimated_event_time_is_a_coordinate_of_the_fiber(): maps, info = maps_of(dosed("x1", time="tau")) (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"] def test_a_map_that_the_truncated_fiber_keeps_is_dropped_further_up(): @@ -191,13 +259,13 @@ def test_detect_in_global_mode_counts_after_the_local_analysis(): r = si.detect(si.Model({"x": "-k*s*x", "z": "x"}, {"y": "z"}), mode="global") assert r.discrete_symmetries == [] and r.info["discrete"]["reduced"] # 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"}, unknown_inputs=["w"]), 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") - with pytest.warns(DeprecationWarning): - si.detect(two_compartment(), discrete={"points": 1}) def test_the_json_interface_runs_the_global_mode(): @@ -288,13 +356,17 @@ def test_a_chain_swaps_the_decay_rates_of_its_last_two_members(): info = r.info["discrete"] assert info["count"] == 2 and info["count_final"] and info["candidates"]["proven"] == 1 cert = info["certificate"] - assert cert["orbit"] == 2 and cert["complete"] == "axiom" and cert["invariance"][0]["proven"] + assert cert["orbit"] == 2 and cert["invariance"][0]["proven"] + # the coefficients of the input-output relation of A and u lie in the field of the outputs; c, sh and the + # symmetric functions of kR and kA follow from them + assert cert["complete"] == "exact" and cert["count_bound"] is None + assert any(r.endswith("proven") for r in cert["exact"]["relations"]) 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") + 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"] @@ -347,3 +419,769 @@ def poly(): if a is not None: assert sorted(map(sorted, map(dict.items, a[0]))) == sorted(map(sorted, map(dict.items, b[0]))) 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"] + cert = info["certificate"] + assert info["count"] == 2 and cert["orbit"] == 2 and cert["complete"] == "exact" and info["count_final"] + # x0 and k^2 generate the field fixed by k -> -k; both are rational in the Taylor coefficients + assert {g["function"] for g in cert["exact"]["generators"]} == {"x0", "-k**2"} + assert cert["count_bound"] is None and "axiom" not in cert and "proven" in repr(r) + + +def test_a_known_constant_is_a_symbol_of_the_base_field_of_the_exact_count(): + m = si.Model({"x": "-k^2*D*x"}, {"y": "x"}, trafo={"x": "x0"}, fixed=["D"]) + cert = si.detect(m, mode="global", cores=1).info["discrete"]["certificate"] + # k^2 D and D known give k^2 + assert cert["complete"] == "exact" and cert["orbit"] == 2 + + +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}) + 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 + orig = discrete.q_count + + 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 + assert "no finite count over Q at the random integer point" in cert["count_bound_why"] + + +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 + # (a + b)/(a - b) + 1/(a - b) has the one denominator a - b + v = (a + b) / d + 1 / d + assert v.dn == 1 and list(v.den.values()) == [1] and A.of(v.den) == 1 + w = (a + b) / d + assert common([w, w * w]) == (2, [2, 2]) + # numbers stay exact, and only an exact zero compares equal to zero + assert (Deg.const(A, Fraction(1, 3)) * 3).c == 1 and (a - a) != 0 and (a * 0) == 0 + + +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]) + # a has two distinct images; the coefficients of (Z - a)(Z - b) and the fixed c generate F + assert alpha == a and others == [b] + assert {spy.expand(f) for f in F} == {c, -a - b, a * b} and [spy.expand(t) for t in traces] == [a + b] + + +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(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"] + assert cert["complete"] == "axiom" and "bits" in cert["count_bound_why"] + + +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]] + + +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 + 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) + assert P == {tuple(int(i in (0, 1099)) for i in range(1100)): Fraction(1, 2), (0,) * 1100: Fraction(3)} + + +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}) + # 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"] + assert cert["complete"] == "verified" and cert["count_bits"] == 4000 + + +def test_a_parameter_read_only_as_a_fourth_power_has_maps_over_q_of_i_from_monodromy(): + # k and -k are rational maps; i*k and -i*k have the output of k as well, over Q(i) + r = si.detect(si.Model({"x": "-k^4*x"}, {"y": "x"}, trafo={"x": "x0"}), mode="global", cores=1) + info = r.info["discrete"] + 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 all(s["level"] == "exact" and s["preserves_domain"] is False for s in over_i) + assert info["monodromy"]["certified"] == 4 + + +def _relaxed(odes, obs, **kw): + r = si.detect(si.Model(odes, obs, **kw), mode="global") + return r.info["discrete"], r.discrete_symmetries + + +def test_an_exponential_of_a_state_is_counted_on_the_relaxed_model(): + info, _ = _relaxed({"x": "-k*exp(x/c)"}, {"y": "x"}) + (lf,) = info["relaxed"]["leaves"] + assert lf["kind"] == "exp" and same(lf["start"], "exp(x/c)") + assert info["count"] == 1 and info["certificate"]["complete"] == "exact" + + +def test_a_free_power_drops_the_coordinate_its_constant_term_determines(): + info, _ = _relaxed({"x": "-k*x^n/(K^n + x^n)"}, {"y": "x"}) + assert list(info["relaxed"]["dropped"]) == ["K"] + assert info["count"] == 1 and info["certificate"]["complete"] == "exact" + + +def test_a_logarithm_of_a_state_is_an_independent_leaf(): + info, _ = _relaxed({"x": "-k*x + p*log(x)"}, {"y": "x"}) + assert info["relaxed"]["premise"] is None + assert info["count"] == 1 and info["certificate"]["complete"] == "exact" + + +def test_a_map_of_the_relaxed_model_that_keeps_the_leaves_is_a_map_of_the_model(): + info, syms = _relaxed({"x1": "-(k1 + k2)*x1 - a*x1*exp(x1/c)", "x2": "k1*k2*x1"}, {"y1": "x1", "y2": "x2"}) + assert info["count"] == 2 and info["certificate"]["complete"] == "exact" + (s,) = syms + assert s["level"] == "exact" and same(s["map"]["k1"], "k2") + + +def test_a_leaf_the_output_does_not_fix_leaves_the_count_open(): + info, _ = _relaxed({"x1": "-(k1 + k2)*x1*exp(x1/c)", "x2": "k1*k2*x1"}, {"y1": "x1", "y2": "x2"}) + assert info["certificate"]["complete"] == "open" and "new coordinate" in info["relaxed"]["why"] + + +def test_a_known_input_inside_a_term_becomes_a_state_with_a_known_start(): + info, _ = _relaxed({"x": "-k*x*exp(u/c)"}, {"y": "x"}, known_inputs=["u"]) + assert info["relaxed"]["model"]["trafo"]["u"].startswith("si_u0") + assert info["count"] == 1 and info["certificate"]["complete"] == "exact" + + +def test_a_free_power_of_a_state_at_zero_is_counted_on_the_slice_of_its_leading_coefficient(): + # x^a/(g^a + x^a) is N/(P + N) with N = (x/c_x)^a and P = (g/c_x)^a, which determines g + info, _ = _relaxed({"x": "p - m*x"}, {"y": "x^a/(g^a + x^a)"}, trafo={"x": "0"}) + (lf,) = info["relaxed"]["leaves"] + assert lf["absorbs"] == "g" and same(lf["start"], "(g/p)^a") + (sp,) = info["start_powers"] + assert (sp["state"], sp["exponent"], sp["order"], sp["premises"]) == ("x", "a", 1, []) + assert info["count"] == 1 and info["certificate"]["complete"] == "verified" + + +def test_a_free_power_of_a_state_at_zero_in_the_dynamics_of_another_state(): + info, _ = _relaxed({"x": "p - m*x", "z": "x^a/(g^a + x^a) - k*z"}, {"y": "z"}, trafo={"x": "0", "z": "0"}) + (sp,) = info["start_powers"] + # z = t^(1 + a)/(1 + a) + ...: the lowest exponent other than an integer is at index 2 + assert sp["index"] == 2 and sp["premises"] == [] + assert info["count"] == 1 and info["certificate"]["complete"] == "verified" + + +def test_a_leading_coefficient_without_a_scaling_is_a_leaf(): + info, _ = _relaxed({"x": "p - m*x"}, {"y": "q*x^a + x"}, trafo={"x": "0"}) + (lf,) = info["relaxed"]["leaves"] + assert lf["kind"] == "power" and same(lf["start"], "p^a") + assert info["count"] == 1 and info["certificate"]["complete"] == "verified" + + +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) + + +def test_a_coefficient_without_a_sign_on_the_domain_is_a_premise(): + (sp,) = _start_power_series({"y": "(q - r)*si_N1 + x"}).start_powers + (why,) = sp["proof"]["premises"] + assert "not zero on the domain" in why + (sp,) = _start_power_series({"y": "(q + r)*si_N1 + x"}).start_powers + assert sp["proof"]["premises"] == [] and sp["proof"]["index"] == 1 + with pytest.raises(ValueError, match="positive"): + _start_power_series({"y": "si_N1 + x"}, positive=["m", "p", "q", "r"]) + + +def test_the_series_of_a_start_power_has_the_layers_of_the_exponent(): + # y = N = (x/p)^a with x = p t - p m t^2/2: N = S (1 - a m t/2 + ...), S = t^a + ser = _start_power_series({"y": "si_N1"}) + pt = {spy.Symbol(c): spy.Rational(v) for c, v in zip(ser.coords, (3, 5, 7, 2, 1))} + (y,) = ser.numeric(pt, 2) + assert [list(v) for v in y] == [[0, 0, 0], [0, 1, 0], [0, Fraction(-15, 2), 0]] + assert ser.pins[0][0] == {(1, 0, 0, 0, 0): 1} + + +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") + + +def test_a_power_below_the_order_of_the_base_is_refused(): + # x = q t^(1 + a)/(1 + a) + p t^2/2: below t^2 for a < 1, the expansion has no leading term c t^k + r = si.detect(si.Model({"x": "z + q*x^a", "z": "p - m*z"}, {"y": "x"}, trafo={"x": "0", "z": "0"}), cores=1) + with pytest.raises(ValueError, match="below"): + r.discrete() + + +def test_a_coordinate_proven_in_the_field_of_the_outputs_pins_the_count(monkeypatch): + 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"] + 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 + assert pinned["certificate"]["complete"] == "verified" + assert pinned["certificate"]["bezout"] < free["certificate"]["bezout"] + + +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) + (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" + + +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}] + sat = [{((0, 1), (1, 1)): 1}] + out, sat2, gone = discrete._monomial_eliminate(polys, sat, 3, p) + assert gone == {0, 3} + assert all(v not in gone for P in out + sat2 for mm in P for v, _ in mm) + # a coordinate does not leave for a monomial that holds a jet + _, _, gone = discrete._monomial_eliminate([{((0, 1),): 1, ((3, 1), (4, 1)): 1}], [], 3, p) + assert gone == set() + + +def test_the_count_after_the_elimination_of_monomial_pins_is_the_same(monkeypatch): + 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"] + pinned = run(["a*b", "a + c", "b/c"]) + assert pinned["count"] == 2 and pinned["certificate"]["complete"] == "verified" + + +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 + + +def test_the_symbols_of_the_package_hold_no_clock(): + import pathlib + 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)] + 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"] + 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"] + 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 + with pytest.raises(discrete.FiberTooLargeError): + discrete._ser_poly({(3,): 1}, xs, [], 2, R(1), R(0), limit=4) + + +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) + with pytest.raises(discrete.FiberTooLargeError): + discrete._ser_poly({(1, 1): 1}, xs, [], 2, R(1), R(0), limit=6) + + +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): + discrete._ser_poly({(1, 0): 1, (0, 1): 1}, xs, [], 2, R(1), R(0), limit=6) + + +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])]] + o, z = E([R(1), R(0)]), E([R(0), R(0)]) + with pytest.raises(discrete.FiberTooLargeError): + discrete._ser_poly({(1, 1): 1}, xs, [], 1, o, z, limit=6) + + +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)) + + +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"}]) + 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"] + + +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"): + r = si.detect(m, equilibrate=True, mode="global", cores=1) + assert "largest coupled block of 2 states is past the cap rest_block of 1" in r.info["discrete"]["unsupported"] + + +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"}) + + +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}] + 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) + b = fib._ms_block([0, 1, 2], polys, sat, p) + assert staged == discrete._gb_count(b["names"], p, b["eqs"], b["sep"]) == 4 + # a block that no stage splits has none + assert discrete._first_stage(polys[:2], [0, 1]) is None + + +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)}] + 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)] + whole = discrete._block_count(fib, [0, 1, 2], polys, sat, 0) + assert discrete._staged_count(fib, [0, 1, 2], polys, sat, 0) == whole == 4 + + +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"], {} + polys = [{((0, 1), (1, 1)): 1, (): p - 2}, {((0, 1),): 1, ((1, 1),): 1, (): p - 3}] + discrete._FAILURES.clear() + assert discrete._block_count(fib, [0, 1], polys, [], p) == 2 + with work.caps(msolve_terms=4): + assert discrete._block_count(fib, [0, 1], polys, [], p) is None + why = discrete.no_count_reason(3) + assert "a system past the caps of msolve (400 unknowns, 4 terms)" in why + assert work.msolve_too_large(["x0", "x1"], ["x0*x1-2", "x0+x1-3"]) is None + with work.caps(msolve_unknowns=1): + assert "past the cap of 1 unknowns of msolve" in work.msolve_too_large(["x0", "x1"], ["x0*x1-2"]) + + +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"], {} + polys = [{((0, 1), (1, 1)): 1, (): p - 2}, {((0, 1),): 1, ((1, 1),): 1, (): p - 3}] + b = fib._ms_block([0, 1], polys, [], p) + discrete._FAILURES.clear() + assert discrete._gb_count(b["names"], p, b["eqs"], b["sep"]) == 2 + with work.caps(msolve_entries=1): + assert discrete._gb_count(b["names"], p, b["eqs"], b["sep"]) is None + why = discrete.no_count_reason(3) + assert "msolve reached the cap msolve_entries of 1 nonzero entries of the matrices of F4" in why + with work.local_caps(msolve_entries=1): + assert discrete._gb_count(b["names"], p, b["eqs"], b["sep"]) is None + assert discrete._gb_count(b["names"], p, b["eqs"], b["sep"]) == 2 + + +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}) + assert r.info["discrete"]["count"] == 2 + assert seen and set(seen) == {3 << 30} and work.MSOLVE_MEMORY == default + + +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, "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) + # every observable starts one order above the highest order of the rank criterion, and the orders rise together + assert given[:2] == [[4, 4], [5, 5]] and len(given) == discrete._ORDER_RAISES + 1 + + +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, "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]] + + +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"] + 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 + + +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 + + +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"]) + + +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 + + +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"] + (lim,) = [w for w in info["limits"] if w.startswith("the Taylor coefficients of the outputs up to order")] + assert "the Taylor series of the outputs reached the cap of 10 term products" in lim + + +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"] + + +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()") + fib = discrete.Fiber(discrete.Series(parts, ["k", "x0"]), [3]) + k, maps = discrete.rational_maps(fib) + assert k == 2 and len(maps) == 1 + meter = work.Meter("the reconstruction of the maps", 0, "points of the fiber") + assert discrete.rational_maps(fib, meter) == (None, None) + assert meter.reason() == "the reconstruction of the maps reached the cap of 0 points of the fiber" + + +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 + assert s.reason() == "the dense relations reached the cap of 3 entries" + t = m.share("the rest", 100) + assert t.spend(7) and m.over and t.reason() == "the search reached the cap of 10 entries" + + +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 + assert rows is not None and series._jac[(PRIMES[0], 0)][0] < 40 + assert rows == _chain_series().rank_rows(max(k for _, k in rows), PRIMES[0]) + + +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] + # the gradients of the pins and of y(0) reach the rank of the three coordinates + assert series.pinned_orders(6, p) == [0] + # the pins of least degree that raise the rank and as many more come first, then all + pins = ["k1^7", "k1^3 + k2^5", "k1^2*k2", "k1*k2", "k2", "k1"] + series = _pinned_series({"x": "-k1*x - k2*x^2"}, {"y": "x"}, {"x": "x0"}, ["k1", "k2", "x0"], pins) + first, every = discrete._pin_sets(series, p) + assert sorted(pins[i] for i in first) == sorted(["k1", "k2", "k1*k2", "k1^2*k2"]) and every == list(range(6)) + + +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"]}) + 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"] + assert info["count"] == 1 and info["count_final"] and cert["complete"] == "verified" + pin = cert["pinned"] + # one order above the criterion of the pins, below the order 2 of the outputs alone + assert pin["functions"] == ["k1", "k2"] and pin["orders"] == {"y": 1} and pin["count"] == 1 + assert cert["count_bound"] == pin["count_bound"] and 0 < pin["count_bound"] < 1e-6 + assert "counted on 2 functions proven" in repr(r) + + +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"]) + out = discrete.pinned_count(series, True, 1) + assert out["count"] == 2 and out["cert"] is None and "not below 2" in out["why"] + + +def _toy_projection(series, syms): + """The supports of the projections of the series, as fieldproof.exact_fiber() reports those past ioproj.TERMS.""" + import random + + 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] + pos = [rel.names.index(str(s)) for s in syms if s in set(series.params)] + h = fieldproof._profiles(rel, rng)[0] + pr = ioproj.Projection.output(rel, h, 0, pos, rng) + S = pr.search([rng.randrange(1, p) for _ in pos], p, math.inf) + return [{"profile": list(h), "observable": 0, "support": [tuple(m) for m in S]}] + + +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) + assert spy.isprime(q) and 1 << 29 <= q <= 1 << 30 + # Rosser and Schoenfeld: more than 3.8e7 primes from 2^29 to the largest engine prime + assert fewcoef.primes_at_least(1 << 29, 1518500183) > 3.8e7 + + +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 = [] + out = fewcoef.verified_functions(series, syms, _toy_projection(series, syms), math.inf, random.Random(2), log) + # y' + k1 y + k2 y^2 = 0 over the coefficient 1 of y' + assert sorted(out["functions"]) == ["k1", "k2"] and out["why"] is None + assert 0 < out["exist"] < 1e-30 and all(0 < b < 1e-30 for b in out["checks"].values()) + + +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)} + 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"] + pin = cert["pinned"] + assert cert["complete"] == "verified" and sorted(pin["functions"]) == ["k1", "k2"] + assert sorted(pin["relation"]["functions"]) == ["k1", "k2"] and pin["relation_bound"] > 0 + assert cert["count_bound"] == pin["count_bound"] == pin["count_bound_q"] + pin["relation_bound"] + assert "verified relation" in cert["bounded"] + + +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"}) + 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"]) + 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)" + assert info["count"] == 1 and info["certificate"]["complete"] == "exact" + + +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"]) + # 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 + assert "E" not in c["positive"] and "si_V_rest1" in c["coordinates"] + + +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"]) + 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") + + +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]))) + + +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") + sig = {a: b, b: a} + assert discrete._state_map(f, g, None, sig, ["x", "y"]) is not None + discrete._CAPPED.clear() + with work.caps(state_map_terms=1): + assert discrete._state_map(f, g, None, sig, ["x", "y"]) is None + assert any("past the cap state_map_terms of 1" in n for n in discrete._CAPPED) + + +def test_a_result_of_reduce_cq_is_counted_on_the_level_sets_of_the_totals(): + f = {"A": "-k1^2*A + k2*B", "B": "k1^2*A - k2*B"} + r = si.detect(si.Model(f, {"y1": "A", "y2": "B"}), reduce_cq=True) + out = r.discrete() + (s,) = out["symmetries"] + assert r.info["coordinates"] == ["B", "k1", "k2", "total1"] and out["info"]["eliminated"] == {"A": "(-B + total1)"} + assert s["level"] == "exact" and s["map"] == {"k1": "-k1"} and out["info"]["count"] == 2 + 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"}]) + 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"}] + assert i["count"] == 2 and i["count_domain"] == 1 and i["certificate"]["complete"] == "exact" diff --git a/tests/test_exact.py b/tests/test_exact.py index 9e61e95..9f2af9f 100644 --- a/tests/test_exact.py +++ b/tests/test_exact.py @@ -18,6 +18,13 @@ SCALE = {"x": "x", "z": "z", "b": "b", "c": "0", "s": "-s"} +@pytest.fixture +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) + + def test_a_symmetry_and_its_lift_pass(): assert certify(regime_identities(REGIME, SCALE))["ok"] is True assert certify(initial_identities(["x = x0", "z = 0"], dict(SCALE, x0="x0")))["ok"] is True @@ -166,7 +173,7 @@ def test_without_a_certified_lie_order_the_symbolic_engine_proves_by_lifts(): assert st["status"] == "lower bound" and st["why"].endswith("stay below the generic rank") -def test_a_direction_of_the_reachable_set_says_why_it_stays_below_exact(): +def test_a_direction_of_the_reachable_set_says_why_it_stays_below_exact(without_support_lift): r = si.detect(_fields_model(), reconstruct=True) (p,) = r.info["proof"] assert p["reason"].startswith("lift of the closed form: [Y, F] on") @@ -208,7 +215,7 @@ def test_directions_below_exact_get_the_bound(): assert 0 < r.info["bound"]["probability"] < 1e-5 and r.info["bound"]["points"] == 2 -def test_the_regime_detections_of_the_combined_lift_keep_to_their_budget(): +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"]) r = si.detect(m, reconstruct=True, control=si.reconst_control(exact_work_cap=1)) @@ -217,7 +224,7 @@ def test_the_regime_detections_of_the_combined_lift_keep_to_their_budget(): assert [s.level for s in si.detect(m, reconstruct=True).symmetries] == ["exact"] -def test_unproven_directions_are_listed_and_printed_with_their_level(): +def test_unproven_directions_are_listed_and_printed_with_their_level(without_support_lift): r = si.detect(_fields_model(), reconstruct=True) assert [s.level for s in r.unproven()] == ["verified"] and r.unproven()[0].explicit text = repr(r) @@ -336,14 +343,19 @@ def test_the_bound_needs_proven_orders(): def _fields_model(): - # the nonlinear balance keeps its direction below exact: the lift needs a state component that is no - # combination of the states + # 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"}]) -def test_a_rank_through_invariant_fields_is_verified(): +def test_a_direction_through_a_start_event_is_proven_by_the_lift_on_the_support(): + r = si.detect(_fields_model(), reconstruct=True) + assert [s.level for s in r.symmetries] == ["exact"] and r.info["rank_proof"] == "proven symmetries" + + +def test_a_rank_through_invariant_fields_is_verified(without_support_lift): r = si.detect(_fields_model(), reconstruct=True) assert r.info["rank_fields"] == 1 and r.info["rank_proven"] is None b = r.info["rank_fields_bound"] @@ -354,7 +366,8 @@ def test_a_rank_through_invariant_fields_is_verified(): 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): +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 @@ -458,6 +471,45 @@ def test_a_lift_whose_parameter_components_move_along_the_flow_is_refused(): 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": []}]} + + +def test_a_scaling_that_rate_sums_absorb_is_lifted_on_the_states_it_reaches(): + # more regimes than the combined lift takes, a start at 0 and a nonlinear regime: only the support holds the lift + f = {"x1": "u - (k1 + k2)*x1 + kd*x2", "x2": "k1*x1 - (kd + k3)*x2", "x3": "k4*x2^2 - k5*x3"} + cg = {"rows": [f"c{i}" for i in range(10)], "cols": {"u": list(range(1, 11))}} + m = si.Model(f, {"y": "e*x3", "y1": "x1"}, trafo={"x1": "0", "x2": "0", "x3": "0"}, conditions=cg) + r = si.detect(m, reconstruct=True) + assert [s.level for s in r.symmetries] == ["exact", "exact"] + assert r.info["rank_status"]["status"] == "proven" + curved = [s for s in r.symmetries if s.state_components] + assert len(curved) == 1 and set(curved[0].state_components) == {"x2", "x3"} + + +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))"} + 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"] + + +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"} + ex = exact_direction(_light(f, ["y = z + q*x^2"], ["x = x0", "z = z0"]), field, [[0]], False) + assert ex["ok"] is True and ex["states"] == {"z": "x**2"} + + def test_a_conserved_total_reads_the_initial_value_on_all_its_states(): regime = ["A = -k1*A + k2*B", "B = k1*A - k2*B"] lift = initial_lift({"T": "T", "k1": "-k1", "k2": "k1"}, ["A = T", "B = 0"], ["A", "B"], regime) diff --git a/tests/test_experiments.py b/tests/test_experiments.py new file mode 100644 index 0000000..2fdf02b --- /dev/null +++ b/tests/test_experiments.py @@ -0,0 +1,187 @@ +"""The count of several experiments: shared parameters, free starts, and the premise of no rational first integral.""" + +from fractions import Fraction + +import pytest +import sympy as spy + +import symident as si +from symident.sym.msolve import MsolveMissingError, _msolve_binary +from symident.sym.numfield import NumberField, charpoly, cycle_type, rank_over_q + + +def _has_msolve(): + try: + _msolve_binary() + except MsolveMissingError: + return False + return True + + +needs_msolve = pytest.mark.skipif(not _has_msolve(), reason="needs 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" + parts = [{"segments": [{"f": f, "g": g, "ic": ic, "t": "0", "label": ""}]}] + return parts, [x for x in f if x != "time"] + params, Series(parts, [x for x in f if x != "time"] + params) + + +def test_a_number_field_reduces_modulo_its_polynomial(): + K = NumberField([-2, 0, 1]) + s = K.from_t([0, 1]) + assert K.mul(s, s) == K.rational(2) + assert K.mul(s, K.inv(s)) == K.one + # det(z - A) of the companion matrix of z^2 - 2 + assert charpoly(K, [[K.zero, K.one], [K.rational(2), K.zero]]) == [K.one, K.zero, K.rational(-2)] + # s maps to a square root of 2 modulo p at a prime of degree one + for p in (7, 17, 23): + for tau in K.primes_of_degree_one(p): + assert tau * tau % p == 2 and K.residue(s, p, tau) == tau + # a polynomial with a leading coefficient becomes monic in s = lc * t + K3 = NumberField([1, 0, 3]) + t = K3.from_t([0, 1]) + assert K3.add(K3.scale(K3.mul(t, t), Fraction(3)), K3.one) == K3.zero + + +def test_the_cycle_types_of_a_polynomial_modulo_primes(): + # z^3 - 2: irreducible modulo 7, a root and an irreducible quadratic modulo 5, not square-free modulo 3 + assert cycle_type([1, 0, 0, -2], 7) == [3] + assert cycle_type([1, 0, 0, -2], 5) == [2, 1] + assert cycle_type([1, 0, 0, -2], 3) is None + assert rank_over_q([(Fraction(1), Fraction(2)), (Fraction(2), Fraction(4))]) == 1 + + +@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"]) + c = firstint.certificate(s) + assert c["proven"] and c["field"] == "Q" + (b,) = c["blocks"] + assert b["degree"] == 3 and b["group"] == "S_3" and set(b["primes"]) >= {"n-cycle", "(n-1)-cycle"} + + +@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) + assert c["proven"] and c["field"] != "Q" and c["alpha"] is not None + assert [b["degree"] for b in c["blocks"]] == [1, 1] + + +@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"), +]) +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"] + + +@needs_msolve +def test_the_count_of_two_experiments_is_that_of_the_parameters_and_the_first_starts(): + import random + + 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"] + pk, ck = multiexp.stacked(parts, coords, s, starts, 2) + assert ck == ["x", "k", "x_e2"] and [p["segments"][0]["label"] for p in pk] == ["e1:", "e2:"] + sk = discrete.Series(pk, ck) + rng = random.Random(3) + pt = {spy.Symbol(c): spy.Integer(rng.randint(2, 1000)) for c in ck} + fib = discrete.Fiber(sk, 2, True) + # each start goes to the negative independently: four points, two values of (x, k) + assert discrete.complex_count(fib, pt, PRIMES[0]) == 4 + fib.proj = len(coords) + assert discrete.complex_count(fib, pt, PRIMES[0]) == 2 + # over Q, from the parametrization of all four points + assert discrete.q_count(fib, pt) == 2 + + +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"} + 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 + seg = dict(seg, f={"x": "-k*x + x0"}, ic={"x": "x0"}) + assert "also a parameter" in multiexp.eligible(Series([{"segments": [seg]}], ["x0", "k"]))[1] + + +@needs_msolve +def test_two_compartments_count_their_swap_on_several_experiments(): + m = si.Model({"x1": "-(k21 + k01)*x1 + k12*x2 + u", "x2": "k21*x1 - k12*x2"}, {"y": "x2"}, known_inputs=["u"]) + r = si.detect(m, cores=1) + info = r.discrete(points=1, experiments=True)["info"] + ex = info["experiments"] + assert ex["why"] is None and ex["experiments"] >= 2 and ex["count"] == 2 + assert ex["first_integrals"]["proven"] + cert = info["certificate"] + assert info["count"] == 2 and info["count_final"] and cert["route"]["experiments"] == ex["experiments"] + assert cert["complete"] in ("verified", "axiom") + assert any("divides the size of the fiber" in p for p in cert["proven"]) + assert "counted on experiments with shared parameters" in str(r) + + +@needs_msolve +def test_the_twisted_oscillator_leaves_the_route_to_one_experiment(): + m = si.Model({"x1": "(w + x3)*x2", "x2": "-w*x1", "x3": "0"}, {"y1": "x2", "y2": "x3"}) + info = si.detect(m, cores=1).discrete(points=1, experiments=True)["info"] + # x3 is a conservation law: on a level set the oscillator has the trace 0 + assert "first integral" in info["experiments"]["why"] and "trace" in info["experiments"]["why"] + assert "route" not in info["certificate"] + # one experiment leaves w and -(w + x3) + assert info["count"] == 2 + + +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")} + assert multiexp.conservation_laws(dict(seg, f=dict(seg["f"], x3="c - d*x3 + u*x1")), ["x1", "x2", "x3"]) == [law] + + +@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"]) + assert not firstint.certificate(s)["proven"] + c = firstint.certificate(s, laws) + assert c["proven"] and c["laws"] and any(b.get("zero_eigenvalues") == 1 for b in c["blocks"]) + # the second experiment starts on the level set of the first: the pivot x1 of the law follows from it + starts, _ = multiexp.eligible(s) + pk, ck = multiexp.stacked(parts, coords, s, starts, 2, laws) + assert ck == coords + ["x2_e2", "x3_e2"] + assert spy.sympify(pk[1]["segments"][0]["ic"]["x1"]) == spy.sympify("x1 + x2 - x2_e2") + + +@needs_msolve +def test_two_experiments_on_one_level_set_count_a_globally_identifiable_exchange(): + m = si.Model({"x1": "-k1*x1 + k2*x2", "x2": "k1*x1 - k2*x2"}, {"y1": "x1", "y2": "x2"}) + info = si.detect(m, cores=1).discrete(points=1, experiments=True)["info"] + ex = info["experiments"] + assert ex["why"] is None and ex["first_integrals"]["laws"] and ex["count"] == 1 + assert info["count"] == 1 and info["count_final"] and "route" in info["certificate"] diff --git a/tests/test_kernel_modes.py b/tests/test_kernel_modes.py new file mode 100644 index 0000000..c4d52fc --- /dev/null +++ b/tests/test_kernel_modes.py @@ -0,0 +1,154 @@ +"""The kernel builds the same rows in forward and in reverse mode, from one shared tape as from a tape per +condition, and with continued jets as from fresh ones.""" + +import numpy as np +import pytest + +import symident as si +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"] + + +def ev(var, time, value, method): + return {"var": var, "time": time, "value": value, "method": 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"}, + 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]}}), + "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"}), + "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")]), + "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")]), + "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"}), + "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"]}}), +} + + +def _calls(monkeypatch, model, **kw): + seen = [] + + def spy(name): + f = getattr(_core, 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) + monkeypatch.undo() + return seen + + +def _both(monkeypatch, name, a, k): + out = [] + for mode in ("forward", "reverse"): + monkeypatch.setenv("SYMIDENT_KERNEL_MODE", mode) + out.append(getattr(_core, name)(*a, **k)) + monkeypatch.delenv("SYMIDENT_KERNEL_MODE") + return out + + +def _equal(x, y): + if isinstance(x, list): + assert len(x) == len(y) + for a, b in zip(x, y): + _equal(a, b) + return + if not isinstance(x, dict): + np.testing.assert_array_equal(np.asarray(x), np.asarray(y)) + return + assert x.keys() == y.keys() + for key in x: + _equal(x[key], y[key]) + + +@pytest.mark.parametrize("name", MODELS) +def test_both_modes_give_the_same_rows(monkeypatch, name): + calls = _calls(monkeypatch, MODELS[name](), reconstruct=True) + assert calls + for fun in FUNS: + for _, a, k in [c for c in calls if c[0] == fun][:4]: + _equal(*_both(monkeypatch, fun, a, k)) + + +def test_the_cases_reach_every_part_of_the_kernel(monkeypatch): + calls = [c for name in MODELS for c in _calls(monkeypatch, MODELS[name]())] + tapes = [t for n, a, _ in calls if n == "sym_obs_null_multi" for t in a[0]] + segs = [s for n, a, _ in calls if n == "sym_obs_null_chain" for ch in a[0] for s in ch] + assert any(3 in list(t.get("op", [])) for t in tapes + segs) + assert any(t.get("ic_op") is not None for t in tapes + segs) + assert {int(m) for s in segs if "ev_method" in s for m in s["ev_method"]} == {0, 1, 2} + assert any("tm_op" in s for s in segs) + assert any("base" in t for t in tapes) and any("leaf_slot" in t for t in tapes) + + +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] + 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 + + +def test_conditions_in_values_share_one_tape(monkeypatch): + shared = si.detect(MODELS["conditions in values"](), reconstruct=True) + monkeypatch.setenv("SYMIDENT_NOSHARED", "1") + per = si.detect(MODELS["conditions in values"](), reconstruct=True) + assert shared.rank == per.rank and shared.dim == per.dim + assert sorted(map(str, shared.symmetries)) == sorted(map(str, per.symmetries)) + + +def test_continued_jets_equal_fresh_ones(monkeypatch): + calls = _calls(monkeypatch, MODELS["switch at a given time"](), reconstruct=True) + rows = [(a, k) for n, a, k in calls if n == "sym_obs_chain_rows"] + assert rows + a, k = rows[0] + chain, nl, ns, z, pt, p = a[:6] + for Nt in (4, 9, 17): + fresh = _core.sym_obs_chain_rows(chain, nl, ns, z, pt, p, Nt, 0, 1, True) + kept = _core.sym_obs_chain_rows(chain, nl, ns, z, pt, p, Nt, 0, 1, True, "test-chain") + _equal(fresh, kept) + seg = [s for s in chain if s.get("ic_op") is not None][:1] + st = np.arange(1, ns + 1, dtype=np.int64).reshape(1, ns) * 7 + 3 + for Nt in (3, 8, 20): + fresh = _core.sym_segment_ranks(seg, nl, ns, z, pt, p, Nt, st, 1, None, True) + kept = _core.sym_segment_ranks(seg, nl, ns, z, pt, p, Nt, st, 1, None, True, "test-seg") + _equal(fresh, kept) + + +def test_lanes_along_directions_equal_the_rows(monkeypatch): + calls = _calls(monkeypatch, MODELS["conditions in values"](), reconstruct=True) + _, (tapes, nl, ns, zs, pt, p, nt, *_), _ = [c for c in calls if c[0] == "sym_obs_null_multi"][-1] + nz = len(zs) + ker = _core.sym_obs_null_multi(tapes, nl, ns, zs, pt, p, nt) + free = [c for c in range(nz) if c not in set(np.atleast_1d(ker["pivots"]).tolist())] + assert free + vecs = [null_residues(ker, c, p) for c in free] + off = np.zeros(nz, dtype=np.int64) + off[np.atleast_1d(ker["pivots"])[0]] = 1 + V = np.stack(vecs + [off], axis=1) % p + other = (np.asarray(pt, dtype=np.int64) * 3 + 7) % p + got = _core.sym_obs_annihilates_batch(tapes, nl, ns, zs, np.vstack([pt, other]), [p, p], nt, V) + assert list(got[0]["zero"]) == [True] * len(free) + [False] + # past nz columns the call reads the rows over every coordinate + 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"]) diff --git a/tests/test_monodromy.py b/tests/test_monodromy.py new file mode 100644 index 0000000..0da07aa --- /dev/null +++ b/tests/test_monodromy.py @@ -0,0 +1,83 @@ +"""Points of the fiber by monodromy and their Krawczyk boxes: proposals that only proven maps turn into results.""" + +from fractions import Fraction + +import numpy as np +import pytest +import sympy as spy + +import symident as si +from symident.detection import monodromy as mono +from symident.detection.discrete import Fiber, Series +from symident.detection.fieldproof import generators +from symident.sym.msolve import MsolveMissingError, _msolve_binary + + +def _has_msolve(): + try: + _msolve_binary() + except MsolveMissingError: + return False + return True + + +pytestmark = pytest.mark.skipif(not _has_msolve(), reason="needs msolve") + + +def _series(model): + r = si.detect(model, cores=1) + coords = list(r.info["coordinates"]) + parts, _ = r._fiber_parts(2 * len(coords), "discrete()") + return Series(parts, coords) + + +def _contains(box, z): + return all(re[0] <= v.real <= re[1] and im[0] <= v.imag <= im[1] for (re, im), v in zip(box, z)) + + +def test_the_boxes_of_a_swap_hold_the_point_and_its_image_and_are_disjoint(): + s = _series(si.Model({"x1": "-a*x1", "x2": "-b*x2"}, {"y": "x1 + x2"}, trafo={"x1": "1", "x2": "1"})) + fib = Fiber(s, [3], True) + info, maps = mono.propose(s, fib, target=2) + a, b = (Fraction(info["base"][c]) for c in ("a", "b")) + assert info["certified"] == 2 and mono.disjoint(*info["boxes"]) + assert sum(_contains(bx, [complex(a), complex(b)]) for bx in info["boxes"]) == 1 + assert sum(_contains(bx, [complex(b), complex(a)]) for bx in info["boxes"]) == 1 + assert [{str(k): str(v) for k, v in m.items()} for m in maps] == [{"a": "b", "b": "a"}] + + +def test_the_krawczyk_operator_proves_no_zero_in_a_box_without_one(): + s = _series(si.Model({"x": "-k^4*x"}, {"y": "x"}, trafo={"x": "x0"})) + base = {c: spy.Rational(3, 2) for c in s.cs} + x = np.array([1.5, 1.5], dtype=complex) + rows = mono.square_rows(s, [2], 0, x) + assert mono.krawczyk(s, [2], 0, rows, base, x, [1e-9, 1e-9]) is not None + # the zeros of the square subsystem are i^m * 3/2 in k: a box of radius 0.1 around 1.8 holds none + assert mono.krawczyk(s, [2], 0, rows, base, np.array([1.8, 1.5], dtype=complex), [0.1, 0.1]) is None + + +def test_a_fourth_power_gives_four_certified_points_and_the_maps_over_q_of_i(): + s = _series(si.Model({"x": "-k^4*x"}, {"y": "x"}, trafo={"x": "x0"})) + info, maps = mono.propose(s, Fiber(s, [3], True), target=4) + k = complex(Fraction(info["base"]["k"])) + assert info["certified"] == 4 + for z in (k, 1j * k, -k, -1j * k): + assert sum(_contains(bx, [z, complex(Fraction(info["base"]["x0"]))]) for bx in info["boxes"]) == 1 + K = spy.Symbol("k") + assert sorted((m[K] / K for m in maps), key=str) == sorted([-1, spy.I, -spy.I], key=str) + + +def test_the_orbit_polynomial_of_a_group_over_q_of_i_has_rational_coefficients(): + k, x0 = spy.symbols("k x0") + 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} + + +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) + assert meter.over and info["why"] == "the monodromy reached the cap of 0 term products" diff --git a/tests/test_petab.py b/tests/test_petab.py index 8dcc1a7..a94479c 100644 --- a/tests/test_petab.py +++ b/tests/test_petab.py @@ -360,3 +360,99 @@ def test_a_parameter_that_no_period_changes_leaves_no_input(tmp_path, xi0): assert ("xi" in m.odes) == (xi0 == 1) # a parameter that only vanishing terms hold has no effect assert m.petab["without_effect"] == ["kb"] + + +def _rest_problem(tmp_path, times, conditions="conditionId\tks\nc1\t1\nc2\t2\n"): + """A v1 problem of x' = ks*kp - k*x, observed as x, with the measurements `times` [(condition, time)].""" + libsbml = pytest.importorskip("libsbml") + doc = libsbml.SBMLDocument(3, 2) + model = doc.createModel() + c = model.createCompartment() + c.setId("V"), c.setSize(1), c.setConstant(True) + x = model.createSpecies() + x.setId("x"), x.setCompartment("V"), x.setInitialConcentration(1), x.setHasOnlySubstanceUnits(False) + x.setBoundaryCondition(False), x.setConstant(False) + for name, value in (("k", 1), ("ks", 1)): + p = model.createParameter() + p.setId(name), p.setValue(value), p.setConstant(True) + r = model.createReaction() + r.setId("syn"), r.setReversible(False) + ref = r.createProduct() + ref.setSpecies("x"), ref.setStoichiometry(1), ref.setConstant(True) + r.createKineticLaw().setMath(libsbml.parseL3Formula("ks*kp - k*x")) + p = model.createParameter() + p.setId("kp"), p.setValue(1), p.setConstant(True) + 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") + return si.read_petab(str(tmp_path / "p.yaml")) + + +def test_an_experiment_measured_only_at_inf_is_a_readout_at_rest(tmp_path): + # a readout at rest sees the resting value only, where the trajectory from a known start sees more + m = _rest_problem(tmp_path, [("c1", "inf"), ("c1", "inf"), ("c2", "Inf")]) + assert m.equilibrate is True and m.petab["at_rest"] == ["c1", "c2"] + assert not m.events and not m.inputs + r = detect(m) + assert r.rank == 1 and r.info["rank_status"]["status"] == "proven" + 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")]]) +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 + if all(t == "inf" for c, t in times if c == "c1") and len({c for c, _ in times}) > 1: + with pytest.warns(UserWarning, match="as a trajectory"): + m = _rest_problem(tmp_path, times) + else: + m = _rest_problem(tmp_path, times) + assert m.equilibrate is False and m.petab["at_rest"] == [] + assert detect(m).rank == 2 + + +def test_a_readout_at_rest_starts_from_the_values_of_its_condition(tmp_path): + # a species target of the condition sets the start, not a jump after the rest: the total of a moiety at rest + libsbml = pytest.importorskip("libsbml") + doc = libsbml.SBMLDocument(3, 2) + model = doc.createModel() + c = model.createCompartment() + c.setId("V"), c.setSize(1), c.setConstant(True) + for sp in ("A", "B"): + x = model.createSpecies() + x.setId(sp), x.setCompartment("V"), x.setInitialConcentration(1), x.setHasOnlySubstanceUnits(False) + x.setBoundaryCondition(False), x.setConstant(False) + for name in ("kf", "kb"): + p = model.createParameter() + p.setId(name), p.setValue(1), p.setConstant(True) + r = model.createReaction() + r.setId("conv"), r.setReversible(True) + ref = r.createReactant() + ref.setSpecies("A"), ref.setStoichiometry(1), ref.setConstant(True) + ref = r.createProduct() + ref.setSpecies("B"), ref.setStoichiometry(1), ref.setConstant(True) + r.createKineticLaw().setMath(libsbml.parseL3Formula("kf*A - kb*B")) + 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") + 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)) + assert [str(t[tot]).replace(" ", "") for t in m.trafo] == ["(3)+(1)", "(5)+(1)"] + r = detect(m) + assert r.rank == 1 and [sorted(s.support) for s in r.symmetries] == [["kb", "kf"]] diff --git a/tests/test_projections.py b/tests/test_projections.py new file mode 100644 index 0000000..f1908c5 --- /dev/null +++ b/tests/test_projections.py @@ -0,0 +1,359 @@ +"""Input-output projections of the exact count: support modulo a prime, coefficients interpolated in the parameters, +the relation checked as a polynomial identity.""" + +import math +import random +from fractions import Fraction + +import numpy as np +import pytest + +import symident as si +from symident.detection import fieldproof, ioproj, work +from symident.gfp import all_primes +from symident.sym.msolve import MsolveMissingError, _msolve_binary + + +def _has_msolve(): + try: + _msolve_binary() + except MsolveMissingError: + return False + return True + + +def _captured(model, monkeypatch): + """The arguments of the first exact count of discrete() on the model.""" + got = [] + + 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) + assert got + return got[0] + + +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 ())), []) + + +def test_rational_reconstruction_of_one_variable_finds_unbalanced_degrees(): + p = all_primes()[0] + rng = random.Random(2) + N = [rng.randrange(p) for _ in range(9)] + D = [rng.randrange(p) for _ in range(3)] + [1] + + 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) + # two points short of the degrees: no answer rather than a wrong one + assert ioproj.ratrec1(ts[:12], [ev(N, t) * pow(ev(D, t), -1, p) % p for t in ts[:12]], p) is None + + +def test_sparse_numerators_find_the_terms_of_a_polynomial(): + q = all_primes()[0] + terms = {(1, 0, 2, 0): 3, (0, 1, 0, 1): 5, (2, 2, 0, 0): 7, (0, 0, 0, 0): 11} + + 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()}] + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_a_projection_is_proven_and_a_wrong_coefficient_fails(monkeypatch): + m = si.Model({"x": "-a*x^2 + b*z", "z": "-c*z"}, {"y": "x"}, trafo={"x": "x0", "z": "1"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + rng = random.Random(1) + p = all_primes()[0] + 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] + 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) + # 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) + assert co.run() + assert ioproj.identity(rel, pr, co, pos) + k = next(iter(co.nums[0])) + co.nums[0][k] += Fraction(1, 7) + assert not ioproj.identity(rel, pr, co, pos) + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_the_exact_count_holds_with_projections_alone(monkeypatch): + m = si.Model({"x": "-a*x^2 + b*z", "z": "-c*z"}, {"y": "x"}, trafo={"x": "x0", "z": "1"}) + out = _search_by_projections(m, monkeypatch) + assert out["exact"] is True + assert any(r.startswith("projection of observable 0") and r.endswith("proven") for r in out["relations"]) + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_a_rational_model_is_proven_through_its_projection(monkeypatch): + m = si.Model({"x": "-a*x/(k + x) + z", "z": "-c*z"}, {"y": "x"}, trafo={"x": "x0", "z": "1"}) + out = _search_by_projections(m, monkeypatch) + assert out["exact"] is True + assert any(r.endswith("proven") for r in out["relations"]) + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_the_start_of_an_unobserved_state_has_a_state_projection(monkeypatch): + m = si.Model({"x": "-a*x + z", "z": "-c*z^2"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, 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) + # 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 + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_a_start_quadratic_below_the_profile_has_a_state_projection_with_the_next_derivative(monkeypatch): + m = si.Model({"x": "z^2 - a*x", "z": "b"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, 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) + 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] + outs = fieldproof._Outputs(series, orders) + R, F, cs = outs.exact(4) + t = {spy.Symbol(f"t{i}"): s for i, s in enumerate(series.cs)} + + 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) + for j, (_i, order) in enumerate(outs.index): + if order > 4: + continue + want = (d / math.factorial(order)).xreplace({x: x0, z: 1}) + assert spy.cancel(expr(cs[j]) - want) == 0 + d = sum(spy.diff(d, v) * fv for v, fv in f.items()) + p = all_primes()[0] + rng = random.Random(4) + pts = [[rng.randrange(1, p) for _ in series.cs] for _ in range(5)] + vals, ok = outs.mod_many(pts, p) + for x_, v, good in zip(pts, vals, ok): + old = series.numeric(dict(zip(series.cs, x_)), outs.order, 0, p) + assert good and [int(w) for w in v] == [int(old[i][kk][0]) % p for i, kk in outs.index] + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_counts_of_points_bound_the_newton_polytope_of_a_projection(monkeypatch): + m = si.Model({"x": "-a*x^2 + b*z", "z": "-c*z"}, {"y": "x"}, trafo={"x": "x0", "z": "1"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + rng = random.Random(5) + p = all_primes()[0] + 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) + theta = [rng.randrange(1, p) for _ in idx] + 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) + assert sorted(S) == sorted([(0, 0, 1), (1, 1, 0), (0, 1, 0), (2, 0, 0)]) + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +def test_a_projection_of_higher_degree_in_the_start_is_not_searched_for_a_linear_one(monkeypatch): + m = si.Model({"x": "z^2 - a*x", "z": "b"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + rng = random.Random(6) + p = all_primes()[0] + 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] + 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.newton[ioproj._unit(pr.nb, pr.top)][1] == 2 + + +def test_relations_skip_derivatives_of_derivatives_above_the_term_limit(monkeypatch): + m = si.Model({"x": "-a*x^3 + b*x*z + z^2", "z": "-c*z^2 + x"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + 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) + # 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]) + + +def test_no_projection_reads_the_derivative_of_one_above_the_term_limit(monkeypatch): + m = si.Model({"x": "-a*x^3 + b*x*z + z^2", "z": "-c*z^2 + x"}, {"y": "x"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + monkeypatch.setattr(ioproj, "_JET", 4) + assert ioproj.Projection.output(rel, [3], 0, [], random.Random(1)) is None + lst = ioproj.jets_of(rel)._obs[(0, str(rel.y[0]))][0] + assert all(len(N) <= 4 for N, _, _ in lst[:-1]) + + +@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 + 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] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + rng = random.Random(1) + p = all_primes()[0] + 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 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): + """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) + series, orders, grp, syms, inputs = args[:5] + monkeypatch.setattr(fieldproof, "io_functions", lambda *a, **k: iter(())) + monkeypatch.setattr(fieldproof, "projection_functions", lambda *a, **k: iter(())) + 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 ())), []) + + +def _saturable(): + return si.Model({"x1": "a1*(x2 - x1) - ka*x1/(kc + x1)", "x2": "a2*(x1 - x2)"}, {"y": "x1"}) + + +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() + rel = fieldproof._relations(series, syms) + got = elim.eliminate_relations(rel, random.Random(1), math.inf) + (P,) = got["relations"].values() + y0, y1, y2, a1, a2, ka, kc = spy.symbols("si_y0_0 si_y0_1 si_y0_2 a1 a2 ka kc") + names = {n: spy.Symbol(n) for n in got["ring"].names} + expr = spy.sympify(str(P).replace("^", "**"), locals=names) + # (kc + y)^2 y'' + (a1 + a2) (kc + y)^2 y' + ka kc y' + a2 ka y (kc + y), up to a constant + want = (kc + y0) ** 2 * y2 + (a1 + a2) * (kc + y0) ** 2 * y1 + ka * kc * y1 + a2 * ka * y0 * (kc + y0) + assert spy.cancel(expr / want).is_number + + +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() + rel = fieldproof._relations(series, syms) + got = elim.eliminate_relations(rel, random.Random(1), math.inf) + (P,) = got["relations"].values() + R = got["ring"] + el = elim.Eliminator(rel, random.Random(2), math.inf) + a1, y0 = (R.gens[R.at[n]] for n in ("a1", "si_y0_0")) + kept = el.keep(P * (a1 + y0) * (y0 + 1), extra=[a1 - 1]) + assert kept == P or kept == -P + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +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"]) + # 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"} + + +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) + A, B = elim._subresultant1(f, g, 0) + # A v + B is a combination of f and g, so it vanishes at their common root v = a + assert (A * a + B).is_zero() and not A.is_zero() + + +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() + rel = fieldproof._relations(series, syms) + with pytest.raises(ValueError, match="past the cap elimination_terms of 2"): + elim.eliminate_relations(rel, random.Random(1), 2) + + +@pytest.mark.skipif(not _has_msolve(), reason="needs msolve") +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"]) + + +@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") diff --git a/tests/test_reduce.py b/tests/test_reduce.py index 26ec293..773ec71 100644 --- a/tests/test_reduce.py +++ b/tests/test_reduce.py @@ -778,12 +778,12 @@ def test_unmoved_monomial_searched_as_one_symbol(): assert not any("si_w" in s for s in texts) -def test_section_search_stops_at_timeout(): +def test_section_search_stops_at_its_work_cap(): f = {"c": "k0 - kd*c", "x": "w*(q + b*c) - x"} pos = ["c", "k0", "kd", "w", "b", "x"] res = det(f, {"y": "x"}, gauge=None, reconstruct=True, positive=pos) - r = red(res, positive=pos, timeout=0) - assert any(b["status"] == "invariant_only" and "timeout" in (b.get("reason") or "") + 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")) @@ -1096,6 +1096,18 @@ def test_the_sign_changes_of_undecided_coefficients_are_counted_without_enumerat assert _interval(spy.Poly(sum((a**2 + 1) * x**k for k in range(1, 12)) - 1, x), True) +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) + assert DOMAIN.get("work_cap") is None + 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"] + + 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") @@ -1108,6 +1120,18 @@ def test_a_triangular_solve_says_when_a_branch_may_be_missing(): assert tri_solve([spy.Integer(1)], ["x"], info) == [] and info["complete"] +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) + info = {"complete": True} + assert tri_solve([x**2 - a, y - big], ["x", "y"], info) == [] and not info["complete"] + info = {"complete": True} + assert len(tri_solve([x**2 - a, y - x - a], ["x", "y"], info)) == 2 and info["complete"] + + def test_a_rank_of_exact_numbers_is_certified(): from symident.reduction.invariants import certified_rank assert certified_rank([[1, 2], [2, 4]]) == 1 @@ -1371,8 +1395,7 @@ 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"}]) - with pytest.warns(UserWarning, match="verified, not proven"): - red = si.detect(m, reconstruct=True).reduce(check=False) + 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 assert red.remaining == [] and red.blocks[0]["pins"]["alpha"] == "1" and red.blocks[0]["injective"] @@ -1385,3 +1408,114 @@ def test_translations_of_log_coordinates_are_scalings(): assert not r.remaining and r.level == "exact" and r.checks["pins"] and r.checks["invariants"] assert sorted(v for v in r.trafo.values() if v == "0") == ["0", "0"] assert all(b["type"] == "scaling" for b in r.blocks) + + +@pytest.fixture +def positive_domain(): + from symident.reduction.sign import set_positive + + def declare(names): + set_positive(list(names)) + old = set_positive(None) + yield declare + set_positive(old) + + +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 + + +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"}} + out = _rebased([{"type": "scaling"}, curved_dir], [1], [blk]) + # X + S, divided by the common factor P + assert blk["pins"] == {"b": "1"} and out[1]["generator"] == {"a1": "b", "a2": "c", "P": "1"} + + +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"}] + 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] + # the product alone changes sign along the second generator, the pair has a Jacobian of one sign + assert section_monotone(["a1*a2", "1"], preps, xi_of, loc, [{}]) is None + assert section_jacobian([["a1*a2", "1"], ["b11", "b22"]], preps, xi_of, loc) + assert not section_jacobian([["b11", "b22"], ["b11", "1"]], preps, xi_of, loc) + + +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"] + try: + a1, a2, b11, b21, b22, P1, P2 = spy.symbols("a1 a2 b11 b21 b22 P1 P2") + 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} + assert section_injective(inv, sol, ["t1", "t2", "t3", "t4"], [], [(a1 * a2, spy.Integer(1)), (b11, b22)]) + finally: + sign.DOMAIN["real_carriers"] = old + + +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 + + +def test_the_carriers_are_solved_without_the_unbounded_solver(monkeypatch): + from symident.reduction import solve + + 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) + # a discriminant with a negative content keeps the roots real + assert len(br) == 2 and not any(e.has(spy.I) for d in br for e in d.values()) + for d in br: + sub = {a1: d["a1"], a2: d["a2"]} + assert spy.simplify((a1 * b - a2 - q1).subs(sub)) == 0 and spy.simplify((a1 + a2**2 - q2).subs(sub)) == 0 + + +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], {}, []) + 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 + + +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"}}]} + 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_rest_nonrational.py b/tests/test_rest_nonrational.py index 4016ec6..9a1549d 100644 --- a/tests/test_rest_nonrational.py +++ b/tests/test_rest_nonrational.py @@ -84,6 +84,19 @@ def test_hodgkin_huxley_offset_at_rest(): assert same_direction(parameter_form(hand.symmetries[0], ("V0",)), {k: v for k, v in shift.items() if k != "EL"}) +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)) + (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"}) + + # ---- small models: a trigonometric and a logarithmic term of a state at rest def test_trigonometric_state_at_rest(): diff --git a/tests/test_rjson.py b/tests/test_rjson.py index f78fe7d..cb02558 100644 --- a/tests/test_rjson.py +++ b/tests/test_rjson.py @@ -1,7 +1,6 @@ """The JSON interface for host languages: arguments in, results out, state restored.""" import json -import math import os from fractions import Fraction @@ -14,11 +13,11 @@ def test_kwargs_of_maps_host_spellings(): kw = rjson.kwargs_of({"f": {"x": "-k*x"}, "trafo": None, "gauge_preference": "AUTO", - "control": {"timeout": "Inf", "term_cap": 7, "degree_cap": None}, + "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"]["timeout"] == math.inf and kw["control"]["term_cap"] == 7 + assert kw["control"]["term_cap"] == 7 assert rjson.kwargs_of({"gauge_preference": ["k"]})["gauge_preference"] == ["k"] @@ -39,7 +38,7 @@ def test_detect_and_reduce_round_trip(monkeypatch): assert (res["rank"], res["dim"], res["identifiable"]) == (2, 3, False) assert res["info"]["kernel"] is None and res["warnings"] == [] assert [d["weights"] for d in res["symmetries"]] == [{"s": "1", "x": "-1"}] - red = json.loads(rjson.reduce_json(out, json.dumps({"timeout": "Inf"}))) + red = json.loads(rjson.reduce_json(out, json.dumps({"work_cap": 4000}))) assert (red["removed"], red["remaining"], red["warnings"]) == (["X₁"], [], []) diff --git a/tests/test_select.py b/tests/test_select.py new file mode 100644 index 0000000..995ee8f --- /dev/null +++ b/tests/test_select.py @@ -0,0 +1,94 @@ +"""Conditions chosen at a random point: the analysis on the conditions that change the rank, the directions proven on +the others.""" + +import warnings + +import pytest + +import symident as si +from symident.detection.observability import select + +K = 30 + + +def model(extra=None, obs=None, odes=None, rest=False): + """x' = k1*u - k2*x seen as y = s*x in K conditions that set u, from x = 0 or at rest; `extra` gives the + observables of one condition.""" + observables = [dict(obs or {"y": "s*x"}) for _ in range(K)] + 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) + + +def run(m, monkeypatch, on): + if on: + monkeypatch.delenv("SYMIDENT_NOSELECT", raising=False) + else: + monkeypatch.setenv("SYMIDENT_NOSELECT", "1") + return si.detect(m, reconstruct=True, cores=1) + + +def same(a, b): + assert (a.rank, a.dim) == (b.rank, b.dim) + assert a.info["rank_status"]["status"] == b.info["rank_status"]["status"] + assert sorted(sorted(s.support) for s in a.symmetries) == sorted(sorted(s.support) for s in b.symmetries) + assert sorted(s.level for s in a.symmetries) == sorted(s.level for s in b.symmetries) + + +@pytest.mark.parametrize("rest", [False, True]) +def test_redundant_conditions_give_the_result_of_all_conditions(monkeypatch, rest): + m = model(rest=rest) + on, off = run(m, monkeypatch, True), run(m, monkeypatch, False) + same(on, off) + sel = on.info["selection"] + assert sel["conditions"] == K and len(sel["kept"]) < K and off.info["selection"] is None + assert on.info["rank_status"]["status"] == "proven" and on.rank == (1 if rest else 2) + + +@pytest.mark.parametrize("rest", [False, True]) +def test_a_direction_that_is_no_scaling_is_proven_on_the_conditions_left_out(monkeypatch, rest): + m = model(odes={"x": "(k1 + k3)*u - k2*x"}, rest=rest) + on, off = run(m, monkeypatch, True), run(m, monkeypatch, False) + same(on, off) + assert on.info["rank_status"]["status"] == "proven" + assert on.info["selection"]["dropped_by"]["lift"] > 0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + red = on.reduce() + assert all(b["status"] == "reduced" for b in red.blocks) + + +@pytest.mark.parametrize("rest", [False, True]) +def test_a_condition_with_new_coordinates_is_kept(monkeypatch, rest): + m = model(extra=(17, {"y": "s*x*q17*r17"}), rest=rest) + on, off = run(m, monkeypatch, True), run(m, monkeypatch, False) + same(on, off) + assert 17 in on.info["selection"]["kept"] + assert ["q17", "r17"] in [sorted(s.support) for s in on.symmetries] + + +@pytest.mark.parametrize("rest", [False, True]) +def test_a_direction_that_fails_on_a_condition_left_out_brings_the_condition_back(monkeypatch, rest): + # a condition left out where a direction of the others is no symmetry joins the analysis + m = model(extra=(29, {"y": "x"}), rest=rest) + choose, choose_resting = select.choose, select.choose_resting + + 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) + monkeypatch.setattr(select, "choose", choose) + monkeypatch.setattr(select, "choose_resting", choose_resting) + off = run(m, monkeypatch, False) + same(on, off) + assert 29 in on.info["selection"]["kept"] and on.info["selection"]["rounds"] == 2 + + +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": {}}) + assert run(m, monkeypatch, True).info["selection"] is None diff --git a/tests/test_series_start.py b/tests/test_series_start.py index cf546ff..de35b1b 100644 --- a/tests/test_series_start.py +++ b/tests/test_series_start.py @@ -238,6 +238,24 @@ 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"}), +]) +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}) + assert res.dim - res.rank == 1 + assert res.info["rank_status"]["status"] == "proven" + assert [(d["level"], d["generator"]) for d in res.symmetries] == [("exact", {"g": "g", "p": "p"})] + + +def test_power_scaling_refused(): + # a term linear in the base forbids the scaling of the power + res = det(F_POW, {"y": "x^a/(g^a + x^a) + x"}, trafo={"x": "0"}) + assert res.rank == res.dim + + def test_power_order_not_proven(): res = det(F_POW, {"y": "x^a/(g^a + x^a)"}, trafo={"x": "0"}) assert not res.info["lie_certified"] diff --git a/tests/test_switching.py b/tests/test_switching.py index 88e709a..21cfa0e 100644 --- a/tests/test_switching.py +++ b/tests/test_switching.py @@ -522,6 +522,36 @@ def test_fresh_coordinates_that_drop_rank_together_are_checked_at_a_random_point assert st["status"] == "verified" and 0 < st["probability"] < 1e-4 +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"}) + assert r.identifiable and r.dim == 3 + assert r.info["projection"] is None and r.info["rank_status"]["status"] == "proven" + + +def test_a_fresh_value_that_a_held_state_hides_enters_no_row(): + ev = [{"var": "U", "root": "U - c", "value": "0", "method": "replace"}] + r = det({"U": "-p*V*U", "V": "-d*V"}, {"y": "s*U"}, trafo={"U": "u0", "V": "1"}, events=ev) + assert (r.rank, r.dim) == (4, 5) and r.symmetries[0].support == ["c", "s", "u0"] + assert r.info["projection"] is None and r.info["rank_status"]["status"] == "proven" + + +def test_start_points_whose_fresh_columns_drop_rank_are_left_out_of_the_proof(): + 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"}) + assert (r.rank, r.dim) == (3, 4) and r.symmetries[0].support == ["x1", "x2"] + assert r.info["projection"]["status"] == "proven" and r.info["rank_status"]["status"] == "proven" + + +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": {}}) + assert (r.rank, r.dim) == (5, 6) + + def test_a_state_that_every_regime_keeps_at_zero_leaves_the_model(): f = {"x1": "-c*x1", "x2": "piecewise(0, x1 > h, -k*x2)"} g = {"y1": "x1", "y2": "x2"} diff --git a/tests/test_unknown_inputs.py b/tests/test_unknown_inputs.py index 2bed4bc..76d621d 100644 --- a/tests/test_unknown_inputs.py +++ b/tests/test_unknown_inputs.py @@ -161,3 +161,97 @@ def test_full_rank_with_unknown_inputs_is_verified(): st = r.info["rank_status"] assert r.identifiable and r.info["projection"]["status"] == "verified" assert st["status"] == "verified" and 0 < st["probability"] < 1e-6 + + +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) + 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 + for s in r.symmetries: + assert s.input_change is None or any(str(v) != "0" for v in s.input_change.values()) + assert not set(s.state_components or {}) - {"x"} + + +# a flux w between two states: one direction moves N, d and the initial values, and w absorbs it +FLUX = ({"a": "-w*a", "b": "w*a - d*b"}, {"y1": "a + b", "y2": "N*b"}) + + +def test_a_pointwise_lift_reduces_a_direction_the_input_absorbs(): + r = si.detect(si.Model(*FLUX, unknown_inputs=["w"]), reconstruct=True) + (s,) = r.symmetries + assert s.level == "exact" and {"N", "d"} <= set(s.generator) + red = si.reduce(r) + assert red.removed and not red.remaining and red.checks["loop"]["ok"] + (b,) = red.to_dict()["blocks"] + assert b["inputs"]["proof"] == "lift" and b["inputs"]["absorb"] == ["w"] + assert {k for k, v in red.trafo.items() if v != k} <= {"N", "d"} + assert "Unknown inputs:" in repr(red) + # the lift satisfies D(xi_x) = V(f) and V(h) = 0 as identities + (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()} + 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 + assert spy.cancel(act(a + bb)) == 0 and spy.cancel(act(N * bb)) == 0 + + +TWO_COMPARTMENTS = {"x1": "-(k12 + k1e)*x1 + k21*x2 + b*u", "x2": "k12*x1 - k21*x2"} + + +def test_the_inversion_of_the_input_proves_every_section(): + r = si.detect(si.Model(TWO_COMPARTMENTS, {"y1": "x1"}, unknown_inputs=["u"]), reconstruct=True) + red = si.reduce(r) + assert len(red.removed) == 5 and not red.remaining + for b in red.to_dict()["blocks"]: + assert b["inputs"]["proof"] == "inversion" and b["inputs"]["determinant"] == "b" + assert "u positive" in b["inputs"]["condition"] + + +def test_a_direction_without_a_proof_that_the_input_absorbs_it_stays(): + # a second, separate observable leaves no inversion; the rates of the hidden compartment need a lift that + # depends on the past of the trajectory + odes = dict(TWO_COMPARTMENTS, z="-m*z") + r = si.detect(si.Model(odes, {"y1": "x1", "y2": "z"}, unknown_inputs=["u"]), reconstruct=True) + red = si.reduce(r) + gens = dict(zip([f"X{c}" for c in "₁₂₃₄₅"], [s.generator for s in r.symmetries])) + left = {k for b in red.to_dict()["blocks"] if b["status"] == "unresolved" for k in gens[b["labels"][0]]} + assert "k21" in left and "x2" in left + assert all("pointwise lift" in b["reason"] for b in red.to_dict()["blocks"] if b["status"] == "unresolved") + done = {k for b in red.to_dict()["blocks"] if b["status"] == "reduced" for k in gens[b["labels"][0]]} + assert {"b", "k1e"} <= done + + +def test_the_count_takes_the_jets_of_an_unknown_input_as_unknowns(): + # x -> -x with w -> -w keeps the output: an exact map of the states and the input + r = si.detect(si.Model({"x": "-k*x + w"}, {"y": "x^2"}, unknown_inputs=["w"]), reconstruct=True) + out = r.discrete() + info = out["info"] + assert info["count"] == 2 and info["certificate"]["complete"] == "verified" and 0 < info["count_bound"] < 1e-6 + (s,) = out["symmetries"] + assert s["map"] == {"x": "-x"} and s["level"] == "exact" and s["state_maps"] == [{"x": "-x", "w": "-w"}] + + +def test_the_count_leaves_out_the_jets_the_output_does_not_read(): + # the flux cancels in y1: the jets above the order the outputs read would leave a free direction + r = si.detect(si.Model(*FLUX, unknown_inputs=["w"]), reconstruct=True) + info = r.discrete()["info"] + assert info["count"] == 1 and info["certificate"]["complete"] == "verified" + assert info["reduced"]["coordinates"] and "w" not in info["reduced"]["coordinates"] + + +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"]}}) + 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"]