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
-[](https://github.com/dModverse/symident/actions/workflows/wheels.yml)
-[](https://dmodverse.github.io/symident/)
+[](https://github.com/dModverse/symident/actions/workflows/ci.yml)
+[](https://pypi.org/project/symident/)
+[](https://dmodverse.github.io/symident/)
[](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