From 3501b174acd446602d2c35829dd07fc90b665cdb Mon Sep 17 00:00:00 2001 From: Simon Beyer <64092903+simonbeyer1@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:01:25 +0100 Subject: [PATCH] feat(detection): the stage tower pins the coordinates one condition at a time and tests the claims over Q with a bound, across events at known times; premises in place of the level axiom, checked for a count modulo the prime without a bound; output saturation of the elimination with known inputs; resting balances without a rational solution, square roots in starts and switches on the clock by exchange of coordinates; the work of msolve per round of F4 with a cap shared by the calls of one count; product jets in the fiber, derivatives of the observables from Taylor coefficients in the C++ kernel and FLINT polynomials in the searches; search_entries 2 * 10^9; msolve 0.11.0 with OpenMP; the method chapters without proofs, with an index of terms; symident 0.18.3 Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 132 +++ cpp/ioproj.cpp | 254 ++++ docs/_static/custom.css | 5 + docs/conf.py | 2 +- docs/guide/detection.rst | 10 +- docs/guide/global.rst | 39 +- docs/guide/inputs.rst | 20 +- docs/guide/models.rst | 8 +- docs/guide/reduction.rst | 29 +- docs/guide/settings.rst | 4 + docs/index.rst | 5 +- docs/method.rst | 37 +- docs/method/{proofs.rst => certificates.rst} | 79 +- docs/method/conditions.rst | 69 +- docs/method/global.rst | 404 ++++--- docs/method/local.rst | 84 +- docs/method/reduction.rst | 31 +- docs/refs.bib | 11 + pyproject.toml | 2 +- src/symident/__init__.py | 2 +- src/symident/api.py | 215 +++- src/symident/detection/clock.py | 124 ++ src/symident/detection/discrete.py | 485 ++++++-- src/symident/detection/elim.py | 332 +++++- src/symident/detection/fewcoef.py | 78 +- src/symident/detection/fieldproof.py | 215 +++- src/symident/detection/fields.py | 8 +- src/symident/detection/gauge.py | 2 +- src/symident/detection/hybrid.py | 2 +- src/symident/detection/ioproj.py | 276 +++-- src/symident/detection/multiexp.py | 86 +- .../detection/observability/analysis.py | 21 +- src/symident/detection/observability/joint.py | 24 +- src/symident/detection/observability/proof.py | 10 +- src/symident/detection/relax.py | 152 +++ src/symident/detection/restchart.py | 120 ++ src/symident/detection/tower.py | 1046 +++++++++++++++++ src/symident/detection/work.py | 123 +- src/symident/install.py | 4 +- src/symident/petab.py | 4 +- src/symident/reduction/branches.py | 2 +- src/symident/report.py | 6 +- src/symident/sym/charts.py | 2 +- src/symident/sym/exact.py | 2 +- src/symident/sym/recast.py | 8 +- src/symident/sym/restforward.py | 42 +- src/symident/sym/tape.py | 2 +- src/symident/tools/build-msolve.sh | 22 +- tests/test_discrete.py | 270 ++++- tests/test_exact.py | 44 + tests/test_experiments.py | 17 +- tests/test_install.py | 8 +- tests/test_projections.py | 89 ++ tests/test_rest_start.py | 14 + tests/test_tower.py | 183 +++ 55 files changed, 4493 insertions(+), 772 deletions(-) rename docs/method/{proofs.rst => certificates.rst} (79%) create mode 100644 src/symident/detection/clock.py create mode 100644 src/symident/detection/tower.py create mode 100644 tests/test_tower.py diff --git a/NEWS.md b/NEWS.md index d086ed4..87b2fe3 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,135 @@ +# symident 0.18.3 + +## Global analysis + +* The level `"axiom"` of `certificate["complete"]` is gone. A count modulo the prime without an + error bound is `"checked"`, with the statement it rests on under `unbounded`. A property of the + model that the count rests on is listed under `certificate["premises"]`, each `{"kind", "text"}` + (`"independent_starts"`, `"start_power"`, `"generic_event_state"`), and no longer lowers the + level: the count holds at the stated level where the premises hold. `certificate["premise"]` and + `certificate["axiom"]` are removed. +* The default of `search_entries` is 2 * 10^9 instead of 5 * 10^8. +* A count of one modulo the prime without a count over Q is taken over Q once more with ten times + the cap `msolve_work` before the stage tower. +* A switch on the clock alone, piecewise in `time` against a number or a coordinate declared + positive, is an indicator state that an event at the time of the switch sets from 0 to 1, so + `discrete()` takes it as a model with events. +* A start that holds the square root of a polynomial of the coordinates, as closed-form steady + states of a quadratic balance do, is a coordinate in exchange for one coordinate solved from it, + as in the resting chart: a count of one in this chart is one for the model + (`info["discrete"]["rest_exchange"]` with `kind` `"root"`). +* The stage tower pins the coordinates one condition at a time where the exact search and the + short count find no orbit and no candidate map exists: at rising orders, the part of the system + of one condition that the kernel of the Jacobian determines is solved modulo a prime on a random + cut, with the coordinates pinned before as numbers. The list of claims is then tested over Q at + a random integer point, which bounds the probability of a false claim by the degrees of the + rows of each condition. With every coordinate accepted, the result is `verified`, and + `info["discrete"]["tower"]` lists the claims. The units are the segments of the conditions + without switches, free powers and unknown inputs; the work caps are `tower_stages` and + `tower_work`, the work of F4 of all calls of msolve of the stage tower together. Before a whole + part, a stage tries per coordinate the fewest equations around it that determine it at the + point. A start that is a rational function of the coordinates has the denominator in the + saturation, and the stage tower takes it. +* The stage tower crosses events: a segment after an event at a known time is a unit whose + starts are known where the state rests at a known value before or the event sets it, and new + coordinates otherwise; a claim on such a start adds the premise `"generic_event_state"`. An event + time that is a coordinate is pinned where an output coefficient jumps at the event. +* The relaxed model also bounds the count where the directions that move the new coordinates or + the coordinates their starts read are not invertible on the new coordinates: where these + directions commute and change each condition of a new coordinate at a rate constant along their + orbits, an orbit meets the starts in a connected set. Where the rates vary along the orbits, a + choice of conditions whose matrix of rates has principal minors of one sign on the domain makes + the conditions injective along the orbits, and the count bounds the points of the fiber in the + domain. +* Under `equilibrate`, balances with no rational solution in the states no longer stop + `discrete()`: the resting values become coordinates in place of coordinates solved from the + balances where these enter linearly (`info["discrete"]["rest_exchange"]`). A count of one there + is one for the model. +* The work of msolve is measured per round of F4 from the output of msolve: the columns of the matrix times + the pairs selected and the basis before it, and the new elements times the pairs after it. A + round is charged at the header with the widest matrix so far, so a call ends before the symbolic + preprocessing of a round past the cap. The cap `msolve_entries` is replaced by `msolve_work` + (10^10 by default), `quick_entries` by `quick_work`. The nonzero entries of the matrices still + count against `search_entries`. +* The calls of msolve of one count, over the blocks and stages, share twice the cap + `msolve_work`; past it the count ends with a reason. +* The search of candidate permutations rejects a permutation at the least of the doubling orders + where the output coefficients differ, instead of forming the series up to the full order for + every permutation. +* `elimination_terms` also bounds the minors of the determinants of the elimination, one at a + time and together, and the elimination factors polynomials of at most 200 terms; a larger one + is kept whole. +* The jets of the observables in the search for input-output relations form a product only within + 25 * 10^6 term products, and the derivative of the common denominator only where a derivative + needs it. +* Under `equilibrate`, resting balances of degree one in the resting states are solved by + elimination over the rational functions of the coordinates, whatever the size of the coupled + block. +* The route of several experiments names a fixed start or a switch before the number of conditions + as the reason it does not apply. +* `discrete()` on a model whose reduced form has no shared columns in a condition no longer fails + in the rank of the stacked conditions. +* The fiber holds the jets of a state only up to the order that the observables read, directly or + through the equations of other jets, in conditions without events. +* A monomial of three or more state factors enters the fiber as a chain of product jets, each the + product of two series order by order, in conditions without events: an equation of the fiber + then has as many terms as the order instead of a power of it. The count is that of the same + fiber, since every product jet takes one value at each point of the fiber. +* The rational reconstruction of the input-output projections and the few-coefficient search runs + in the C++ kernel, column by column on the threads of the analysis. +* The searches of the exact count and of the projections take the derivatives of the observables + at their sample points from the Taylor coefficients of the trajectory that starts there, modulo + the prime in the C++ kernel; the derivatives as rational functions are formed only for the + identities over Q of a relation found. +* The products of these derivatives count against `search_entries` and end the search while they + are formed. +* Where the short count equals the orbit of the proven candidates, the count over Q runs while the + exact search runs in a separate process, the two sharing the threads of the analysis: an exact + result is kept, and where the search ends without one, the verified count is already there. +* The polynomials of the jets, of the identities over Q and of the equations of the fiber are those + of FLINT (python-flint) instead of SymPy. +* Each observable enters the count of the fiber one order above the order of that observable in the + rank criterion, instead of one above the highest of these orders. +* The count of several experiments takes a state with a fixed start that enters only with a + coordinate, as c x or as c + x, as a state with the start c: the relaxed terms of the states + have such states. +* The elimination of the input-output relations changes the variables: where the state to eliminate + enters the relation of an observable with degree one and a coefficient A x + B in another state x, + A free of the states, x becomes x + B / A. The degrees of the resultants that follow drop, and + models with saturable rates reach their relations within the cap `elimination_terms`. The start of + a state so changed has no relation of the start. +* With a known input and every start of a state a separate coordinate that no right-hand side and + no observable reads, the elimination of the exact count adds observables: the coefficients of the + derivatives of the outputs in the derivatives of the input that raise the rank in the states + (output saturation), and runs before the projections. +* The derivatives of an observable with a denominator, y = M / E, in the projections and the exact + search are those of M / E. +* Where the relaxed model gives a result below `verified`, the route of the reduced model still + runs, and the stronger of the two results is kept. + +## msolve + +* `install_msolve()` builds msolve 0.11.0, with OpenMP where the compiler supports it, so that + calls of msolve run on the `cores` of the analysis; without OpenMP msolve runs on one thread as + before. A build of an earlier version in the cache stays usable until a newer one is built. + +## Resting conditions + +* A forward draw never solves a balance for a rate that divides it: the rate would be zero at every + draw, the draw would rest outside the component of the model, and the Lie order certificate + refused it. +* With resting conditions the stacked pass runs the Lie order certificate; when it proves an order + for every block, the pass takes the kernel at the certified orders and ends without the block + scans. +* The diagonal start and the plans of the forward draws are formed once per model, not in every + pass and pivot set. + +## Benchmark collection + +* Of the models of the benchmark of the manuscript, NFKB1 is now `exact` (by the output + saturation), Blasi `exact` (by the linear resting balances), Alkan and Bachmann `verified` (by + the stage tower) and NFKB2 `verified`; before, these were `open` or rested on the axiom. + # symident 0.18.2 * Under `equilibrate` with a diagonal start, reconstruction and the kernel checks take curve diff --git a/cpp/ioproj.cpp b/cpp/ioproj.cpp index 0717820..834b628 100644 --- a/cpp/ioproj.cpp +++ b/cpp/ioproj.cpp @@ -310,13 +310,267 @@ py::array_t mono_matrix(py::array_t Poly; + +void trim(Poly& a) { + while (!a.empty() && !a.back()) a.pop_back(); +} + +// a - q b modulo p, trimmed +Poly sub_mul(const Poly& a, const Poly& q, const Poly& b, const Mod& md) { + Poly out(std::max(a.size(), q.empty() || b.empty() ? 0 : q.size() + b.size() - 1), 0); + for (size_t i = 0; i < a.size(); ++i) out[i] = a[i]; + for (size_t i = 0; i < q.size(); ++i) + if (q[i]) + for (size_t j = 0; j < b.size(); ++j) out[i + j] = md.sub(out[i + j], md.mul(q[i], b[j])); + trim(out); + return out; +} + +// The rational function of one variable through the points (ts, v): the step of the extended Euclidean algorithm +// before the quotient of largest degree, at least three; false where there is none. As ioproj.ratrec1(). +bool ratrec(const std::vector& ts, const std::vector& dinv, const Poly& m, std::vector c, const Mod& md, + Poly& num, Poly& den) { + const int n = (int)ts.size(); + for (int j = 1; j < n; ++j) + for (int i = n - 1; i >= j; --i) + c[i] = md.mul(md.sub(c[i], c[i - 1]), dinv[(size_t)j * n + i]); + Poly r1(n, 0); + for (int i = n - 1; i >= 0; --i) { + for (int k = n - 1; k >= 1; --k) r1[k] = md.sub(r1[k - 1], md.mul(ts[i], r1[k])); + r1[0] = (md.p - md.mul(ts[i], r1[0])) % md.p; + r1[0] = (r1[0] + c[i]) % md.p; + } + trim(r1); + if (r1.empty()) { + num.clear(); + den.assign(1, 1); + return true; + } + Poly r0 = m, s0, s1(1, 1), bn, bd; + int gap = 2; + bool got = false; + while (!r1.empty()) { + Poly q(r0.size() >= r1.size() ? r0.size() - r1.size() + 1 : 1, 0), r = r0; + const u64 inv = md.inv(r1.back()); + for (int k = (int)r0.size() - (int)r1.size(); k >= 0; --k) { + const u64 a = md.mul(r[k + r1.size() - 1], inv); + q[k] = a; + if (a) + for (size_t j = 0; j < r1.size(); ++j) r[k + j] = md.sub(r[k + j], md.mul(a, r1[j])); + } + r.resize(r1.size() - 1); + trim(q); + trim(r); + if ((int)q.size() - 1 > gap) { + bn = r1; + bd = s1; + gap = (int)q.size() - 1; + got = true; + } + Poly s2 = sub_mul(s0, q, s1, md); + r0.swap(r1); + r1.swap(r); + s0.swap(s1); + s1.swap(s2); + } + if (!got) return false; + const u64 ic = md.inv(bd.back()); + for (auto& x : bn) x = md.mul(x, ic); + for (auto& x : bd) x = md.mul(x, ic); + num.swap(bn); + den.swap(bd); + return true; +} + +// Per column of V (values at the points ts) the (numerator, denominator) of ratrec(), None where there is none. +py::list ratrec_columns(py::array_t ts_in, + py::array_t V, double pIn, int threads) { + check_prime(pIn); + Mod md((u64)pIn); + const int n = (int)V.shape(0), C = (int)V.shape(1); + if ((int)ts_in.shape(0) != n) throw std::runtime_error("points and values differ in number"); + std::vector ts(n); + for (int i = 0; i < n; ++i) ts[i] = residue(ts_in.data()[i], md.p); + Poly m(1, 1); + for (int i = 0; i < n; ++i) { + Poly next(m.size() + 1, 0); + for (size_t k = 0; k < m.size(); ++k) { + next[k + 1] = (next[k + 1] + m[k]) % md.p; + next[k] = md.sub(next[k], md.mul(ts[i], m[k])); + } + m.swap(next); + } + // the inverses of the differences of the points of the divided differences + std::vector dinv((size_t)n * n, 0); + for (int j = 1; j < n; ++j) + for (int i = j; i < n; ++i) dinv[(size_t)j * n + i] = md.inv(md.sub(ts[i], ts[i - j])); + std::vector nums(C), dens(C); + std::vector ok(C, 0); + const i64* D = V.data(); + { + py::gil_scoped_release rel; +#pragma omp parallel for schedule(dynamic) num_threads(threads > 0 ? threads : 1) + for (int e = 0; e < C; ++e) { + std::vector c(n); + for (int i = 0; i < n; ++i) c[i] = residue(D[(size_t)i * C + e], md.p); + ok[e] = ratrec(ts, dinv, m, c, md, nums[e], dens[e]); + } + } + py::list out; + for (int e = 0; e < C; ++e) { + if (!ok[e]) { + out.append(py::none()); + continue; + } + py::list a, b; + for (u64 x : nums[e]) a.append((i64)x); + for (u64 x : dens[e]) b.append((i64)x); + out.append(py::make_tuple(a, b)); + } + return out; +} + } // namespace +// The derivatives y_r^(j) = j! c_j, j <= m, of y_r = M_r / E_r along x_s' Q = F_s at each point modulo p, from the +// Taylor coefficients c_j there; polynomials F_0..F_{S-1}, Q, M_0, E_0, M_1, ... in the layout of poly_eval, `states` +// the state variables. A row is -1 where Q or an E vanishes at the point. +py::array_t lie_values(py::array_t exps, + py::array_t coef, + py::array_t off, + py::array_t states, + py::array_t pts, int m, double pIn, + int threads) { + check_prime(pIn); + Mod md((u64)pIn); + const int T = (int)exps.shape(0), V = (int)exps.shape(1), M = (int)pts.shape(0); + const int S = (int)states.shape(0), NP = (int)off.shape(0) - 1, R = (NP - S - 1) / 2; + if (pts.shape(1) != V || NP != S + 1 + 2 * R) throw std::runtime_error("lie_values: inconsistent layout"); + const int32_t* E = exps.data(); + const i64* O = off.data(); + std::vector slot(V, -1); + for (int s = 0; s < S; ++s) slot[states.data()[s]] = s; + // the monomials in the states with a parent of one degree less, shared by every point + std::vector > mon(1, std::vector(S, 0)); + std::vector > parent(1, {-1, -1}); + std::vector termMon(T); + // a linear search is enough for the few monomials of the right-hand sides and observables + for (int t = 0; t < T; ++t) { + std::vector e(S, 0); + for (int v = 0; v < V; ++v) + if (slot[v] >= 0) e[slot[v]] = E[t * V + v]; + // insert e and the chain of parents of e + std::vector > chain; + std::vector cur = e; + int at = -1; + while (true) { + auto it = std::find(mon.begin(), mon.end(), cur); + if (it != mon.end()) { + at = (int)(it - mon.begin()); + break; + } + chain.push_back(cur); + int a = 0; + while (cur[a] == 0) ++a; + cur[a] -= 1; + } + for (int c = (int)chain.size() - 1; c >= 0; --c) { + // the variable that the parent lacks: the first nonzero entry, as in the descent above + int a = 0; + while (chain[c][a] == 0) ++a; + mon.push_back(chain[c]); + parent.push_back({at, a}); + at = (int)mon.size() - 1; + } + termMon[t] = (int)(std::find(mon.begin(), mon.end(), e) - mon.begin()); + } + const int NM = (int)mon.size(); + std::vector C(T); + for (int t = 0; t < T; ++t) C[t] = residue(coef.data()[t], md.p); + std::vector invk(m + 2, 1), fact(m + 1, 1); + for (int k = 1; k <= m + 1; ++k) invk[k] = md.inv((u64)k); + for (int k = 1; k <= m; ++k) fact[k] = md.mul(fact[k - 1], (u64)k); + py::array_t out({M, R * (m + 1)}); + i64* Rout = 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) { + const i64* P = pts.data() + (size_t)i * V; + std::vector ct(T); + for (int t = 0; t < T; ++t) { + u64 x = C[t]; + for (int v = 0; v < V && x; ++v) { + int e = E[t * V + v]; + if (e && slot[v] < 0) x = md.mul(x, md.pow(residue(P[v], md.p), (u64)e)); + } + ct[t] = x; + } + std::vector > X(S, std::vector(m + 1, 0)), D(S, std::vector(m, 0)); + std::vector > ser(NM, std::vector(m + 1, 0)); + for (int s = 0; s < S; ++s) X[s][0] = residue(P[states.data()[s]], md.p); + ser[0][0] = 1; + auto monOrder = [&](int k) { + for (int j = 1; j < NM; ++j) { + const std::vector& a = ser[parent[j].first]; + const std::vector& b = X[parent[j].second]; + u64 s = 0; + for (int l = 0; l <= k; ++l) s = md.red(s + md.mul(a[l], b[k - l])); + ser[j][k] = s; + } + }; + auto value = [&](int poly, int k) { + u64 s = 0; + for (i64 t = O[poly]; t < O[poly + 1]; ++t) s = md.red(s + md.mul(ct[t], ser[termMon[t]][k])); + return s; + }; + bool ok = true; + std::vector q(m + 1, 0); + for (int k = 0; k < m && ok; ++k) { + monOrder(k); + q[k] = value(S, k); + if (k == 0 && q[0] == 0) ok = false; + if (!ok) break; + u64 iq = md.inv(q[0]); + for (int s = 0; s < S; ++s) { + u64 rest = 0; + for (int l = 1; l <= k; ++l) rest = md.red(rest + md.mul(q[l], D[s][k - l])); + D[s][k] = md.mul(md.sub(value(s, k), rest), iq); + X[s][k + 1] = md.mul(D[s][k], invk[k + 1]); + } + } + if (ok) monOrder(m); + for (int r = 0; r < R && ok; ++r) { + std::vector y(m + 1, 0); + u64 e0 = value(S + 1 + 2 * r + 1, 0); + if (e0 == 0) { + ok = false; + break; + } + u64 ie = md.inv(e0); + for (int k = 0; k <= m; ++k) { + u64 rest = 0; + for (int l = 1; l <= k; ++l) rest = md.red(rest + md.mul(value(S + 2 + 2 * r, l), y[k - l])); + y[k] = md.mul(md.sub(value(S + 1 + 2 * r, k), rest), ie); + Rout[(size_t)i * R * (m + 1) + r * (m + 1) + k] = (i64)md.mul(y[k], fact[k]); + } + } + if (!ok) + for (int c = 0; c < R * (m + 1); ++c) Rout[(size_t)i * R * (m + 1) + c] = -1; + } + } + return out; +} + void register_ioproj(py::module_& m) { + m.def("io_lie_values", &lie_values, py::arg("exps"), py::arg("coef"), py::arg("off"), py::arg("states"), + py::arg("points"), py::arg("m"), py::arg("p"), py::arg("threads") = 1); 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_ratrec", &ratrec_columns, py::arg("ts"), py::arg("V"), 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/docs/_static/custom.css b/docs/_static/custom.css index c307cfe..7e70896 100644 --- a/docs/_static/custom.css +++ b/docs/_static/custom.css @@ -26,6 +26,11 @@ html { max-width: 100ch; } +/* Tables start at the left edge of the text, as the prose does. */ +.bd-article table { + margin-left: 0; +} + /* 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 { diff --git a/docs/conf.py b/docs/conf.py index 86482af..7440655 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -70,7 +70,7 @@ def _chapters(doc): (d, _title(d), _chapters(d) if d in ("guide", "method") else []) for d in ("install", "quickstart", "guide", "method", "api") ] - + [("changelog", "Changelog", [])] + + [("changelog", "Changelog", []), ("genindex", "Index", [])] } # citations: numbered in the order cited, in the reference format of IEEE, as on the dMod2 and cppDE sites diff --git a/docs/guide/detection.rst b/docs/guide/detection.rst index da05368..00f570c 100644 --- a/docs/guide/detection.rst +++ b/docs/guide/detection.rst @@ -47,10 +47,10 @@ of the coordinate ``θ`` along the direction; coordinates that do not change are directions are grouped by the geometry of their orbits, ``Symmetry.kind``: - a *scaling* has components ``ξ(θ) = w θ`` with integer weights ``w``, so it multiplies the - coordinates by powers of one factor; its orbits are lines in logarithmic coordinates, and its + coordinates by powers of one factor; the orbits are lines in logarithmic coordinates, and the invariants are monomials; -- a *translation* has constant components, so it shifts the coordinates; its orbits are lines in - linear coordinates, which end on the boundary of the positive orthant, and its invariants are +- a *translation* has constant components, so it shifts the coordinates; the orbits are lines in + linear coordinates, which end on the boundary of the positive orthant, and the invariants are linear; - every other direction is *curved*. @@ -66,7 +66,7 @@ stay the same: Levels and rank status ---------------------- -A direction is proven, checked with an error bound, or checked without one. Its ``level`` is +A direction is proven, checked with an error bound, or checked without one. The ``level`` is ``exact`` proven over Q; @@ -82,7 +82,7 @@ A direction is proven, checked with an error bound, or checked without one. Its non-identifiable directions. ``info["rank_status"]`` gives the status and the reason, the printout flags an unproven rank, and :ref:`levels` states when each applies. -``res.symmetries`` lists :class:`~symident.Symmetry` objects, with the generator, its +``res.symmetries`` lists :class:`~symident.Symmetry` objects, with the generator, the ``level``, ``kind`` (scaling, translation or curved), ``type`` (scaling or general), ``support``, the coordinates it moves, and ``route``, the way the closed form was obtained (:ref:`general-directions`). ``res.summary()`` adds the Lie order, diff --git a/docs/guide/global.rst b/docs/guide/global.rst index 6e0a5e8..cfcb68d 100644 --- a/docs/guide/global.rst +++ b/docs/guide/global.rst @@ -15,9 +15,9 @@ second step on a result of a local detection. ``global_options`` passes the argu :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), +work limits ``msolve_work`` (the work of the F4 rounds of one msolve call, 1e10), ``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 +matrices over :math:`\mathbb{F}_p` the exact search reduces, 2e9) 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`). @@ -99,8 +99,12 @@ The result inequalities that keep one point of each orbit; ``certificate`` what the count rests on, summed up in ``complete``; -``reduced``, ``rewrites``, ``relaxed``, ``start_powers``, ``experiments`` +``reduced``, ``rewrites``, ``relaxed``, ``rest_exchange``, ``start_powers``, ``experiments`` the reduction the analysis ran on, and the rewrites into rational form; +``tower`` + the stage tower, where it ran: the stages, the orders, the coordinates pinned modulo a prime + and accepted over :math:`\mathbb{Q}`, the bits of the point of the test, ``count_bound``, the + event times pinned by a jump, and whether a claim rests on a state at an event (``premise``); ``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``; @@ -117,19 +121,23 @@ The certificate 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. + a count over :math:`\mathbb{Q}` at a random integer point equals the orbit, or the stage + tower shows every coordinate to take one value on the fiber; ``count_bound`` is the + probability that a generic point has more points, ``count_bits`` and ``bezout`` the numbers + it rests on. +``"checked"`` + the count modulo a prime at a random point, taken for the count at a generic point without an + error bound; ``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. +A count that rests on a property of the model which the analysis does not show lists it under +``certificate["premises"]``, each with ``kind`` and ``text``, such as a generic state at an event. +The level is that of the count; it holds where the premises hold. + Unsupported models and open results ----------------------------------- @@ -141,13 +149,16 @@ A model that the global analysis does not handle gets the reason in - 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; +- under ``equilibrate``, resting balances with no rational closed form and no coordinates that + enter them linearly, or conditions that rest at different balances; - 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 +A result is ``open`` or ``checked`` 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. +of the coordinates, or where neither the search of the exact count nor the stage tower reaches +every coordinate. Where the fiber is too large to count, the stage tower takes one segment of a +condition at a time, at rising orders, and shows one coordinate after another to take one value on +the fiber (:ref:`stage-tower`). ``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 diff --git a/docs/guide/inputs.rst b/docs/guide/inputs.rst index 955dd82..e2d1eb1 100644 --- a/docs/guide/inputs.rst +++ b/docs/guide/inputs.rst @@ -12,12 +12,12 @@ non-identifiable direction may change the input along with the parameters; the i does not count in ``rank`` and ``dim``, the rank and the number of coordinates. An input of known form, such as dosing steps, a physical law or the spline a fit will use, -belongs in the model, with its coefficients as parameters, and the result then holds for that -form only. The two questions are related: a direction that is non-identifiable with an unknown -input is non-identifiable under every flexible enough parametrization of the input. The -converse fails, since identifiability under a parametrization may rest on taking the form as -exact. A recorded input of unmodeled form goes into ``known_inputs``, and the result then holds -for a generic recorded course. +belongs in the model, with the coefficients of that form as parameters, and the result then holds +for that form only. The two questions are related: a direction that is non-identifiable with an +unknown input is non-identifiable under every flexible enough parametrization of the input. The +converse fails, since identifiability under a parametrization may rest on taking the form as exact. +A recorded input of unmodeled form goes into ``known_inputs``, and the result then holds for a +generic recorded course. As an example we consider a readout ``x`` that follows an unmeasured stimulus ``u`` with gain ``k`` on the time scale ``tau``: @@ -75,6 +75,8 @@ The following rules apply to unknown inputs: - With switches each condition needs a separate input (:ref:`switching`). - An event or ``trafo`` entry for the input and ``engine="symbolic"`` are refused. +.. index:: lift + ``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 @@ -86,6 +88,6 @@ Known inputs ------------ A *known input* is a function of time that is recorded but has no assumed form. It is listed in -``known_inputs``; its values and time derivatives at the start are known symbols, as many as -the Lie order needs, and ``info["known_inputs"]`` reports them. The result holds for a generic -recorded course of the input. +``known_inputs``; the values and time derivatives of the input at the start are known symbols, as +many as the Lie order needs, and ``info["known_inputs"]`` reports them. The result holds for a +generic recorded course of the input. diff --git a/docs/guide/models.rst b/docs/guide/models.rst index 9b99f2a..9817422 100644 --- a/docs/guide/models.rst +++ b/docs/guide/models.rst @@ -12,6 +12,8 @@ becomes the observed product ``x2`` or is degraded. From rest, ``u`` switches on \dot x_1 = k_b + k_{in}\, u - (k_1 + k_l)\, x_1, \qquad \dot x_2 = k_1 x_1 - k_2 x_2, \qquad \dot u = 0, \qquad y = s\, x_2 . +.. index:: free initial values + The *coordinates* of a model are the quantities whose identifiability is decided: the estimated parameters, here ``kb``, ``kin``, ``k1``, ``kl``, ``k2`` and ``s``, and the initial values that neither the model nor ``trafo`` fixes, the *free initial values*. Symbols listed in @@ -52,6 +54,8 @@ Arguments The further arguments of :class:`~symident.Model` describe how the model is observed: +.. index:: condition grid + ``inputs`` input states, i.e., inputs that events set, as ``u`` above; they are zero at the start and at rest. @@ -71,8 +75,8 @@ The further arguments of :class:`~symident.Model` describe how the model is obse shared between conditions unless the grid or ``trafo`` sets them. ``trafo`` a parameter transformation, i.e., a dict of expressions by symbol; an entry named like a - state sets its initial value. A list gives one dict per condition and must have as many - entries as the grid has rows. + state sets the initial value of that state. A list gives one dict per condition and must have as + many entries as the grid has rows. ``fixed`` known symbols; they take generic values and are no coordinates. ``parameters`` diff --git a/docs/guide/reduction.rst b/docs/guide/reduction.rst index e1fa0c3..c487991 100644 --- a/docs/guide/reduction.rst +++ b/docs/guide/reduction.rst @@ -6,8 +6,8 @@ or ``res.reduce()``, describes the model in the invariants of the directions of result, i.e., the combinations of the coordinates that are constant along them, which become new parameters ``q_1, q_2, ...``. The invariants are coordinates on the quotient of the parameter space by the orbits, a *chart*. A scaling (``Symmetry.kind``, :doc:`detection`) is -removed by fixing one of its coordinates to one, a translation by its linear invariants with a -coordinate fixed to zero on a face of the positive orthant, and a curved direction by its +removed by fixing one coordinate it moves to one, a translation by the linear invariants with a +coordinate fixed to zero on a face of the positive orthant, and a curved direction by the invariants. For the result of the running example in :doc:`detection`: .. code-block:: python @@ -36,10 +36,12 @@ invariants. For the result of the running example in :doc:`detection`: {X₂} kl = 0 summary(detailed=True) explains each section. +.. index:: block, section + ``q_1`` is the outflow rate of ``x1``, and ``q_2`` and ``q_3`` are the basal and the stimulated flux into ``x2`` in units of the signal; ``k2`` stays. Each line under ``Sections`` is one *block* of jointly reduced directions. Along a direction, the coordinates -move on a curve of equal prediction, its *orbit*; a *section* picks one point per orbit, here by +move on a curve of equal prediction, the *orbit*; a *section* picks one point per orbit, here by fixing ``s = 1`` and ``kl = 0``, and the trafo is this section in the coordinates of the chart. ``red.summary(detailed=True)`` says why each section meets every orbit once. A chart is returned only where it is valid on the declared domain, by default the positive orthant. ``kl = 0`` lies on the boundary of the parameter @@ -103,10 +105,10 @@ Options runs the detection again on the reduced model (``red.checks["loop"]``). ``branch`` 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 - ``red.alternatives`` and the trafo is the section alone. + the fixed set of the symmetry, 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 ``red.alternatives`` and the trafo is the section alone. The result ---------- @@ -121,18 +123,19 @@ A :class:`~symident.Reduction` holds the transformation and what is known about hold. ``blocks`` one entry per block of jointly reduced directions, with ``status`` (``reduced``, - ``fixed``, ``invariant_only``, ``unresolved``), ``level``, the section and its - certificates: ``reach`` (every set of equal invariants is one orbit), ``injective`` (every - orbit meets the section at most once), ``coverage`` (``total`` when every orbit meets it) and - ``unproven`` (the claims not proven). + ``fixed``, ``invariant_only``, ``unresolved``), ``level``, the section and the + certificates of the section: ``reach`` (every set of equal invariants is one orbit), + ``injective`` (every orbit meets the section at most once), ``coverage`` (``total`` when every + orbit meets it) and ``unproven`` (the claims not proven). ``checks`` the check of the transformation over Q (``pins``, ``invariants``) and, with ``check=True``, the detection on the reduced model (``loop``), whose ``ok`` is None where it could not run. ``discrete`` the discrete symmetries of the detection, the fundamental domain and, under ``branches``, per - side of the fixed set its name, the ``trafo``, the coordinate it ``solved``, the new parameter, - the ``boundary``, ``injective``, ``reach`` and ``unproven``; ``branch`` is the chosen one. + side of the fixed set the name of the side, the ``trafo``, the coordinate it ``solved``, the new + parameter, the ``boundary``, ``injective``, ``reach`` and ``unproven``; ``branch`` is the chosen + one. ``alternatives``, ``limits``, ``assumptions`` the charts of the other valid choices of the fixed coordinates, what stopped part of the search, and the assumptions of the detection with the domain of the reduction. diff --git a/docs/guide/settings.rst b/docs/guide/settings.rst index a1ce2cd..fa89dc2 100644 --- a/docs/guide/settings.rst +++ b/docs/guide/settings.rst @@ -4,6 +4,8 @@ Settings and diagnostics Reconstruction settings ----------------------- +.. index:: saturation + :func:`symident.reconst_control` builds the ``control`` argument of :func:`~symident.detect`, which governs the *saturation*, i.e., the choice of the Lie order at which the rank stops growing, and the reconstruction of closed forms. The most used @@ -24,6 +26,8 @@ the others. Model, settings and seed fix the result for any number of ``cores``. Diagnostic output and switches ------------------------------ +.. index:: switches + ``detect(trace=True)`` prints the time of each stage, and ``trace="full"`` also the diagnostics of the Lie order. Further diagnostics and route choices are *switches*. A switch is set as an environment variable ``SYMIDENT_`` or, taking precedence, as a keyword of diff --git a/docs/index.rst b/docs/index.rst index 7aaafc2..0021ec1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -14,11 +14,13 @@ symident models and expressions, detection, reduction, global analysis, PEtab, inputs, switches, settings. :doc:`method` - the mathematics: local analysis, proofs, reduction, global analysis, conditions and inputs. + the mathematics: local analysis, certificates, reduction, global analysis, conditions and inputs. :doc:`api` every exported function, class and switch. :doc:`changelog` changes per version. +:ref:`genindex` + the terms and symbols of the guide and the method, each linked to the place that defines it. .. toctree:: :maxdepth: 2 @@ -30,3 +32,4 @@ symident method api changelog + genindex diff --git a/docs/method.rst b/docs/method.rst index b6410a9..8ca0456 100644 --- a/docs/method.rst +++ b/docs/method.rst @@ -3,7 +3,7 @@ Method The method chapters state the mathematics behind symident: the rank of the observability-identifiability matrix and when the order is sufficient, non-identifiable directions -in closed form and their proofs, the reduction to identifiable parameters, and the count of +in closed form and their certificates, the reduction to identifiable parameters, and the count of parameter values with the same output. Every statement that rests on random points comes with an error probability or is named in the result. @@ -11,7 +11,7 @@ error probability or is named in the result. :maxdepth: 1 method/local - method/proofs + method/certificates method/reduction method/global method/conditions @@ -20,6 +20,10 @@ error probability or is named in the result. Notation and terms ------------------ +.. index:: + single: θ (coordinates) + single: Θ (parameter space) + **Model.** symident analyzes models given by ordinary differential equations (ODEs), .. math:: @@ -27,6 +31,8 @@ Notation and terms \dot x = f(x, u, \eta), \qquad x(t_0) = x_0(\eta), +.. index:: coordinates, parametrization, parameter space + with states :math:`x \in \mathbb{R}^{n_x}`, parameters :math:`\eta`, start time :math:`t_0`, given inputs :math:`u = u(t, \eta)`, and an observation function :math:`h = (h_1, \dots, h_{n_y})` with one component per observable. The *coordinates* :math:`\theta \in \Theta \subseteq \mathbb{R}^d` are the @@ -39,11 +45,15 @@ solution, g(t; \theta) = h\big(x(t), \eta(\theta)\big), +.. index:: direction + 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. +.. index:: invariant + **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` :cite:p:`Tunali1987`. :math:`F(\varphi)` is the rate of @@ -56,6 +66,8 @@ solution that starts in :math:`S` stays in :math:`S`. and differ in fixed values, inputs or renamings. An *event* changes a state or an input instantaneously at a given time and splits a condition into *segments*. +.. index:: variety, irreducible, generic, generic rank + **Algebra.** A *variety* is the common zero set of finitely many polynomials; it is *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 @@ -67,6 +79,19 @@ denominator; to *clear* an expression is to multiply it by the denominator. The :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. +.. index:: + single: ℚ(θ) + single: algebraic closure + single: 𝔽_p + +**Fields.** :math:`\mathbb{Q}(\theta)` is the field of rational functions of the coordinates with +rational coefficients, :math:`K(c)` the smallest field that holds :math:`K` and the elements +:math:`c`, and :math:`\overline{K}` the algebraic closure of :math:`K`, which holds the roots of +every polynomial over :math:`K`. :math:`\mathbb{F}_p` is the field of integers modulo a prime +:math:`p`. + +.. index:: base point + **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 @@ -74,6 +99,8 @@ seed of each detection. A point *uniform modulo* :math:`p` has independent coord 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. +.. index:: closed form, level, route + **Closed forms.** A *closed form* of a direction gives each component :math:`\xi_i` as a rational expression of the coordinates. The *level* (``exact``, ``verified``, ``checked``, ``open``) says how far it is established (:ref:`levels`), and the *route* how it @@ -94,6 +121,8 @@ with free initial values :math:`A_0` and :math:`B_0`, so that Structural identifiability and Lie symmetries --------------------------------------------- +.. index:: locally structurally identifiable + The model is *locally structurally identifiable* at :math:`\theta` if no nearby :math:`\tilde\theta \ne \theta` has the same output. *Structural* means that the question is decided by the equations alone, for exact and continuous observables and generic @@ -108,6 +137,8 @@ symmetry*, a local one-parameter group :math:`\Phi_\lambda` of transformations o g\big(t; \Phi_\lambda(\theta)\big) = g(t; \theta) +.. index:: generator + :cite:p:`Yates2009,Merkt2015,Massonis2020`. The group is described by the *generator*, the vector field @@ -117,6 +148,8 @@ vector field X = \sum_{i=1}^d \xi_i(\theta)\, \partial_{\theta_i}, \qquad \xi(\theta) = \partial_\lambda \Phi_\lambda(\theta)\big|_{\lambda = 0}, +.. index:: orbit, identifiable + whose value :math:`\xi(\theta)` at :math:`\theta` is a direction. The integral curve of :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)` diff --git a/docs/method/proofs.rst b/docs/method/certificates.rst similarity index 79% rename from docs/method/proofs.rst rename to docs/method/certificates.rst index e32e5e6..66e30be 100644 --- a/docs/method/proofs.rst +++ b/docs/method/certificates.rst @@ -1,5 +1,5 @@ -Reconstruction and proofs -========================= +Reconstruction and certificates +=============================== 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 @@ -10,6 +10,8 @@ prove them over :math:`\mathbb{Q}`. Scalings -------- +.. index:: scaling, homogeneous, integer kernel + 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 @@ -30,6 +32,8 @@ Equation :eq:`eq-example` is exact, with weights :math:`(0, 0, -1, 1, 1)`. General directions ------------------ +.. index:: general directions + The other non-identifiable directions are *general directions*. The coordinates are ordered with the initial values of the free states first, 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 @@ -47,6 +51,8 @@ restrict it to the support of one direction, and ``homotopy fit`` fits Padé for the base point, also in parameters and resting states (the state :math:`x` of condition :math:`c` named ``x_c``). +.. index:: kernel check + Before it is reported, every closed form is checked at seeded points uniform modulo the verification prime, the *kernel check* of :ref:`kernel-check`. @@ -58,7 +64,9 @@ 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 +- .. index:: translation, curved + + 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 as orbits and linear invariants. It is proven like a scaling, from the linear structure of the model. In the positive @@ -75,6 +83,8 @@ translations and the curved directions. Invariant fields and gauge -------------------------- +.. index:: global symmetry, static subsystem, invariant fields + Some directions follow from the model equations without sampling: a *global symmetry*, a field of one regime with free initial values that lies in the kernel, and a *static subsystem*, a set of states at rest that no event moves, whose parameters give fields that leave the rest in place. @@ -99,8 +109,8 @@ field :math:`Y = \xi_\theta\, \partial_\theta + \xi_x\, \partial_x` on parameter 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:`\mathcal{D}`; :math:`\tilde 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 @@ -108,35 +118,20 @@ direction lifted onto the start :math:`z_0`. \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} + &\text{(C)} \quad \mathrm{D}E_e\, X_l = \textstyle\sum_k \tilde c_{lk}\, \tilde X_k \circ E_e + + \sum_u \tilde 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. The fields are the lift alone, with :math:`[F, Y] = 0`, or the lift together with the -lifts proven before, with coefficients solved at a random point and checked over :math:`\mathbb{Q}`. -With unknown inputs the jets take no identity, since the prolongation of the input component makes -(B) hold there. +with :math:`a` numbers and :math:`c, \tilde c` rational functions of states and parameters, which +may have poles. The fields are the lift alone, with :math:`[F, Y] = 0`, or the lift together with +the lifts proven before, with coefficients solved at a random point and checked over +:math:`\mathbb{Q}`. With unknown inputs the jets take no identity, since the prolongation of the +input component makes (B) hold there. **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`, -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 and from :math:`\varphi \circ E_e`, -:math:`\varphi \in \mathcal{A}_{k+1}`, by Lie derivatives along :math:`F`; they are analytic along -the trajectory. The claim is that the derivative of :math:`\chi(z^{(k)})` along :math:`v` vanishes -for every :math:`\chi \in \mathcal{A}_k`, :math:`z^{(k)}` the start of segment :math:`k`. For -:math:`k = 1` this is (D). If it holds for :math:`k`, the derivative of -:math:`\chi(\varphi_t(z^{(k)}))` along :math:`v` is analytic in :math:`t` with vanishing -derivatives :math:`L_F^j \chi` at :math:`t = 0`, so it vanishes on the 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, 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 :math:`\mathcal{D} = 0` at :math:`x = 0`. The proof follows the functions that the @@ -166,6 +161,8 @@ in ``info["limits"]``. Error probability of a closed form ---------------------------------- +.. index:: kernel identity + **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* @@ -188,14 +185,14 @@ orders used. It covers the closed forms of the routes checked at points uniform route, such as a static subsystem or the forward fit, is checked at particular points only and stays ``checked``. +.. index:: Bezout number + **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. The resting states are algebraic 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 and :math:`P` a -polynomial of degree :math:`D` that does not vanish on :math:`Z`. 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 to the coordinates lies in a hypersurface of at most that -degree, and therefore +resting variety: for an irreducible component :math:`Z` of the resting variety, of degree at most +the *Bezout number* :math:`\prod_i \deg f_i` of the balances :cite:p:`Heintz1983`, and a polynomial +:math:`P` of degree :math:`D` that does not vanish on :math:`Z`, .. math:: :label: eq-rest-bound @@ -219,18 +216,14 @@ taken lies on one component over :math:`\mathbb{Q}(\theta)` (``info["branches"]` with a power or exponential in the balances, a direction that the proof leaves open is ``checked``, and ``info["bound"]`` gives the reason. +.. index:: curve samples + **The bound on curves.** On a curve sample (:doc:`conditions`, *Curve samples*) the check point :math:`\theta^\ast` is still uniform modulo :math:`p`, and the resting states lie on the component through the seed. Where the Padé form of every kernel entry is the entry itself, the check is the -check at a resting point and Equation :eq:`eq-rest-bound` applies unchanged. A Padé form from -:math:`n` coefficients is unique up to total degree :math:`(n - 3)/2`, so a wrong value at -:math:`\varepsilon = 1` needs an entry of higher degree whose coefficient at -:math:`\varepsilon^{n-1}` agrees with the form. The coefficient at :math:`\varepsilon^k` of the -lifted states is a polynomial in the seed and :math:`\zeta = \theta^\ast - \hat\theta` of degree -at most :math:`1 + 2k (d - 1)`, :math:`d = \max_i \deg f_i`, since each Newton step multiplies -by :math:`\operatorname{adj}(J_x)` over :math:`\det J_x` at the seed. For kernel entries of degree -:math:`\delta` in the states and coordinates, the agreement is a nonzero polynomial of degree at -most :math:`\delta (1 + 2 (n - 1)(d - 1))` in the drawn values, and +check at a resting point and Equation :eq:`eq-rest-bound` applies unchanged. Otherwise, for Padé +forms from :math:`n` coefficients, kernel entries of degree :math:`\delta` in the states and +coordinates and :math:`d = \max_i \deg f_i`, .. math:: :label: eq-curve-bound diff --git a/docs/method/conditions.rst b/docs/method/conditions.rst index b47c06d..f6e1a21 100644 --- a/docs/method/conditions.rst +++ b/docs/method/conditions.rst @@ -3,8 +3,8 @@ 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`. +certificates of :doc:`certificates`, and how a PEtab problem maps onto them; the global analysis +takes them up in :ref:`fiber-features`. .. _conditions-events: @@ -14,6 +14,8 @@ 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)}`. +.. index:: gap + 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}` @@ -49,6 +51,8 @@ or when the lift of the closed form, or at rest the output identities, are prove Resting states -------------- +.. index:: resting state, balances, resting variety + 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* @@ -64,24 +68,31 @@ at zero at rest, and :math:`f_N` their balances, the tangency rows are 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 . +.. index:: resting jacobian + Dropping the balance of each pivot 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 square :math:`J_x` is the *resting Jacobian*. A proven rank also needs the resting Jacobian of every condition invertible at the base point; otherwise the rank is a lower bound. +.. index:: branch, forward seed, conjugate + **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*), which -names the component that the drawn values parametrize. Where a balance has several roots, the one -taken is named in ``info["branches"]``, by the factor over :math:`\mathbb{Q}(\theta)` it solves, or -as *conjugate* where the balances have an irreducible eliminant; conjugate roots have equal rank, -and an eliminant irreducible at a point is irreducible over :math:`\mathbb{Q}(\theta)`. A -state rests at zero when the right-hand side, with the inputs at zero, is linear in it with a -coefficient nonzero at rest; a second branch with the state away from zero is named there and taken -by ``free_initial``. The same holds for a set of states whose right-hand sides all vanish where the -set is zero, an invariant face, when the Jacobian on the set is invertible at generic values; states -of a conserved total make it singular and stay off the face. +names the component that the drawn values parametrize. A rate that divides the balance is never +solved for: at every draw it would be zero, a component outside the model. Where a balance has +several roots, the one taken is named in ``info["branches"]``, by the factor over +:math:`\mathbb{Q}(\theta)` it solves, or as *conjugate* where the balances have an irreducible +eliminant; conjugate roots have equal rank, and an eliminant irreducible at a point is irreducible +over :math:`\mathbb{Q}(\theta)`. A state rests at zero when the right-hand side, with the inputs at +zero, is linear in it with a coefficient nonzero at rest; a second branch with the state away from +zero is named there and taken by ``free_initial``. The same holds for a set of states whose +right-hand sides all vanish where the set is zero, an invariant face, when the Jacobian on the set +is invertible at generic values; states of a conserved total make it singular and stay off the face. + +.. index:: total, pivot **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, and the basis @@ -110,6 +121,8 @@ z` exists, and lifts each condition along :math:`\theta(\varepsilon) = \hat\thet x_{c,k} = -J_c(\hat z)^{-1}\, [\varepsilon^k]\, f_c\big(x_{c, 0`. The *declared signs* are the domain declared by ``positive`` and the start sides declared by ``regimes``. Conditions that @@ -235,7 +258,7 @@ rank along the trajectories from the declared start; without switches it cannot .. math:: - \big(L_{F_\sigma}^k h_{\sigma,i} - L_{F_{\sigma'}}^k h_{\sigma',i}\big)\big|_{\Gamma_j} + \big(L_{F_\sigma}^k h_{\sigma,i} - L_{F_{\tilde\sigma}}^k h_{\tilde\sigma,i}\big)\big|_{\Gamma_j} \ne 0 , proven by a nonzero Taylor coefficient at a point of :math:`\Gamma_j` modulo a prime; *hidden* @@ -262,8 +285,8 @@ and, at a surface that is not visible and that some :math:`Y_i` moves, for every .. math:: - \big(F_\sigma - F_{\sigma'}\big)\big|_{\Gamma_j} \in \mathcal{D}, \qquad - \big(h_\sigma - h_{\sigma'}\big)\big|_{\Gamma_j} = 0 . + \big(F_\sigma - F_{\tilde\sigma}\big)\big|_{\Gamma_j} \in \mathcal{D}, \qquad + \big(h_\sigma - h_{\tilde\sigma}\big)\big|_{\Gamma_j} = 0 . No :math:`Y_i` moves a fixed symbol, an input or time. 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 @@ -271,11 +294,13 @@ tangent, so the crossing time stays; at a hidden one the crossing may move, but :math:`\mathcal{D}` and the observables agree. The rule therefore never reports a direction that changes the observables, for any sequence of the allowed regimes. +.. index:: fresh coordinates + **Lower bound.** The directions of the rule satisfy the rows of copies of the model: each regime from the start of each condition, from generic points of the surfaces, and switched at fixed times -into the other regimes, with outputs along *words* :math:`L_{F_\sigma}^a L_{F_{\sigma'}}^b -h_{\sigma'}`. A kernel dimension :math:`k_\Delta` of these rows, projected onto :math:`\theta` off -the *fresh coordinates*, the entry states at surface points, gives the lower bound :math:`d - +into the other regimes, with outputs along *words* :math:`L_{F_\sigma}^a L_{F_{\tilde\sigma}}^b +h_{\tilde\sigma}`. A kernel dimension :math:`k_\Delta` of these rows, projected onto :math:`\theta` +off the *fresh coordinates*, the entry states at surface points, gives the lower bound :math:`d - k_\Delta`. The projection is proven where the fresh columns have full column rank at the sample point, ``verified`` with the chance by :cite:p:`Schwartz1980` that a maximal minor vanishes at a point uniform modulo the verification prime, else a lower bound (``info["projection"]``, @@ -300,13 +325,13 @@ direction :math:`G_\sigma = \partial_w F_\sigma` joins the bracket condition, and :math:`v = \sum_i \beta_i Y_i` changes the input in :math:`\sigma` by :math:`-\sum_i \beta_i a_{i\sigma}`. Where :math:`G_\sigma \notin \mathcal{D}`, the change must not jump where a trajectory -crosses :math:`\Gamma_j` into a neighbor :math:`\sigma'`: on :math:`\Gamma_j`, +crosses :math:`\Gamma_j` into a neighbor :math:`\tilde\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 , + a_{i\tilde\sigma} - a_{i\sigma} + - \frac{Y_i(\gamma_j)}{F_\sigma(\gamma_j)} \sum_k e_k\, a_{k\tilde\sigma} = 0 , + \qquad F_\sigma - F_{\tilde\sigma} = \sum_k e_k Y_k , the last term counting only at a hidden surface that :math:`Y_i` moves. The jets of each copy are nuisance coordinates (:ref:`inputs`). The rule holds per condition, so each condition needs a @@ -337,6 +362,8 @@ the other parameters take their nominal values. A preequilibration is the restin at zero and the condition of the experiment as events at the start; it has to be part of every experiment or of none. +.. index:: readout at rest + An experiment without preequilibration whose measurements are all at :math:`t = \infty` is a *readout at rest*: the output is :math:`h(x^\ast(\theta), \eta(\theta))` at the resting state of the condition, under the premise that the trajectory converges to that resting state. Only the rows of diff --git a/docs/method/global.rst b/docs/method/global.rst index 3c4f18d..6f73f79 100644 --- a/docs/method/global.rst +++ b/docs/method/global.rst @@ -1,6 +1,8 @@ Global analysis =============== +.. index:: discrete symmetry + 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 @@ -14,14 +16,41 @@ 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. +(:ref:`verified-count`, :ref:`several-experiments`), or not (:ref:`certificates`). Where the fiber +is too large to count, the stage tower (:ref:`stage-tower`) shows one coordinate after another to +take one value on the fiber. Points proposed numerically and certified by interval arithmetic +(:ref:`monodromy`) propose maps only. + +.. list-table:: + :header-rows: 1 + :widths: 24 46 16 + + * - route + - applies where + - level + * - :ref:`exact-count` + - the field fixed by the exact maps is shown inside the field of the output coefficients + - ``exact`` + * - :ref:`verified-count` + - msolve counts the fiber over :math:`\mathbb{Q}`; no events or switches, rational starts + - ``verified`` + * - :ref:`several-experiments` + - one condition with free starts and no rational first integral + - ``verified`` + * - :ref:`stage-tower` + - the fiber is too large to count; units are segments without switches + - ``verified``, with a premise after an event + * - count modulo a prime + - the routes above end at a work limit + - ``checked`` .. _fiber: The fiber --------- +.. index:: 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. It is the solution set of the polynomial system that equates the Taylor coefficients of the @@ -32,8 +61,9 @@ and :math:`E(x)\, g = M(x)`. msolve :cite:p:`Berthomieu2021` counts the points o closure of :math:`\mathbb{F}_p`; the count is the number of distinct values of a random linear form in the coordinates, so points that differ only in the derivatives of the states, or that are multiple, count once. It bounds the size of the fiber of the model, and more equations can only -lower it. The orders rise until the count is the same at two successive steps or equals the orbit -of the proven maps, which no higher order changes. +lower it. The calls of msolve of one count share a work limit on their F4 rounds. The orders rise +until the count is the same at two successive steps or equals the orbit of the proven maps, which +no higher order changes. The system splits into blocks without a shared variable, whose counts multiply. A block may be counted in *stages*: with :math:`P_A` the equations that read only the variables :math:`A`, the count @@ -49,7 +79,23 @@ The conditions are stacked as in the local analysis: each has separate derivativ coordinates are shared. After an event the gaps are :math:`\varepsilon\, \Delta t_i^0` as in :ref:`conditions-events`, and every coefficient after the event is a power series in :math:`\varepsilon`, kept up to the gap order. Under ``equilibrate`` the start of a condition is -the rational solution of the balances over :math:`\mathbb{Q}(\theta)`, and none without one. With +the rational solution of the balances over :math:`\mathbb{Q}(\theta)`; balances of degree one in +the resting states are solved by elimination over that field. Where the balances have no such +solution, the resting values :math:`R` become coordinates and as many coordinates :math:`p` that +enter the balances linearly, with a coefficient matrix invertible at a random point, are solved +from them, the same for every condition (``info["discrete"]["rest_exchange"]``). The map +:math:`\theta \mapsto (\theta \setminus p, R)` is injective, so a count of one in this chart is +one for the model; another count and the maps stay in the chart, and the result is ``open``. +A start that holds the square root :math:`w = \sqrt{P(\theta)}` of one polynomial of the +coordinates is handled in the same way: the start :math:`R` of one state that depends on +:math:`w` becomes a coordinate, and a coordinate :math:`p` of degree one in the factor of +:math:`(a - R c)^2 - P\, (R d - b)^2` that the start satisfies, with :math:`R = (a + b w)/(c + d w)` +and :math:`a, b, c, d` polynomials of the coordinates, is solved from it; the other starts are +rational in the chart. A switch on the clock alone, :math:`A` before the time :math:`\tau` and +:math:`B` from it on, with +:math:`\tau` a number or a coordinate declared positive, is :math:`A + (B - A)\, s` with a state +:math:`s`, :math:`\dot s = 0`, :math:`s(0) = 0`, that an event at :math:`\tau` sets to one; the +model is then one with events. With switches (:ref:`switching`), each allowed regime enters as a copy whose start is free on a switching surface :math:`\gamma_j = 0`, an equation of the fiber. A map is ``exact`` with a map of the states in every regime that takes each surface to itself, :math:`\gamma_j(\varphi(x), @@ -75,13 +121,18 @@ are reported in the original coordinates. ``info["discrete"]["rewrites"]`` lists exponential, a logarithm or a power :math:`b^\mu` with 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: +start, one row per kind of term: .. 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 . + \begin{array}{lllll} + \text{term} & W & \nu & \dot\nu & \nu(0) \\[2pt] + e^{\psi} & e^{\psi_0} & e^{\psi - \psi_0} & \nu\, \dot\psi & 1 \\[2pt] + b^{\mu} & b_0^{\mu} & (b / b_0)^{\mu} & \mu\, \nu\, \dot b / b & 1 \\[2pt] + \log \psi & \log \psi_0 & \log(\psi / \psi_0) & \dot\psi / \psi & 0 + \end{array} + +.. index:: relaxed model A term of the coordinates alone becomes a new coordinate :math:`P`, and a coordinate that no equation reads afterwards is dropped where one :math:`P` determines it on the positive reals. The @@ -100,21 +151,30 @@ Then at a generic point the fiber of the model has at most :math:`k` connected c 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 (c) a generic :math:`\theta` lies on a generic orbit of the relaxed model, and a point -:math:`\theta'` of the fiber gives the point :math:`(\theta', \omega(\theta'))` of the relaxed -fiber. On a relaxed orbit :math:`O`, the :math:`W` that no scaling moves and, by (b), what their -starts read are constant; by (a) a unique group element :math:`s(q)`, continuous in :math:`q`, -brings :math:`q \in O` to the starts of the moved :math:`W`. So :math:`O \cap \Gamma` is empty or -the connected image of :math:`O` under :math:`q \mapsto s(q)\, q`. 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` +The conclusion holds as well with (a) and (b) replaced by (d): the exact directions that move a +:math:`W` or a coordinate read by a start commute, and each changes every +:math:`c_W = \log W - \log \omega_W(\theta)` (:math:`W - \omega_W(\theta)` for a logarithm) at a +rate that these directions do not move. Then :math:`c` is affine in the parameters of the directions +on every orbit, and an orbit meets :math:`\Gamma` in an affine image, connected; a single point +where the rates have full rank. + +For the points in :math:`\Theta`, (a) and (b) can also be replaced by (e): these directions are +scalings and shifts that commute, and for :math:`r` of the :math:`c_W`, :math:`r` the number of +directions, with signs, the matrix of the rates :math:`X_i(c_W)` has principal minors of one sign +wherever the coordinates they read are positive, shown by the signs of the coefficients. Then +:math:`t \mapsto c(g_t q)` is injective on the parameters that keep the orbit in :math:`\Theta` +:cite:p:`GaleNikaido1965`, and an orbit meets :math:`\Gamma` in :math:`\Theta` in one point at most; +the count of the relaxed model bounds the points of the fiber in :math:`\Theta`. For exponentials alone, (c) holds where the Jacobian of the exponents :math:`\psi_0` in the coordinates has full rank, by the lemma of Kolchin and Ostrowski in :ref:`non-rational`, and for -logarithms alone likewise with :math:`\mathrm{d} \log \psi_0`. 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, and the certificate -is ``open``. +logarithms alone likewise with :math:`\mathrm{d} \log \psi_0`. (c) also holds where every new state +has a coordinate that no other new state reads, in the exponent :math:`\psi_0`, in the argument of +the logarithm, or in the exponent :math:`\mu` of :math:`b_0^{\mu}` and not in :math:`b_0`, with a +start that depends on it. Otherwise (c) is a premise in ``certificate["premises"]`` (kind +``"independent_starts"``), and the count holds at the stated level where the premise holds. Where +none of (a) and (b), (d) or (e) holds, ``certificate["relaxed_why"]`` names the direction, the count +is not reported, and the certificate is ``open``. **Free powers of a state at 0.** A power :math:`x^{c_0 + c\alpha}` of a state that starts at 0, with a positive coordinate :math:`\alpha`, has no start to relax. With :math:`k` and :math:`c_x` as @@ -123,20 +183,17 @@ c_x)^\alpha` a series in :math:`t` and :math:`t^{k\alpha}` with coefficients pol :math:`\alpha`. :math:`Z` cancels, is absorbed by a scaling of the new coordinates, or becomes a new coordinate under the proposition above. -**Lemma.** Let :math:`c_x` have one sign on the domain, and let :math:`d`, the coefficient of the -term :math:`t^{v_h + k\alpha}`, :math:`v_h` an integer, of least exponent among the terms of an observable :math:`h` that read -:math:`N`, 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`. +Where :math:`c_x` and the coefficient of least exponent of the terms of an observable that read +:math:`N` have one sign on the domain, every point of the domain with the output of a generic +point has the same :math:`\alpha`. -*Proof.* The expansions converge, and :math:`e = v_h + k\alpha \notin \mathbb{Q}` for generic -:math:`\alpha`. If :math:`e' = v_h + k\alpha' \ne e`, the smaller exponent, or :math:`e` where -:math:`k\alpha'` is an integer, has a nonzero coefficient on one side only, which the independence -of the powers of :math:`t` (:ref:`singular-starts`) excludes. :math:`\square` - -Where one sign is not shown, the condition is a premise and the count is ``axiom``. The fiber then -has the equation :math:`\alpha' = \alpha`, and the exact count is not taken +Where one sign is not shown, the condition is a premise (kind ``"start_power"``). The fiber then +holds the equation :math:`\bar\alpha = \alpha` for the value :math:`\bar\alpha` of :math:`\alpha` at +the points of the fiber, and the exact count is not taken (``info["discrete"]["start_powers"]``). +.. index:: resting chart + **Resting states inside a term.** Under ``equilibrate`` a resting value inside a transcendental term solves a transcendental balance. Such resting values :math:`R_H` become coordinates of a *resting chart*, with the terms at rest as leaves :math:`W` and the other resting states and one @@ -152,6 +209,8 @@ so the fiber in the chart is the fiber of the model; it is relaxed as above, and the rank of the exponents. The counts in the domain do not hold the declared sign of :math:`p` (``info["limits"]``). +.. index:: relative degree + **Unknown inputs.** An unknown input enters the fiber through the jets at the start, unknowns that are no coordinates (:ref:`inputs`); 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 @@ -163,7 +222,8 @@ jet of :math:`w`, has \qquad \partial_w L^r h \ne 0, so the Taylor coefficient of order :math:`n` reads exactly the jets up to :math:`n - r`, and higher -jets are set to zero without changing the coordinates of the fiber. A map :math:`\sigma` is ``exact`` where a map :math:`\psi(x, \theta, w)` of the input +jets are set to zero without changing the coordinates of the fiber. A map :math:`\sigma` is +``exact`` where a map :math:`\psi(x, \theta, w)` of the input values, with :math:`\varphi` reading no input, satisfies .. math:: @@ -208,8 +268,11 @@ The ``exact`` maps generate a group :math:`G`; at a generic point the orbit is : of the fiber. When :math:`|G|` equals the count, the count is final (``count_final``). ``complete`` is ``"exact"`` where the fiber is proven to be the orbit (:ref:`exact-count`), ``"verified"`` where a count over :math:`\mathbb{Q}` equals the orbit with the probability -``count_bound`` of more points, else ``"axiom"``: that the count modulo the prime at a random point -is the count over :math:`\mathbb{C}` at a generic point (``count_bound_why``). +``count_bound`` of more points, else ``"checked"``: the count modulo the prime at a random point, +which stands for the count over :math:`\mathbb{C}` at a generic point without an error bound +(``count_bound_why``). + +.. index:: fundamental domain 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 @@ -226,6 +289,11 @@ between the hypersurfaces on which two points meet or a point crosses the bounda The exact count --------------- +.. index:: + single: F (field of the output coefficients) + single: T (fiber at a generic point) + single: G (group of the exact maps) + Let :math:`L = \mathbb{Q}(\theta)`, :math:`G` the group of the ``exact`` 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 each condition, with the known inputs at the values drawn for them. Let :math:`T` be @@ -236,12 +304,6 @@ the fiber at a generic point :math:`\theta` for these inputs, the values :math:` \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 coefficients of the output generate a field :math:`\mathbb{Q}(\Psi) \supseteq F`. A -point :math:`\sigma \in T` has algebraically independent coordinates, so :math:`\theta \mapsto -\sigma` defines an embedding of :math:`L` over :math:`\mathbb{Q}(\Psi)`, and every such embedding -gives a point of :math:`T`; so :math:`|T| = [L : \mathbb{Q}(\Psi)]`. The orbit lies in :math:`T`, -and :math:`|T| \le [L : F] = [F(\alpha) : F] \le |G|`. :math:`\square` - The test has no random step: random points only propose candidates, each checked exactly. Membership in :math:`F` is proven as a tower: :math:`f = A(w)/B(w)` lies in :math:`F` when :math:`w` are output coefficients or functions already shown in :math:`F`, by the identity @@ -249,7 +311,9 @@ Membership in :math:`F` is proven as a tower: :math:`f = A(w)/B(w)` lies in :mat :math:`B(w(\theta)) \ne 0`, checked as polynomials in :math:`\theta`. The functions shown in :math:`F` are: -- *Coefficients of input-output relations.* A vector :math:`\lambda(\theta)` with :math:`\sum_j +- .. index:: projection + + *Coefficients of input-output relations.* A vector :math:`\lambda(\theta)` with :math:`\sum_j \lambda_j \phi_j(g, u) = 0` along every trajectory, :math:`\phi_j` monomials in the derivatives of the observables and the known inputs, lies in the kernel of the matrix :math:`M(c)` of the Taylor coefficients of the :math:`\phi_j`. The relation is checked exactly as a polynomial @@ -265,12 +329,19 @@ Membership in :math:`F` is proven as a tower: :math:`f = A(w)/B(w)` lies in :mat :cite:p:`BenOr1988`. Every proposing step can only make the search fail; the identity check decides, and the coefficients lie in :math:`F` as in the item before. - *Coefficients of relations by elimination.* The states are eliminated as in - :cite:p:`Hong2020`, one at a time by resultants over :math:`\mathbb{Z}[\theta]`. Every polynomial - of this process vanishes along every trajectory, and of the irreducible factors one does, since - the power series along a trajectory form a domain and the closed sets where a given factor - vanishes cover the parameter space; the product of the factors that vanish at three random - trajectory points therefore vanishes along every trajectory, without a random step. A remaining + :cite:p:`Hong2020`, one at a time by resultants over :math:`\mathbb{Z}[\theta]`. Of the + irreducible factors of each polynomial of this process, the product of those that vanish at three + random trajectory points vanishes along every trajectory, without a random step. A remaining equation of degree one in a removed state gives the start of that state in :math:`F`. + + .. index:: output saturation + + *Output saturation.* Let :math:`u` be a known input with a generic recorded course, and let + every start of a state be a separate coordinate that no right-hand side and no observable + reads. Where a derivative :math:`g_i^{(j)}` is a polynomial in the derivatives of :math:`u`, the + coefficients :math:`b_m(x, \theta)` of the polynomial lie in the field of the outputs and the + inputs. Those that raise the rank of the Jacobian in the states join the observables of the + elimination. - the coordinates that :math:`G` fixes, the coefficients of :math:`P_\alpha` and traces over :math:`G`, each shown as a rational function of the functions before. @@ -278,7 +349,7 @@ Membership in :math:`F` is proven as a tower: :math:`f = A(w)/B(w)` lies in :mat :math:`L = F(\alpha)` is shown coordinate by coordinate, each as a rational function of functions in :math:`F`, of :math:`\alpha` and of the coordinates shown before, the start of a state also by a relation of degree one in that start along every trajectory. The search ends at the work limits -``search_entries``, ``msolve_entries`` and ``elimination_terms``; past a limit the certificate names +``search_entries``, ``msolve_work`` and ``elimination_terms``; past a limit the certificate names what was not reached. Constants of the model that are no coordinates are known symbols :math:`\kappa`: :math:`\mathbb{Q}` is replaced by :math:`\mathbb{Q}(\kappa)`, and the theorem holds for generic values of the constants. ``info["discrete"]["certificate"]["exact"]`` lists the @@ -294,34 +365,11 @@ over :math:`\mathbb{Q}` with :math:`|G| \le k < 2|G|` gives :math:`|T| = |G|`, w the bound. **Coefficients of a large projection, verified.** Where the elimination gives no relation, a few -coefficients of a projection join the :math:`f_i` with an error bound. Let :math:`S` be the support -of :math:`r` monomials :math:`\phi_j`. (a) The Taylor coefficients of the :math:`\phi_j` have rank -:math:`r - 1` at a random point modulo a prime, so at most one relation on :math:`S` holds, with -coefficients in :math:`F`. - -(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. Without a relation, the determinant of :math:`r` rows of the cleared values -:math:`P_j` is a nonzero polynomial of degree at most :math:`D = \sum_j \deg P_j` with content at -most :math:`H`, :math:`\log_2 H \le \log_2 r! + \sum_j \log_2 \|P_j\|_1`. With :math:`N` the number -of primes in the range, bounded by :math:`x / \ln x < \pi(x) < 1.25506\, x / \ln x` -:cite:p:`Rosser1962`, and :math:`a \ge 1 - (r + 6) \deg \prod_k F_k / (q - 1)` the probability that -no denominator vanishes, a trial shows a kernel with probability at most - -.. math:: - - \varepsilon = \frac{D}{(2^{29} - 1)\, a} + \frac{\lceil \log_2 H / 29 \rceil}{N} - -by :cite:p:`Schwartz1980`, and :math:`k = 5` independent trials with probability at most -:math:`\varepsilon^k`. - -(c) A coefficient :math:`w` interpolated as a Laurent polynomial over a monomial coefficient -:math:`c_{j_0}` passes every trial; a wrong one would make a nonzero cofactor polynomial vanish, so -:math:`k` trials pass with probability at most :math:`\varepsilon_w^k`, :math:`\varepsilon_w` as -:math:`\varepsilon` with the degree and height of :math:`w` added. - -The bound of the count is that over :math:`\mathbb{Q}` (``count_bound_q``) plus -:math:`\varepsilon^k` and :math:`\varepsilon_w^k` per function counted (``relation_bound``). +coefficients of a projection join the :math:`f_i` with an error bound. The rank of the Taylor +coefficients of the monomials of the support at a random point leaves at most one relation, five +trials modulo random primes verify that it exists, and each interpolated coefficient passes every +trial. The bound of the count is that over :math:`\mathbb{Q}` +(``count_bound_q``) plus the probabilities of the trials per function counted (``relation_bound``). .. _verified-count: @@ -341,51 +389,100 @@ with :math:`N_u` the number of unknowns and :math:`D` the Bezout number below; : chosen so that the bound is at most :math:`10^{-6}` (``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, at orders no lower than those of the -rank criterion; otherwise the count stays under the axiom of :ref:`certificates`, and +rank criterion; otherwise the count is ``checked`` (:ref:`certificates`), and ``count_bound_why`` names the reason. msolve is taken to be correct. *The system.* The unknowns :math:`u` are the coordinates, the derivatives of the states at the start and the variable :math:`w` of the saturation :math:`w\, s(u) = 1`, :math:`s` the product of -the coordinates and the denominators at the start. Cleared over one denominator, the equations +the coordinates and the denominators at the start. In a condition without events, a product of +three or more states enters through product jets: the Taylor coefficients of the product of two +of the factors, of that product and the next factor, and so on, each an unknown with one equation +per order. Cleared over one denominator, the equations :math:`F_1, \dots, F_s \in \mathbb{Q}[\theta, u]` define :math:`V` of degree at most :math:`D = \prod_i \deg F_i` by the Bezout inequality :cite:p:`Heintz1983`. -*Step 1: the points of T are isolated.* For :math:`\sigma \in T` the Jacobian of :math:`F` in -:math:`u` has full column rank at the point of :math:`\sigma`: the equations of the derivatives are -triangular with nonzero diagonal, and the output equations have the Jacobian :math:`-E_0 \cdot -\partial_x \Psi_N` up to a triangular factor, of rank :math:`n` at every point with algebraically -independent coordinates by the rank criterion. So the point lies on the union :math:`V_0` of the -components of :math:`V` that dominate the coordinates, at most :math:`D` points over -:math:`\theta`. - -*Step 2: polynomials of bounded degree.* The image of :math:`V_0` under :math:`(\theta, u) \mapsto -(\theta, u_j)` is a hypersurface :math:`V(E_j)` of degree at most :math:`D`, and so is that under a -separating linear form :math:`\lambda(x)`, square-free over :math:`\mathbb{Q}(\theta)`, with -discriminant :math:`R_\lambda \in \mathbb{Q}[\theta]` nonzero of degree at most :math:`(2D - 1) D`. - -*Step 3: specialization.* Let :math:`\Delta = a_\lambda R_\lambda \prod_j a_j` with the leading -coefficients :math:`a`, 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`. -Otherwise, by Chevalley's extension theorem, every point of :math:`V_0` specializes to a solution at -:math:`\theta^\ast` away from the saturation, and the values of :math:`\lambda` stay distinct, so -the system solved has at least :math:`|T|` points with distinct :math:`x`, and the count of msolve -is at least :math:`|T|`. A count by stages adds exact counts over rational points and gives the +A block counted in stages (:ref:`fiber`) adds exact counts over rational points and gives the same bound. -*A smaller variety.* The same steps hold for the variety in :math:`(\theta, x, w)` cut out by +*A smaller variety.* The bound holds as well for the variety in :math:`(\theta, x, w)` cut out by :math:`n` output equations whose gradients in :math:`x` are independent at a random point and by -the saturation, with :math:`D' = (1 + \deg s') \prod_i \deg(\mathrm{num}_i\, \mathrm{den}_i)` and -:math:`n + 1` unknowns; the smaller of the two bounds is used. +the saturation, with :math:`\tilde D = (1 + \deg \tilde s) \prod_i \deg(\mathrm{num}_i\, +\mathrm{den}_i)` and :math:`n + 1` unknowns; the smaller of the two bounds is used. *Pins.* A function :math:`f = a/b` proven to lie in :math:`F` takes the same value at every point of :math:`T`, so the equation :math:`a(x)\, b(\theta) - b(x)\, a(\theta)` removes points outside -:math:`T` only, and Steps 1 to 3 hold with it. +:math:`T` only, and the bound holds with it. *Unknown inputs.* The jets :math:`v` that the output coefficients read are drawn with -:math:`\theta^\ast`, and :math:`\theta` is replaced by :math:`(\theta, \hat v)`. Step 1 needs the +:math:`\theta^\ast`, and :math:`\theta` is replaced by :math:`(\theta, \hat v)`. The bound needs the Jacobian of the output coefficients in :math:`(x, v)` of full column rank, checked at a random point. Equation :eq:`eq-count-bound` keeps the same form; the smaller variety is not used. +.. _stage-tower: + +The stage tower +--------------- + +.. index:: stage tower, pin, claim + +Where no candidate map exists and neither the exact count nor a count at low orders gives the orbit, +the coordinates are shown one at a time to take one value on the fiber. A coordinate +:math:`\theta_i` is *pinned* when it lies in the field :math:`F` of the output coefficients. + +*Stages.* The units are the segments of the conditions. At a random point modulo :math:`p` and an +order :math:`N` rising from 1, the system of one unit is taken with the coordinates pinned so far as +numbers. The kernel of the Jacobian of this system at the point names the unknowns it determines, +and the other directions of the kernel are cut at random rational values :math:`\rho` of +coordinates. msolve solves the part of the block triangular form that holds the determined unknowns; +a coordinate with one value on all points, the value of the point, is *claimed*, with the original +equations the claim rests on. The order rises where no unit gives a claim. + +*Theorem (pin by descent).* Let :math:`S` be the solutions of the system of a claim at a generic +:math:`\theta`, away from the saturation, over the algebraic closure. If :math:`S` is finite and not +empty and :math:`x_i` has one value :math:`w` on :math:`S`, then :math:`w \in F`; with :math:`w = +\theta_i`, :math:`\theta_i` is pinned. + +*Theorem (verified pin).* The list of claims is fixed before an integer point :math:`\theta^\ast`, +uniform in :math:`\{1, \dots, 2^b\}^n`, is drawn. A claim is accepted where the system of the +equations of the claim at :math:`\theta^\ast`, with the pins of the claims before it, has no pole, +finitely many points, at least one, and :math:`x_i = \theta^\ast_i` on all of them. A false claim is +accepted with probability at most + +.. math:: + :label: eq-stage-bound + + \varepsilon = \frac{\max\big(D_1,\ (m + \deg \tilde s + 2 \delta_x)\, \delta\big)}{2^b}, + +with :math:`m` the open unknowns of the system, the jets it reads without the equation of the jet +among them, :math:`\delta` and :math:`\delta_x` the products of the :math:`m` largest degrees of the +rows, in all variables and in the unknowns alone, from the recursion of the degrees with these jets +as unknowns of degree one, :math:`\tilde s` the saturation, and :math:`D_1` the Bezout number of the +system with the saturation. A start :math:`N/D` with :math:`D` not constant has :math:`D` in the +saturation :math:`s`; with :math:`q` the largest degree of the numerators of the starts and +:math:`L` the product of their distinct denominators, :math:`\deg \tilde s \le \deg s\, +(\max(1, q) + \deg L)`. + +The probability that an accepted list holds a false claim is at most the sum of the +:math:`\varepsilon`, and :math:`b` makes the sum at most :math:`10^{-6}` (``count_bits``, +``count_bound``). With every coordinate accepted, the fiber at a generic point is the point, at +level ``verified``; ``info["discrete"]["tower"]`` reports the stages. + +*Events.* The Taylor coefficients at the start of a condition are invariants of the output whatever +follows; those after an event are where the event time is a number or pinned. An event time +:math:`\tau`, a coordinate read nowhere else in the condition, is pinned without a random step where +an output coefficient at the start differs between the states and right-hand sides before and after +the event: every point of the fiber then has the same :math:`\tau` (``tower["jumps"]``). A start +after an event is known where the state stays at a known value on the segment before (the right-hand +sides of a set of such states vanish at these values whatever the other states do) or the event sets +it from known values. The other starts are new coordinates of the unit, drawn with +:math:`\theta^\ast`; a claim that rests on them holds at a generic start, and the result holds under +the premise (kind ``"generic_event_state"``) that the states at the event are such a start for the +stages that read them. + +A unit with switches, a free power of a state at 0 or unknown inputs is left out. The stages end at +the work caps ``tower_stages``, the number of stages, and ``tower_work``, the work of F4 of all +calls of msolve of the stages together; ``limits`` names the cap reached. + .. _several-experiments: Several experiments @@ -395,62 +492,32 @@ The fiber of one experiment needs Taylor coefficients up to an order near the nu coordinates over the number of observables, and the degrees grow with the order. :math:`K` experiments that share :math:`\theta` and have starts :math:`x_0^1, \dots, x_0^K` of their own need lower orders :cite:p:`OvchinnikovPogudinThompson2023,Ovchinnikov2022`. Let :math:`T_K` be the -fiber of the :math:`K` experiments 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 +fiber of the :math:`K` experiments and :math:`\pi` the projection onto :math:`(\bar\theta, +\bar x_0^1)`; always :math:`\pi(T_K) \subseteq T(\theta, x_0^1)`. The route takes a model with one condition, no events, switches or clock in the equations, and every start a free coordinate. *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.* The coefficients :math:`e` of :math:`\prod_{\theta'} (Z - \lambda(\theta'))` over the -:math:`\theta'` of :math:`T(\theta, x_0)` are rational in :math:`\theta`, :math:`x_0` and the input -jets :math:`\kappa_0, \dots, \kappa_M`. Starting the experiment later along the trajectory shifts -the output for :math:`\theta` and every :math:`\theta'`, so :math:`X e = 0` for :math:`X = f \cdot -\partial_x + \sum_j \kappa_{j+1} \partial_{\kappa_j}`. Only :math:`\kappa_{M+1} -\partial_{\kappa_M} e` reads :math:`\kappa_{M+1}`, so :math:`e` reads no jet, and :math:`f \cdot -\partial_x e = 0` makes :math:`e` a first integral, hence :math:`e \in \mathbb{Q}(\theta)`. The set -of :math:`\theta'` therefore does not depend on the start, and each :math:`(\theta', x_0'^1)` extends -to a point of :math:`T_K`. :math:`\square` - The premise is needed: the twisted oscillator of :cite:p:`OvchinnikovPogudinThompson2023` (Example 2.7) has a first integral and a second point for one experiment only. Under linear conservation laws :math:`C(\theta) f = 0` the premise is taken on the level sets, and the experiments start on the level set of the first. -*The premise at one point.* A system 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 the integer relations :math:`\sum_i k_i \lambda_i = 0` among the eigenvalues of -:math:`DF(x^\ast)` :cite:p:`CongLlibreZhang2011`. The parameters with a rational first integral of -degree at most :math:`d` form a closed set :math:`S_d` defined over :math:`\mathbb{Q}`, by a -condition linear on a Grassmannian, which is projective. A point outside every :math:`S_d` puts a -generic point outside every :math:`S_d`: the premise holds. - -*The test.* symident draws an equilibrium over a number field :math:`F` and takes :math:`J = -Df(x^\ast)` in diagonal blocks. With :math:`\chi_j` the characteristic polynomial of block -:math:`j` without the eigenvalue 0 of the laws, the eigenvalues on the level set 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 of the blocks of degree at least 2 are pairwise distinct, and - -(c) the traces :math:`t_j` of the blocks are linearly independent over :math:`\mathbb{Q}`. - -*Proof.* The :math:`F`-linear relations among the eigenvalues form a module for the Galois group of -the compositum. By (a) each block splits into the trivial module and an absolutely irreducible -:math:`V_j` :cite:p:`Isaacs1976`, pairwise non-isomorphic by (b); :math:`V_j` in the relations would -make two roots equal. So a relation lies in the span of the block sums, :math:`\sum_j c_j t_j = 0`, -which (c) excludes. :math:`\square` For one block this is a case of :cite:p:`Girstmair1999`. - -(a) and (b) follow from Frobenius elements: at a prime of degree one where :math:`\chi_j` is -square-free, the degrees of the factors modulo the prime are the cycle type of a Frobenius element -(Dedekind, :cite:p:`Neukirch1999`). Where the test cannot decide, it refuses with the reason; +*The premise at one point.* A point outside the parameters with a rational first integral puts a +generic point outside them, and an equilibrium whose eigenvalues on the level set are linearly +independent over :math:`\mathbb{Q}` has no rational first integral nearby +:cite:p:`CongLlibreZhang2011`. symident draws an equilibrium over a number field and shows this +independence where the Galois group of the characteristic polynomial of each diagonal block acts +2-transitively on the roots, the splitting fields of the blocks are pairwise distinct and the +traces of the blocks are linearly independent; the Galois groups are read from Frobenius elements +at primes of degree one. Where the test cannot decide, it refuses with the reason. ``info["discrete"]["experiments"]["first_integrals"]`` holds the point, the equilibrium and the primes. *The count.* Equation :eq:`eq-count-bound` holds for the stacked model with the projection: -:math:`\lambda` in Step 2 separates the projections of the points of :math:`V_0`, so the solutions +:math:`\lambda` separates the projections of the points of :math:`V_0`, so the solutions at the random point have at least :math:`|\pi(T_K)|` distinct projections, which by Proposition 1 bounds :math:`|T|`. @@ -458,9 +525,9 @@ bounds :math:`|T|`. 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 adds the premise and the -divisibility to ``proven``; ``experiments`` of :meth:`~symident.Symmetries.discrete` selects the -route. +over :math:`\mathbb{Q}` is below :math:`2|G|`, else ``"checked"``. The certificate adds the absence +of a rational first integral and the divisibility to ``proven``; ``experiments`` of +:meth:`~symident.Symmetries.discrete` selects the route. .. _monodromy: @@ -475,22 +542,9 @@ locus :cite:p:`Duff2019`, and tracking the known points around random loops in : others. A point is kept where every coefficient up to the order of the count agrees (``info["discrete"]["monodromy"]``). -*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`, then :math:`\phi` has exactly one zero in :math:`X`, and :math:`\partial \phi` is -invertible there. - -*Proof.* :math:`k(x) = x - Y \phi(x)` maps :math:`X` into :math:`K \subset X` by the mean value -theorem and is a contraction in the norm :math:`\max_i |v_i| / r_i`, so it has one fixed point; the -row sums make :math:`Y` invertible, so the fixed points of :math:`k` are the zeros of :math:`\phi`. -:math:`\square` - -The enclosures are evaluated in rectangle arithmetic rounded outward, so disjoint boxes prove that -many simple zeros of the square system (``certified``). A point of the fiber needs every +The Krawczyk test in rectangle arithmetic rounded outward +:cite:p:`Krawczyk1969,Moore1977,Rump2010` proves the points as simple zeros of the square system +(``certified``). A point of the fiber needs every coefficient equal, an overdetermined identity that no enclosure shows, so the certified boxes are no lower bound of the count; the lower bound is the orbit of the exact maps. A map read from a point is ``exact`` only once the identities of :ref:`maps` hold over :math:`\mathbb{Q}(i)(x, \theta)`. @@ -508,22 +562,30 @@ Certificates 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. + (:ref:`verified-count`) or for several experiments (:ref:`several-experiments`), or the stage + tower pins every coordinate (:ref:`stage-tower`), with the probability ``count_bound`` that the + fiber at a generic point has more points. +``"checked"`` + the count modulo the prime at a random point stands for the count over :math:`\mathbb{C}` at a + generic point, without an error bound; ``count_bound_why`` names the reason no bound applies. ``"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. +.. index:: premise + +The level is that of the count. A count that rests on a property of the model which the analysis +does not show lists it under ``premises``, each with ``kind`` and ``text``: ``"independent_starts"`` +(the starts of the new states of the relaxed model are algebraically independent, +:ref:`fiber`), ``"start_power"`` (a sign of a free power of a state at 0) and +``"generic_event_state"`` (the states at an event are a generic start for the stages after it, +:ref:`stage-tower`). Where the premises hold, the count holds at the stated level. + ``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``. +``rewrites``, ``relaxed``, ``rest_exchange`` and ``start_powers``. diff --git a/docs/method/local.rst b/docs/method/local.rst index 8a322b7..009178e 100644 --- a/docs/method/local.rst +++ b/docs/method/local.rst @@ -11,6 +11,8 @@ of the rank is reached. Lie derivatives and the observability-identifiability matrix ------------------------------------------------------------ +.. index:: Lie derivatives + The *Lie derivatives* of the output are .. math:: @@ -25,16 +27,24 @@ For analytic models they determine the output: near :math:`t_0` it is the Lie se g(t; \theta) = \sum_{k \ge 0} \frac{(t - t_0)^k}{k!}\, L_F^k h\big(z_0(\theta)\big), +.. index:: Lie order + 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`, +.. index:: + single: Ψ_N (output coefficients up to order N) + single: OIM (observability-identifiability matrix) + .. 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}, +.. index:: observability-identifiability matrix + 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 @@ -62,6 +72,8 @@ and the kernel is spanned by the value of the generator above. Ranks over finite fields ------------------------ +.. index:: modular engine + 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 :cite:p:`Sedoglavic2002`. A point can @@ -74,6 +86,8 @@ engine primes, and checked at points uniform modulo the verification prime. Sufficient Lie order -------------------- +.. index:: ceiling + 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 @@ -89,25 +103,6 @@ under :math:`F`. By the chain rule, **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 @@ -115,14 +110,7 @@ Let :math:`\rho_S`, the *ceiling*, be this final rank at a generic point of :mat 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` +.. index:: resting point, Krylov sequence 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 @@ -137,6 +125,8 @@ the same matrix, so there one order without change of rank is final at the point itself. +.. index:: plateau + **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\} @@ -161,6 +151,8 @@ state or reads the states adds it, and the proposition extends to the power seri :ref:`conditions-events`. :math:`U` and :math:`\rho_S` are taken at points uniform modulo the verification prime; the error is bounded in :ref:`order-bound`. +.. index:: saturation guard + **Without a stopping rule.** A direction that is an exact symmetry (:ref:`scalings`, :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"`` confirms @@ -195,8 +187,9 @@ Non-rational terms The modular engine needs rational functions. Elementary functions are therefore recast into rational form :cite:p:`Savageau1987`, innermost first. 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:`\psi` rational in the states becomes a new state with right-hand side +:math:`\frac{\mathrm{d}\varphi}{\mathrm{d}\psi}\, \sum_j \partial_{x_j} \psi \, f_j`, which is +rational in :math:`\nu` and :math:`\psi` for .. math:: @@ -205,12 +198,16 @@ rational form :cite:p:`Savageau1987`, innermost first. A term :math:`\nu = \varp \arctan(\psi):\ \ \frac{1}{1 + \psi^2}, \qquad \operatorname{artanh}(\psi):\ \ \frac{1}{1 - \psi^2}, +.. index:: free power + and for the other inverse functions 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 :math:`\mu` enters through :math:`\partial B / \partial \mu = B L_b`. A nesting the recast cannot order, such as :math:`\sin(\exp x)`, is refused. +.. index:: leaf + 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 engine, a *leaf*, drawn independently of the argument and tied to it by relation rows :math:`\mathrm{d}\nu = @@ -223,10 +220,11 @@ the declared signs do not make positive on :math:`\Theta` is named in ``info["li **Terms of resting states.** Under ``equilibrate`` a transcendental term :math:`\varphi(\psi(x, \theta))` is a leaf :math:`W` in the balances as well, tied to states and coordinates by -:math:`\mathrm{d}W = \varphi'(\psi)\, \mathrm{d}\psi`, and the resting states are solved at the drawn -leaves. 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 :math:`\{f(x, \theta, W) = 0\}` on which the drawn -points lie. Rank and kernel are rational, so their generic values on :math:`A` are those on +:math:`\mathrm{d}W = \frac{\mathrm{d}\varphi}{\mathrm{d}\psi}\, \mathrm{d}\psi`, and the resting +states are solved at the drawn leaves. 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 :math:`\{f(x, \theta, +W) = 0\}` on which the drawn points lie. Rank and kernel are rational, so their generic values on +:math:`A` are those on :math:`M` when :math:`M` is Zariski dense in :math:`A`. This holds when the resting values of the states inside the arguments vary independently of the coordinates inside them, which gives a chart of :math:`M` with rational arguments, and no nontrivial integer combination of the arguments is @@ -237,12 +235,6 @@ Kolchin-Ostrowski theorem :cite:p:`Kolchin1968,Ostrowski1946`: \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.* A relation reads :math:`\sum_a c_a(z)\, e^{\langle a, \psi \rangle} -= 0` with rational :math:`c_a \ne 0` and exponents that differ pairwise by nonconstant functions, -also on a generic line. In a relation with the fewest terms, divided by the last term and -differentiated, every :math:`r_j' + r_j h_j' = 0`, so :math:`e^{h_j}` is a constant over a rational -function, which a nonconstant rational :math:`h_j` excludes. :math:`\square` - Logarithms of rational functions no product of integer powers of which is constant are algebraically independent in the same way, and :math:`\tan(\psi/2)` is rational in :math:`e^{i\psi}`; Ax's theorem :cite:p:`Ax1971` generalizes the lemma. The first condition is @@ -281,12 +273,6 @@ The stopping rule of :ref:`sufficient-lie-order` extends to these outputs. Let : **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 rank of the Wronskian matrix :math:`(u^{(j)}(t))_{j \ge 0}`. -By the chain rule :math:`u^{(j)}(t) = \partial_z L_F^j h(\varphi_t(z_0))\, \Phi(t)` with the -invertible fundamental matrix :math:`\Phi(t)`, and for small :math:`t > 0`, :math:`\varphi_t(z_0)` -is a point of :math:`S` where the output is defined, so the rank is at most :math:`\rho_S`. -:math:`\square` - 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 order is proven sufficient. The event that the base point lies where a leading coefficient vanishes is not counted in @@ -302,21 +288,19 @@ coordinate :math:`\alpha > 0`. Generically :math:`x = c_x t^k (1 + O(t))` with : x^\alpha = S\, Q, \qquad Q = \Big(\frac{x}{c_x t^k}\Big)^{\alpha}, +.. index:: layer + 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`, the *index* :math:`n` and the *layer* :math:`m`, stands for :math:`t^{n - km + km\alpha}`, and differentiation multiplies it by :math:`\lambda_{n,m} = n + km(\alpha - 1) \ge \min(1, \alpha)\, n`. So the coefficients :math:`d_{n,m}` are rational in :math:`\theta` for :math:`\alpha > 0`, and the series converges for -small :math:`t > 0` by a Cauchy majorant. +small :math:`t > 0`. **Lemma.** For distinct real numbers :math:`q_j`, 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.* In a relation, divide by the term of least exponent with a nonzero coefficient -:math:`a_j + b_j \log t`; the other terms tend to 0 as :math:`t \to 0^+`, and :math:`a_j + b_j -\log t` does not. :math:`\square` - For :math:`\alpha \notin \mathbb{Q}` distinct :math:`(n, m)` give distinct exponents, and with several powers this holds where the exponents are distinct coordinates; two powers of states at 0 with the same exponent are refused. The gradient of the output is diff --git a/docs/method/reduction.rst b/docs/method/reduction.rst index 3fee709..ef597a8 100644 --- a/docs/method/reduction.rst +++ b/docs/method/reduction.rst @@ -1,6 +1,8 @@ Reduction ========= +.. index:: chart + 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. @@ -19,6 +21,8 @@ valid choices of the fixed coordinates. Scalings -------- +.. index:: pin, global section, sign certificate + A scaling is removed by fixing one of the coordinates it moves at one, a *pin*. Every orbit of a scaling meets the hypersurface :math:`\theta_i = 1` of a moved positive coordinate once, so the result is a *global section*: a one-to-one map of the new parameters onto a *global @@ -28,6 +32,8 @@ coordinate is pinned like a scaling where a *sign certificate*, a proof that an sign on :math:`\Theta`, shows that the generator component on the pinned coordinate has one sign; else the pin is listed under ``unproven``. +.. index:: transversal, module reduction + The pinned coordinates of a block of scalings, the *transversal*, are coordinates :math:`T` 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; @@ -43,6 +49,8 @@ generators is split by *module reduction* into combinations with smaller support Linear flows ------------ +.. index:: linear flow + 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` @@ -60,6 +68,8 @@ a linear coordinate is pinned to 0, a positive one to 1. General blocks -------------- +.. index:: gauge coordinates + 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 @@ -71,6 +81,8 @@ left. Every level set :math:`\Lambda_q = \{\theta \in \Theta : I(\theta) = q\}` :math:`\Theta`, so every orbit is :math:`r`-dimensional and open in :math:`\Lambda_q`; 3. :math:`\mathcal{G}_q` is connected. +.. index:: section point, positivity certificate + :math:`\mathcal{G}_q` is given by one inequality :math:`\pi_k(q, \vartheta) > 0` per positive solved coordinate. It is connected when every inequality is convex in :math:`\vartheta`, or when a gauge coordinate enters every inequality affinely with a coefficient of known sign and the @@ -78,6 +90,8 @@ projection is connected, decided the same way. The *section point* :math:`\hat\t in :math:`\Lambda_q` and, by a *positivity certificate*, a proof that each entry is positive on the domain, in :math:`\Theta`. +.. index:: section chart + **Sections.** Sections equate *balances*, monomials or summands of the invariants. Where the section point holds a root but the section itself is rational, a *section chart* takes the remaining coordinates of the section as new parameters, which the count of discrete symmetries @@ -90,6 +104,8 @@ positivity certificate is kept, with partial coverage, and listed under ``unprov it is kept only where no section is certified on the whole domain, and the transformation then covers the orbits on which the ``sign_conditions``, the entries as inequalities in :math:`q`, hold. +.. index:: face + **Face sections.** A *face* is a boundary set :math:`\theta_f = 0`; a section on a face lies outside :math:`\Theta` and is reached only in a limit. 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 @@ -129,14 +145,9 @@ reduced. For a model with one condition, no events and no ``equilibrate``, :math *Inversion.* Suppose there are as many observables as unknown inputs, none reads an input, and :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)` 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')` near -:math:`(\hat\theta, \hat x_0)` with :math:`h(x_0', \theta') = \hat g(0)` gives :math:`\hat g` with -some continuous input :math:`w'`. - -*Proof.* The implicit function theorem solves :math:`D(h)(x, \theta, w) = \dot{\hat g}(t)` for -:math:`w = W(t, x, \theta)` near the trajectory, the solution of :math:`\dot x = f(x, \theta, W)` -exists on :math:`[0, T]` by continuous dependence, and :math:`e = h(x', \theta') - \hat g` has -:math:`\dot e = 0`, :math:`e(0) = 0`. :math:`\square` +:math:`\det M \ne 0` along the trajectory. Then every :math:`(\bar\theta, \bar x_0)` near +:math:`(\hat\theta, \hat x_0)` with :math:`h(\bar x_0, \bar\theta) = \hat g(0)` gives :math:`\hat g` +with some continuous input :math:`\bar w`. Every exact direction keeps :math:`h(x_0, \theta)`, so a section chosen as without inputs gives the output of every point under this condition. @@ -155,10 +166,6 @@ over :math:`\mathbb{Q}`, and a given initial value moves with the parameters. Th a solution of the model with :math:`\theta(\varepsilon)` and the input :math:`w(\cdot, \varepsilon)` and the output :math:`\hat g`. -*Proof.* With :math:`R = \partial_t x - f(x, \theta, w)`, Equation :eq:`eq-input-lift` gives -:math:`\partial_\varepsilon R = \partial_x \xi_x\, R` with :math:`R(t, 0) = 0`, hence :math:`R = 0`, -and :math:`\partial_\varepsilon h = V(h) = 0`. :math:`\square` - The reduction removes the field :math:`\xi_\theta` as long as the input stays in the domain of the inputs; initial values and inputs stay free. ``Reduction.blocks`` holds per block ``inputs``: the proof (``"inversion"`` with the ``determinant``, or ``"lift"`` with the components) and the diff --git a/docs/refs.bib b/docs/refs.bib index 2920d6d..909c309 100644 --- a/docs/refs.bib +++ b/docs/refs.bib @@ -96,6 +96,17 @@ @article{Evans2000 doi = {10.1016/S0025-5564(00)00047-X} } +@article{GaleNikaido1965, + author = {Gale, David and Nikaid{\^o}, Hukukane}, + title = {The {Jacobian} matrix and global univalence of mappings}, + journal = {Mathematische Annalen}, + volume = {159}, + number = {2}, + pages = {81--93}, + year = {1965}, + doi = {10.1007/BF01360282} +} + @article{Girstmair1999, author = {Girstmair, Kurt}, title = {Linear relations between roots of polynomials}, diff --git a/pyproject.toml b/pyproject.toml index cce4771..dd1dac1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build" [project] name = "symident" -version = "0.18.2" +version = "0.18.3" description = "Structural identifiability of ODE models by Lie symmetries over finite fields" readme = "README.md" requires-python = ">=3.10" diff --git a/src/symident/__init__.py b/src/symident/__init__.py index 99b4f81..a7e6f30 100644 --- a/src/symident/__init__.py +++ b/src/symident/__init__.py @@ -19,4 +19,4 @@ "install_msolve", "switches", ] -__version__ = "0.18.2" +__version__ = "0.18.3" diff --git a/src/symident/api.py b/src/symident/api.py index fc31763..b721854 100644 --- a/src/symident/api.py +++ b/src/symident/api.py @@ -22,7 +22,7 @@ "points", "memory", "experiments", - "msolve_entries", + "msolve_work", "msolve_terms", "search_entries", "elimination_terms", @@ -305,6 +305,13 @@ def sympy(self): return {k: model_sympify(v) for k, v in self["generator"].items()} +def _level_rank(out): + """The order of the level of a result of discrete(): exact above verified above checked above the rest, and at + one level a result without premises above one with.""" + cert = (out.get("info") or {}).get("certificate") or {} + return 2 * {"exact": 3, "verified": 2, "checked": 1}.get(cert.get("complete"), 0) - bool(cert.get("premises")) + + class Symmetries: """Result of :func:`detect`. @@ -437,7 +444,7 @@ def solution_count(self, order=None): ------- dict or None ``{"count", "order", "prime"}``, or None where the model is not rational, msolve - fails, reaches the work caps (``msolve_entries`` and ``msolve_terms`` of + fails, reaches the work caps (``msolve_work`` and ``msolve_terms`` of :meth:`discrete`), or the solutions are not finitely many. Points where a coordinate or a denominator vanishes are not counted. @@ -496,7 +503,7 @@ def discrete( cores=1, memory=None, experiments=None, - msolve_entries=None, + msolve_work=None, msolve_terms=None, search_entries=None, elimination_terms=None, @@ -543,21 +550,24 @@ def discrete( 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_work : int, optional + The work of the F4 rounds that one call of msolve may do, 10^10 by default, read from + the output of msolve: per round the columns of the matrix times the pairs selected and + the elements of the basis before it, and the new elements times the pairs after it. A + round is charged at the header with the widest matrix so far, so the call ends before + the symbolic preprocessing of a round past the cap, without a result. The first short + count and the count of a block before the stages take a fraction of it, and the calls + of one count share twice this cap. 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 + The entries of the matrices over finite fields that the exact count may reduce, 2 * 10^9 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. + 3 * 10^6 by default, and of the minors of one determinant together. 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. @@ -584,8 +594,10 @@ def discrete( ``rewrites``, ``candidates``, ``timing`` (seconds per stage), ``certificate`` (what 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 with ``count_bound``, or the count modulo a prime without a bound where neither + applies, and ``complete``: ``"exact"``, ``"verified"``, ``"checked"``, ``"no"`` or + ``"open"``; ``premises``, each ``{"kind", "text"}``, under which the count holds at the + stated level; 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`` @@ -603,7 +615,7 @@ def discrete( from .detection import work limits = { - "msolve_entries": msolve_entries, + "msolve_work": msolve_work, "msolve_terms": msolve_terms, "search_entries": search_entries, "elimination_terms": elimination_terms, @@ -623,6 +635,7 @@ def _discrete(self, order, points, cores, experiments=None): from .detection.relax import terms_of_states obs = self.model.observables + relaxed = None 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: @@ -633,13 +646,17 @@ def _discrete(self, order, points, cores, experiments=None): cores=cores, ) if not (out["info"].get("certificate") or {}).get("relaxed_why"): - return out + if _level_rank(out) >= _level_rank({"info": {"certificate": {"complete": "verified"}}}): + return out + relaxed = out except ValueError: pass # the continuous symmetries first: the reduced model has a finite fiber try: red = self._reduced_detection() except ValueError as exc: + if relaxed is not None: + return self._keep_discrete(relaxed) from .detection.rationalize import _blocking from .sym.parse import model_sympify @@ -650,6 +667,8 @@ def _discrete(self, order, points, cores, experiments=None): # 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) + if relaxed is not None and _level_rank(relaxed) > _level_rank(out): + return self._keep_discrete(relaxed) out["info"]["reduced"] = { "trafo": red.model.trafo, "fixed": list(red.model.fixed or []), @@ -667,6 +686,15 @@ def _discrete(self, order, points, cores, experiments=None): return self._relaxed_discrete(exc, order=order, points=points, cores=cores, experiments=experiments) st = self.info.get("settings") or {} positive = st.get("positive", True) + rest = rw.get("rest") + if rest is not None: + coords = list(rest["coordinates"]) + if positive is not True: + # a resting value holds the sign of the state; a coordinate solved in exchange holds none + old = [str(x) for x in declared(positive)[0] or ()] + [str(x) for x in declared(positive)[1]] + positive = [p for p in old if p not in rest["exchanged"]] + [ + r for x, r in rest["rest"].items() if x in old + ] if rw["logs"] and positive is not True: # X = b^theta is positive whatever the domain of theta positive = list(declared(positive)[0] or ()) + [str(x) for x in declared(positive)[1]] + list(rw["logs"]) @@ -689,6 +717,8 @@ def _discrete(self, order, points, cores, experiments=None): "a prime, the real count at rational points" ] + out["info"]["limits"] out["info"]["rewrites"] = rw["rewrites"] + if rest is not None: + self._rest_exchanged(out, rest) 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)] @@ -707,6 +737,45 @@ def _discrete(self, order, points, cores, experiments=None): report_given(out, rw["logs"]) return self._keep_discrete(out) + def _rest_exchanged(self, out, rest): + """The result of discrete() in the resting chart: the coordinates solved from the balances map the values + of the coordinates injectively into the chart, so a count of one there is one here; other counts and the + maps stay in the chart.""" + info = out["info"] + cert = info.get("certificate") or {} + info["rest_exchange"] = rest + if rest.get("kind") == "root": + info["limits"].append( + "the start " + + ", ".join(rest["rest"].values()) + + f" holds {rest['root']} and is a coordinate in place of " + + ", ".join(rest["exchanged"]) + + ", solved from it (info['discrete']['rest_exchange']); the count is that of this chart, " + "and the domain does not hold the coordinates solved in exchange in their declared signs" + ) + else: + info["limits"].append( + "under equilibrate the resting values " + + ", ".join(rest["rest"].values()) + + " are coordinates in place of " + + ", ".join(rest["exchanged"]) + + ", solved from the balances (info['discrete']['rest_exchange']); the count is that of this chart, " + "and the domain does not hold the coordinates solved in exchange in their declared signs" + ) + cert.setdefault("proven", []).append( + "the coordinates solved in exchange are rational functions of the chart, so the values of the " + "coordinates with the output of a generic point map injectively into the fiber of the chart" + ) + info["count_domain"] = None + if info.get("count") != 1: + # a map of the chart need not keep the resting state the model starts from + cert["rest_why"] = "the count of the chart is not one, and the maps of the chart are not mapped back" + if cert.get("complete") in ("exact", "verified", "checked"): + cert["complete"] = "open" + info["count_final"] = False + for sym in out["symmetries"]: + sym["chart"] = True + def _keep_discrete(self, out): """The result `out` of discrete(), stored on this result.""" self.info["discrete"] = out["info"] @@ -719,7 +788,16 @@ 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 + from .detection.discrete import add_premise + from .detection.relax import ( + affine_on_orbits, + independent_leaves, + keeps_leaves, + monotone_on_orbits, + private_leaves, + relax, + scalings_keep_leaves, + ) if getattr(self, "_relaxed", False): # a relaxed model is not relaxed again @@ -774,16 +852,25 @@ def _relaxed_discrete(self, exc, **opts): 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 + syms = r._raw.get("symmetries") or [] + why = scalings_keep_leaves(syms, rx["leaves"], rx["dropped"]) if not r.identifiable else None + affine = why is not None and affine_on_orbits(syms, rx["leaves"], rx["dropped"]) is None + monotone = ( + why is not None + and not affine + and monotone_on_orbits(syms, rx["leaves"], rx["dropped"], rx["positive"]) is None ) + if affine or monotone: + why = 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)): + if ( + free + and not (len(kinds) == 1 and kinds <= {"exp", "log"} and independent_leaves(free, coords)) + and not private_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" @@ -831,19 +918,31 @@ def _relaxed_discrete(self, exc, **opts): info["relaxed"]["count"], info["count"] = count, None info["count_domain"] = None cert["relaxed_why"] = why - if cert.get("complete") in ("exact", "verified", "axiom"): + if cert.get("complete") in ("exact", "verified", "checked"): 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"] + # with the premise of the count of the relaxed model + add_premise(cert, "independent_starts", 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" ) + if affine: + cert["proven"].append( + "the conditions that tie the new coordinates to their starts are affine in the parameters of the " + "continuous directions on every orbit, so an orbit meets the starts in a connected set" + ) + if monotone: + cert["proven"].append( + "the conditions that tie the new coordinates to their starts have rates along the continuous " + "directions whose principal minors keep one sign on the domain, so an orbit meets the starts in the " + "domain in one point at most (Gale and Nikaido)" + ) + info["limits"].append( + "the count of the relaxed model bounds the points of the fiber in the domain, where the conditions " + "of the new coordinates are monotone along the continuous directions" + ) for s in out["symmetries"]: if s.get("map"): s["relaxed"] = True @@ -899,7 +998,7 @@ def _fiber_parts(self, order, what, switches=True): time_value, ) from .detection.core import _input_jets - from .detection.discrete import observed_states, resting_start + from .detection.discrete import observed_states, resting_exchange, resting_start from .errors import SYMPY_FAILS from .rexpr import get_symbols, replace_symbols from .sym.switching import _SWITCHY @@ -921,12 +1020,22 @@ def _fiber_parts(self, order, what, switches=True): from .detection.cq import reduced_by_totals f0, obs, events, recon = reduced_by_totals(f0, obs, events, m.totals, st["eliminated"]) + from .detection.clock import clock_events + + # a switch on the clock alone is an indicator state set by an event at the time of the switch + gs = list(obs) if isinstance(obs, (list, tuple)) else [dict(obs)] + clock = clock_events(f0, gs, list(get_symbols(list(f0.values()))), st.get("positive", True)) + clock_starts = {} + if clock is not None: + f0, gs, clock_starts, clock_ev = clock + obs = gs if isinstance(obs, (list, tuple)) else gs[0] + events = list(events) + [{**e, "root": None} for e in clock_ev] 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()] 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): + if (self.info.get("switching") and clock is None) or roots or any(_SWITCHY.search(v) for v in texts): if not switches: return None hy = self._switches(f0, obs, events, what) @@ -948,6 +1057,7 @@ def _fiber_parts(self, order, what, switches=True): rows = (grid.rows if grid is not None and grid.rows else None) or [str(c + 1) for c in range(K)] inputs = set(m.inputs or []) per = [] + chart = {} 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 @@ -957,6 +1067,7 @@ def _fiber_parts(self, order, what, switches=True): if str(k) not in recon } tr = initial_value_split([tr], list(f0), taken=list(g))["trafos"][0] + tr.update(clock_starts) sub = {k: v for k, v in tr.items() if k not in f0} cells = ( {} @@ -997,7 +1108,16 @@ def apply(e, steps=steps): ic = {x: "0" if x in inputs else at_time(apply(tr.get(x, cells.get(x, x))), start) for x in f} if equil: # the condition rests with the inputs at zero before the events at the start - ic = resting_start(f, ic, inputs, set(self.info.get("coordinates") or ())) + cset = set(self.info.get("coordinates") or ()) + try: + ic = resting_start(f, ic, inputs, cset) + except ValueError as exc: + if what != "discrete()" or "does not solve the balances" not in str(exc): + raise + try: + ic = resting_exchange(f, ic, inputs, cset, chart, list(m.fixed or []), st.get("positive", True)) + except ValueError as err: + raise ValueError(f"{exc}; no resting chart: {err}") from None # an event on a state the observables do not depend on changes nothing ev = [e for e in ev if e["var"] in f] first = [e for e in ev if time_value(e["time"]) is not None and time_value(e["time"]) <= t0] @@ -1076,15 +1196,46 @@ def key(e): if regimes is not None: for part in parts[n0:]: part["surfaces"] = [apply(q) for q in regimes[0]["surfaces"]] + coords = list(self.info.get("coordinates") or ()) + if not chart: + from .detection.restchart import root_chart + + # starts with the square root of a polynomial: the start of one state in exchange for a coordinate + chart = root_chart(parts, coords, st.get("positive", True), list(m.fixed or [])) or {} + if chart: + # the coordinates solved from the balances in exchange for the resting values + ex = {str(p): f"({v})" for p, v in chart["exchanged"].items()} + + def swap(e): + return None if e is None else replace_symbols(list(ex), list(ex.values()), str(e)) + + for part in parts: + for seg in part["segments"]: + seg["f"] = {k: swap(v) for k, v in seg["f"].items()} + seg["g"] = {k: swap(v) for k, v in seg["g"].items()} + if "ic" in seg: + seg["ic"] = {k: swap(v) for k, v in seg["ic"].items()} + for e in seg.get("events") or []: + e["value"] = swap(e["value"]) + coords = [c for c in coords if c not in ex] + [str(r) for r in chart["rest"].values()] from .detection.rationalize import NotRationalError, rationalize try: - parts, rewrites, logs = rationalize(parts, list(self.info.get("coordinates") or ()), states) + parts, rewrites, logs = rationalize(parts, coords, 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, "states": states, "eliminated": recon} + rest = None + if chart: + rest = { + "rest": {str(x): str(r) for x, r in chart["rest"].items()}, + "exchanged": {str(p): str(v).replace("**", "^") for p, v in chart["exchanged"].items()}, + "coordinates": coords, + } + if chart.get("kind") == "root": + rest.update(kind="root", root=chart["root"]) + return parts, {"rewrites": rewrites, "logs": logs, "states": states, "eliminated": recon, "rest": rest} def _switches(self, f, obs, events, what): """The model in the indicators of the undecided switches (sym.switching.Hybrid), a dict where the declared @@ -1412,7 +1563,7 @@ def detect( ``info["discrete"]["unsupported"]`` and a warning. global_options : dict, optional Arguments of the global analysis: ``order``, ``points``, ``memory``, ``experiments`` and the - work limits ``msolve_entries``, ``msolve_terms``, ``search_entries`` and + work limits ``msolve_work``, ``msolve_terms``, ``search_entries`` and ``elimination_terms`` of :meth:`Symmetries.discrete`. Returns diff --git a/src/symident/detection/clock.py b/src/symident/detection/clock.py new file mode 100644 index 0000000..9f0cba8 --- /dev/null +++ b/src/symident/detection/clock.py @@ -0,0 +1,124 @@ +"""Switches on the clock alone as events: piecewise(A, time < c, B) is A + (B - A) s with an indicator state s, s' = 0, +that an event at time c sets from 0 to 1 (docs/method/global.rst, "Conditions, events, resting states and switches").""" + +import sympy as spy + +from ..sym.parse import model_sympify +from ..sym.switching import _SWITCHY as _SWITCH +from .rationalize import _str + +TIME = spy.Symbol("time") + + +def _threshold(cond, states): + """(c, after) for a comparison of a + b time with 0, b a nonzero number and a free of the clock and the states, + c = -a/b: `after` whether the comparison holds after the time c. None otherwise.""" + if not isinstance(cond, (spy.StrictLessThan, spy.LessThan, spy.StrictGreaterThan, spy.GreaterThan)): + return None + d = spy.expand(cond.lhs - cond.rhs) + b = d.coeff(TIME, 1) + a = spy.expand(d - b * TIME) + if not b.is_number or b == 0 or a.has(TIME) or a.free_symbols & states: + return None + greater = isinstance(cond, (spy.StrictGreaterThan, spy.GreaterThan)) + return spy.nsimplify(-a / b, rational=True) if a.is_number else -a / b, greater == bool(b > 0) + + +def clock_events(f, gs, starts, positive, start=0): + """(f, gs, {indicator: start}, events) with every piecewise() on the clock alone in the right-hand sides `f` and + the observables `gs` (a list of dicts) replaced by indicators; None where no expression holds such a switch or + another switch remains. A threshold c is a number or a coordinate declared positive, and the conditions start at + `start` = 0; `starts` are the names in use.""" + states = {spy.Symbol(x) for x in f} + pos = None if positive is True else {str(p) for p in (positive or ())} + ind, events, init = {}, [], {} + taken = set(starts) | set(f) + + def indicator(c): + """1 from the time c on: an indicator state, or 1 for a number c at or before the start.""" + key = spy.srepr(c) + if key not in ind: + if c.is_number: + if c <= start: + return spy.Integer(1) + elif not (c.is_Symbol and (pos is None or str(c) in pos)): + raise _SkipError + k = 1 + while f"si_clock{k}" in taken: + k += 1 + name = f"si_clock{k}" + taken.add(name) + ind[key] = spy.Symbol(name) + init[name] = "0" + events.append({"var": name, "time": _str(c), "value": "1", "method": "replace"}) + return ind[key] + + def holds(cond): + """The condition as a product of indicators: comparisons of the clock, joined by and, or and not.""" + if isinstance(cond, spy.And): + return spy.Mul(*[holds(c) for c in cond.args]) + if isinstance(cond, spy.Or): + return 1 - spy.Mul(*[1 - holds(c) for c in cond.args]) + if isinstance(cond, spy.Not): + return 1 - holds(cond.args[0]) + th = _threshold(cond, states) + if th is None: + raise _SkipError + s = indicator(th[0]) + return s if th[1] else 1 - s + + def piece(pw): + # piecewise(v1, c1, v2, c2, ..., otherwise) of the expression language + args = pw.args + if len(args) % 2 == 0: + raise _SkipError + out = args[-1] + for e, cond in reversed(list(zip(args[:-1:2], args[1:-1:2]))): + if spy.cancel(e - out) == 0: + # a switch between equal pieces is none + continue + out = out + holds(cond) * (e - out) + return out + + def conv(text): + e = model_sympify(str(text)) + if not _pieces(e): + return text, False + while _pieces(e): + # the innermost first + inner = next(a for a in _pieces(e) if len(_pieces(a)) == 1) + e = e.xreplace({inner: piece(inner)}) + if _SWITCH.search(_str(e)): + raise _SkipError + return _str(spy.cancel(e) if e.is_rational_function() else e), True + + try: + f2, hit = {}, False + for x, v in f.items(): + f2[x], h = conv(v) + hit |= h + gs2 = [] + for g in gs: + d = {} + for y, v in g.items(): + d[y], h = conv(v) + hit |= h + gs2.append(d) + except _SkipError: + return None + if not hit: + return None + # an indicator whose switch leaves every expression unchanged is dropped + texts = list(f2.values()) + [w for g in gs2 for w in g.values()] + used = {str(s) for v in texts for s in model_sympify(v).free_symbols} + events = [e for e in events if e["var"] in used] + f2.update({e["var"]: "0" for e in events}) + return f2, gs2, {e["var"]: init[e["var"]] for e in events}, events + + +def _pieces(e): + return [a for a in spy.preorder_traversal(e) if isinstance(a, spy.Function) and a.func.__name__ == "piecewise"] + + +class _SkipError(Exception): + """A switch outside the clock or a threshold the indicators do not cover.""" diff --git a/src/symident/detection/discrete.py b/src/symident/detection/discrete.py index cd245a4..b8f4757 100644 --- a/src/symident/detection/discrete.py +++ b/src/symident/detection/discrete.py @@ -11,10 +11,9 @@ from concurrent.futures import ThreadPoolExecutor from fractions import Fraction +import flint 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 _core, session, state @@ -68,7 +67,9 @@ def _fiber_terms(): _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", + "work": "msolve reached the cap msolve_work of {entries:,} units of work of F4", + "shared": "the calls of msolve of one count reached twice the cap msolve_work, {shared:,} units of work of F4 " + "together", "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", @@ -81,7 +82,7 @@ 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" + kind = "shared" if getattr(r, "shared", False) else "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" @@ -101,9 +102,10 @@ def no_count_reason(order): cap=5000, unknowns=cap("msolve_unknowns"), terms=cap("msolve_terms"), - entries=int(cap("msolve_entries")), + entries=int(cap("msolve_work")), + shared=int(2 * cap("msolve_work")), ) - for k in ("memory", "work", "size", "dimension", "quotient", "error") + for k in ("memory", "work", "shared", "size", "dimension", "quotient", "error") if k in _FAILURES ] return f"msolve found no finite count up to order {order}: " + "; ".join(why) @@ -207,12 +209,17 @@ def _mul_add(acc, x, y, room): 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: + if not _is_poly(x) or not _is_poly(y) or len(x) * len(y) <= room: acc = acc + x * y else: - items, step = list(x.items()), max(1, room // max(1, len(y))) + items, step = list(x.terms()), 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 + part = items[s : s + step] + if isinstance(x, flint.fmpq_mpoly): + part = x.context().from_dict(dict(part)) + else: + part = x.ring.dtype(part) + acc = acc + part * y if _terms(acc) > room: raise FiberTooLargeError(room) if _terms(acc) > room: @@ -222,13 +229,27 @@ def _mul_add(acc, x, y, room): 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 + return sum(_terms(c) for c in x.c) if isinstance(x, _Eps) else len(x) if _is_poly(x) else 1 + + +def _is_poly(x): + """Whether x is a polynomial of the FLINT context of the fiber (not a number, a dual or a series in eps).""" + return isinstance(x, (flint.fmpq_mpoly, dict)) + +def _scalar(one, c): + """The rational number c in the arithmetic of `one`: FLINT polynomials take fmpq, the others Fraction.""" + base = one.c[0] if isinstance(one, _Eps) else one + if isinstance(base, flint.fmpq_mpoly) and isinstance(c, Fraction): + return flint.fmpq(c.numerator, c.denominator) + return c -def _ser_poly(P, xs, params, n, one, zero, limit=None): + +def _ser_poly(P, xs, params, n, one, zero, limit=None, nodes=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.""" + series has more terms. `nodes` maps sorted tuples of state indices to the series of their product (product + jets): a monomial of three or more state factors is the node of all but the last factor times the last.""" out = [zero] * (n + 1) cache = {} @@ -244,18 +265,27 @@ def power(i, e): ns = len(xs) for m, c in P.items(): - coef = one * c + coef = one * _scalar(one, c) for j, e in enumerate(m[ns:]): if e: coef = coef * params[j] ** e - ser = [coef] + [zero] * n - for i, e in enumerate(m[:ns]): - if e: - ser = _ser_mul(ser, power(i, e), n, zero, limit) + fac = _factors(m[:ns]) + if nodes and len(fac) >= 3 and fac[:-1] in nodes: + ser = [coef * t for t in _ser_mul(nodes[fac[:-1]], xs[fac[-1]], n, zero, limit)] + else: + ser = [coef] + [zero] * n + for i, e in enumerate(m[:ns]): + if e: + ser = _ser_mul(ser, power(i, e), n, zero, limit) out = check([u + v for u, v in zip(out, ser)]) return out +def _factors(exps): + """The state indices of a monomial with their multiplicity, sorted: (0, 0, 2) for x0^2 x2.""" + return tuple(i for i, e in enumerate(exps) for _ in range(e)) + + class _Eps: """A power series in the formal gap variable eps, truncated after a fixed degree, over the coefficients of any ring: the gaps between events are eps times the given gaps, as in the local analysis.""" @@ -345,10 +375,10 @@ def _coeffs(x): return x.c if isinstance(x, _Eps) else [x] -def _flow(F, xs, params, order, one, zero, skip=(), meter=None, weight=1): +def _flow(F, xs, params, order, one, zero, skip=(), meter=None, weight=1, given=None): """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. Coefficient k spends (k + 1)^2 times `weight` times the - terms of F on `meter`; CapError past the cap.""" + at a pole. `skip` holds the states whose series is known, `given` {(i, k): value} coefficients taken as they are. + 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): @@ -362,6 +392,8 @@ def _flow(F, xs, params, order, one, zero, skip=(), meter=None, weight=1): return False rest = sum((dser[l] * (k + 1 - l) * xs[i][k + 1 - l] for l in range(1, k + 1)), zero) xs[i][k + 1] = (nser[k] - rest) / ((k + 1) * dser[0]) + if given and (i, k + 1) in given: + xs[i][k + 1] = given[(i, k + 1)] return True @@ -383,6 +415,8 @@ class Series: # the Taylor series of jacobian() spend on `meter`; `capped` holds the order not formed within the cap meter = capped = None + # {(state, k): value} Taylor coefficients of the first condition taken as given in _outputs() + given = None def __init__(self, parts, coords, positive=True): self.coords = list(coords) @@ -649,6 +683,7 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): out = [] for pi, part in enumerate(self.parts): xs = None + given = self.given if pi == 0 else None for j, seg in enumerate(part["segs"]): if j == 0: kser = self._known_series(pi, order) @@ -672,6 +707,9 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): if d == 0: return None xs.append([_eval(num, cvals, zero) / d] + [zero] * order) + for (i, k), v in (given or {}).items(): + if k == 0: + xs[i][0] = v if seg["on"] is not None: i, A, B = seg["on"][:3] start = [x[0] for x in xs] @@ -714,11 +752,12 @@ def _outputs(self, cvals, order, gap, one, zero, meter=None, weight=1): 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) + and not _flow(seg["F"], xs, params, order, o, z, kser, meter, weight, given if j == 0 else None) ): return None if pi == 0 and j == 0: - # the series of the states at the start of the first condition, for the exact count + # the series of the states at the start of the first condition, for the exact count and the + # stage tower self.states0 = xs for M, E in seg["G"]: mser = _ser_poly(M, xs, params, order, o, z) @@ -905,6 +944,51 @@ def adds(row): return orders return "short" + def _needs(self, pi, orders, order): + """Per state of part `pi` the highest jet the observables at `orders` read, directly or through the + equations of the jets they read; None for a part with events, a free power at the start or inputs.""" + part = self.parts[pi] + if len(part["segs"]) > 1 or part.get("spow") is not None or self.inputs: + return None + seg = part["segs"][0] + ns = len(part["st"]) + row0 = sum(len(s["labels"]) for p_ in self.parts[:pi] for s in p_["segs"]) + + def states(*polys): + return {i for P in polys for m in P for i in range(ns) if m[i]} + + need = [0] * ns + for (M, E), n in zip(seg["G"], orders[row0 : row0 + len(seg["G"])]): + for i in states(M, E): + need[i] = max(need[i], n) + reads = [states(N, D) for N, D in seg["F"]] + changed = True + while changed: + changed = False + for i in range(ns): + for j in reads[i]: + if need[i] - 1 > need[j]: + need[j], changed = need[i] - 1, True + return [min(n, order) for n in need] + + def _product_nodes(self, pi, orders, need): + """{factors: order} of the product jets of part `pi`: every proper prefix of two or more factors of a + monomial of three or more state factors, up to the highest order at which a right-hand side or an + observable reads the monomial.""" + seg = self.parts[pi]["segs"][0] + ns = len(self.parts[pi]["st"]) + row0 = sum(len(s["labels"]) for p_ in self.parts[:pi] for s in p_["segs"]) + uses = [(polys, need[i] - 1) for i, polys in enumerate(seg["F"]) if need[i] >= 1] + uses += list(zip(seg["G"], orders[row0 : row0 + len(seg["G"])])) + nodes = {} + for polys, o in uses: + for P in polys: + for m in P: + fac = _factors(m[:ns]) + for L in range(2, len(fac)): + nodes[fac[:L]] = max(nodes.get(fac[:L], 0), o) + return nodes + 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.""" @@ -920,6 +1004,7 @@ def _jet_names(self, orders, order, gap): ) jets.update(self._spow_jets(pi, order, kser)) continue + need = self._needs(pi, orders, order) or [order] * len(part["st"]) for j, seg in enumerate(part["segs"]): for i in range(len(part["st"])): if j == 0: @@ -927,7 +1012,7 @@ def _jet_names(self, orders, order, gap): 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 k in range(lo, order + 1): + for k in range(lo, need[i] + 1): jets[(pi, j, i, k, 0)] = f"si_j{pi}_{j}_{i}_{k}" else: # the start after an event is a separate jet where the event divides by the states, and @@ -954,16 +1039,32 @@ def prolonged(self, orders, gap=0): 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} + # product jets: a product of three or more state factors as a chain of products of two series + nodes = {} + for pi in range(len(self.parts)): + need = self._needs(pi, orders, order) + if need is not None: + nodes[pi] = sorted(self._product_nodes(pi, orders, need).items(), key=lambda kv: (len(kv[0]), kv[0])) + for idx, (_, o) in enumerate(nodes[pi]): + jets.update({("q", pi, idx, k): f"si_q{pi}_{idx}_{k}" for k in range(o + 1)}) if len(names) + len(jets) > _FIBER_UNKNOWNS: raise FiberTooLargeError(len(names) + len(jets), "unknowns") - R, *gens = ring(",".join(names + list(jets.values())), QQ) + R = flint.fmpq_mpoly_ctx.get(tuple(names + list(jets.values())), "degrevlex") + gens = list(R.gens()) g = dict(zip(names + list(jets.values()), gens)) + one_, zero_ = R.constant(1), R.from_dict({}) cof = {str(c): g[str(c)] for c in self.cs} params = [g[str(p)] for p in self.params] pad = (0,) * len(jets) def in_ring(P): - return R.from_dict({mm + pad: c for mm, c in P.items()}) if P else R.zero + return ( + R.from_dict({mm + pad: flint.fmpq(c.numerator, c.denominator) for mm, c in P.items()}) if P else zero_ + ) + + def number(v): + v = spy.Rational(v) + return R.constant(flint.fmpq(int(v.p), int(v.q))) eqs, outs = [], [] sat = [cof[str(c)] for c in self.cs] @@ -980,7 +1081,7 @@ def add_eq(e): def add_sat(e): e = _lead(e) - if not e.is_ground: + if not e.is_constant(): sat.append(e) row = 0 @@ -988,43 +1089,47 @@ def add_sat(e): kser = self._known_series(pi, order) xs = None sp = part.get("spow") + # the jets each state needs: the observables at `orders` determine the others by the equations alone + need = self._needs(pi, orders, order) or [order] * len(part["st"]) for j, seg in enumerate(part["segs"]): if j == 0: xs = [] for i in range(len(part["st"])): v, num, den = seg["x0"][i] if i in kser: - xs.append([R(spy.Rational(c.numerator, c.denominator)) for c in kser[i]]) + xs.append([number(spy.Rational(c.numerator, c.denominator)) for c in kser[i]]) continue if sp is not None and i == sp["N"]: xs.append(None) continue if (pi, i) in zero_in: - a0 = R.zero + a0 = 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: a0 = g[jets[(pi, 0, i, 0, 0)]] - # the start is a polynomial in the coordinates; the jet variables follow them in R + # the start is a rational function of the coordinates; the jet variables follow them in R, + # and the denominator of the start joins the saturation add_eq(in_ring(den) * a0 - in_ring(num)) + add_sat(in_ring(den)) elif v.is_number: - a0 = R(spy.Rational(v)) + a0 = number(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)]) + xs.append([a0] + [g[jets[(pi, 0, i, k, 0)]] for k in range(1, need[i] + 1)]) if seg["on"] is not None: N, D = seg["on"][3:] start = [x[0] for x in xs] - add_eq(_value(N, start, params, R.one, R.zero)) - add_sat(_value(D, start, params, R.one, R.zero)) - o, z = R.one, R.zero + add_eq(_value(N, start, params, one_, zero_)) + add_sat(_value(D, start, params, one_, zero_)) + o, z = one_, zero_ else: - o, z = _Eps([R.one] + [R.zero] * gap), _Eps([R.zero] * (gap + 1)) - pre = [_at_gap(x, in_ring(seg["dt"]), gap, R.one, R.zero) for x in xs] + o, z = _Eps([one_] + [zero_] * gap), _Eps([zero_] * (gap + 1)) + pre = [_at_gap(x, in_ring(seg["dt"]), gap, one_, zero_) for x in xs] xs = [] for i in range(len(part["st"])): @@ -1036,11 +1141,7 @@ def jet(k, i=i): if (pi, j, i, 0, 0) in jets: w0 = jet(0) # the state at the event: the series at the anchor where the start holds coordinates - at = ( - _at_gap([w0] + ws, in_ring(seg["off"]), gap, R.one, R.zero) - if seg["off"] is not None - else w0 - ) + at = _at_gap([w0] + ws, in_ring(seg["off"]), gap, one_, zero_) if seg["off"] is not None else w0 if i in seg["event"]: N, D = seg["event"][i] nv, dv = _value(N, pre, params, o, z), _value(D, pre, params, o, z) @@ -1049,17 +1150,17 @@ def jet(k, i=i): add_sat(dv) else: c = next(iter(D.values())) - w0 = nv * R(spy.Rational(c.denominator, c.numerator)) + w0 = nv * number(spy.Rational(c.denominator, c.numerator)) 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) + o, z = _Eps([one_] + [zero_] * (L - 1)), _Eps([zero_] * L) def layers(key): - return _Eps([g[jets[key + (m,)]] if key + (m,) in jets else R.zero for m in range(L)]) + return _Eps([g[jets[key + (m,)]] if key + (m,) in jets else zero_ for m in range(L)]) for i in range(len(xs)): if i == sp["N"]: @@ -1084,19 +1185,31 @@ def layers(key): add_sat, _fiber_terms(), ) + pn = None + if j == 0 and pi in nodes: + # each product jet is the product of a shorter one (or a state) and one state, order by order + pn = {} + for idx, (key, top) in enumerate(nodes[pi]): + A = pn[key[:-1]] if len(key) > 2 else xs[key[0]] + B = xs[key[-1]] + q = [g[jets[("q", pi, idx, k)]] for k in range(top + 1)] + for k in range(top + 1): + add_eq(q[k] - sum((A[l] * B[k - l] for l in range(k + 1)), z)) + pn[key] = q for i, (N, D) in enumerate(seg["F"]): if (j == 0 and i in kser) or sp is not None: continue - 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): + top = need[i] if j == 0 else order + nser = _ser_poly(N, xs, params, top - 1, o, z, _fiber_terms(), pn) if top else [] + dser = _ser_poly(D, xs, params, top - 1, o, z, _fiber_terms(), pn) if top else [] + for k in range(top): 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, _fiber_terms())[0]) for M, E in seg["G"]: n = orders[row] row += 1 - mser = _ser_poly(M, xs, params, n, o, z, _fiber_terms()) - eser = _ser_poly(E, xs, params, n, o, z, _fiber_terms()) + mser = _ser_poly(M, xs, params, n, o, z, _fiber_terms(), pn) + eser = _ser_poly(E, xs, params, n, o, z, _fiber_terms(), pn) add_sat(eser[0]) outs.append( ( @@ -1128,7 +1241,7 @@ def _sparse_ring(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()} + return {tuple(int(e) for e in m): Fraction(int(c.numerator), int(c.denominator)) for m, c in P.terms()} def _clear(P, p=0): @@ -1664,14 +1777,15 @@ def complex_count(fib, point, p, exact=False, dims=None): if sysd is None: return None n = 1 - for block in sysd["blocks"]: - if exact: - k = _gb_count(block["names"], p, block["eqs"], block["proj"], exact=exact, dims=dims) - else: - k = _staged_count(fib, block["idx"], block["polys"], block["sat"], p) - if not k: - return None - n *= k + with work.shared_work(): + for block in sysd["blocks"]: + if exact: + k = _gb_count(block["names"], p, block["eqs"], block["proj"], exact=exact, dims=dims) + else: + k = _staged_count(fib, block["idx"], block["polys"], block["sat"], p) + if not k: + return None + n *= k return n @@ -1825,14 +1939,14 @@ def ev(coeffs, x): 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 + over the points. The block is first counted at once within an eighth of the cap msolve_work 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") + cap = work.cap("msolve_work") 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): + with work.local_caps(msolve_work=cap / 8): k = _block_count(fib, idx, polys, sat, p) if k is not None: return k @@ -1841,7 +1955,7 @@ def _staged_count(fib, idx, polys, sat, p): # 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): + with work.local_caps(msolve_work=cap / 16): if _stage_points(fib, A, inA, satA, PRIMES[0]) is None: A = None if A is not None: @@ -2760,8 +2874,8 @@ def candidates(series, order, gap, p, meter=None): rng = session.current().rng("discrete candidates", tuple(series.coords)) pt = [rng.randint(2, p - 1) for _ in series.cs] - def vals(v): - out = series.numeric(dict(zip(series.cs, v)), order, gap, p) + def vals(v, n): + out = series.numeric(dict(zip(series.cs, v)), n, gap, p) return None if out is None else [r for k, r in enumerate(out) if k not in series.free_rows] def swapped(pairs): @@ -2770,21 +2884,29 @@ def swapped(pairs): v[i], v[j] = v[j], v[i] return v - base = vals(pt) - if base is None: + # the coefficients up to an order are those of every higher order: a permutation is rejected at the least of the + # doubling orders where they differ + steps = [] if series.start_powers else [2**e for e in range(order.bit_length()) if 2**e < order] + steps.append(order) + bases = [vals(pt, n) for n in steps] + if bases[-1] is None: return [] + + def keeps(v): + return all(vals(v, n) == b for n, b in zip(steps, bases)) + found, failed = [], [] for idx in groups.values(): for i, j in itertools.combinations(idx, 2): if meter.spend(): return _as_maps(series, found) - (found if vals(swapped([(i, j)])) == base else failed).append([(i, j)]) + (found if keeps(swapped([(i, j)])) else failed).append([(i, j)]) for a, b in itertools.combinations(failed, 2): 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: + if keeps(swapped(a + b)): found.append(a + b) return _as_maps(series, found) @@ -3082,19 +3204,18 @@ def fundamental_domain(coords, states, maps): return list(dict.fromkeys(out)) -def choose_order(series, positive, start, cap, floor=1, proj=None, lowest=False, raises=None): +def choose_order(series, positive, start, cap, floor=1, proj=None, lowest=True, 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` 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.""" + the values of the first `proj` coordinates. Each observable starts one order above the order of that observable + in the rank criterion; without `lowest`, every observable starts one above the highest of these orders.""" 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 + # smaller in count and faster to solve, and an observable one order higher adds equations of more jets base = ( ([c + 1 for c in crit] if lowest else [max(crit) + 1] * len(crit)) if crit @@ -3304,9 +3425,10 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI cgrp = group(proven, syms) if proven else None # 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 + from . import fieldproof + from .fieldproof import ExactSearch, exact_fiber - proof, tried = None, None + proof, tried, early = None, 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 @@ -3328,7 +3450,26 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI 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) + args = (ex, [max(crit) + 3] * len(crit), tried, ex_syms, inputs, consts) + race = quick[2] == floor and fieldproof.exact_fiber is fieldproof.EXACT_FIBER + threads = max(1, int(msolve._MSOLVE_THREADS)) + # in the race the search and the count over Q share the threads + with msolve.msolve_threads(max(1, threads // 2) if race else threads): + # a replaced exact_fiber() runs as it is, without the race + search = ExactSearch(*args) if fieldproof.exact_fiber is fieldproof.EXACT_FIBER else None + if search is None: + proof = fieldproof.exact_fiber(*args) + elif race: + # the count over Q while the exact search runs: an exact result is kept, and where the search ends + # without one, the count is already there + t4 = time.monotonic() + with msolve.msolve_threads(max(1, threads - threads // 2)): + cb0 = count_certificate(quick[0], quick[2], crit) + timing["verified"] = round(time.monotonic() - t4, 2) + if cb0["bound"] is not None: + early = cb0 + if search is not None: + proof = search.result() timing["exact"] = round(time.monotonic() - t3, 2) pinned = verified = None if proof is not None and not proof["exact"]: @@ -3348,6 +3489,7 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI 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 + tw, staged = None, False if proof is not None and proof["exact"]: fib, stable = Fiber(series, [max(crit) + 1] * len(crit), positive), None elif certified: @@ -3356,6 +3498,9 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI 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 + elif (tw := _tower(parts, coords, series, positive, cand, limits, timing)) is not None and tw["complete"]: + # every coordinate pinned by the stages: the fiber at a generic point is the point + fib, stable, cc, staged = Fiber(series, 1, positive), None, 1, True else: if me is None and experiments is not False: # one experiment gave no short count: several experiments come first @@ -3382,6 +3527,9 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI # below twice the orbit of the proven candidates, which divides the size of the fiber k, maps = floor, [] timing["maps"] = 0.0 + elif staged: + k, maps = 1, [] + 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 @@ -3481,6 +3629,7 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI and (tried is None or len(grp) != len(tried)) and not (route is not None and complete) and not series.inputs + and not staged ): t3 = time.monotonic() # the functions the first search proved in the field of the outputs hold for any group @@ -3500,6 +3649,8 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI cb = None if certified: cb = pinned["cert"] + elif staged: + cb = {"bound": tw["bound"], "why": tw["why"], "bits": tw["bits"], "count": 1, "bezout": None} elif k is not None and not (proof and proof["exact"]): t4 = time.monotonic() if route is not None: @@ -3512,9 +3663,28 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI one = count_certificate(fib, k, series.output_orders(2 * len(coords), PRIMES[0])) if one["bound"] is not None: route, cb = None, one + elif early is not None and quick is not None and fib is quick[0]: + # the count over Q of the race with the exact search + cb = early else: cb = count_certificate(fib, k, series.output_orders(2 * len(coords), PRIMES[0])) - timing["verified"] = round(time.monotonic() - t4, 2) + timing["verified"] = round(timing.get("verified", 0.0) + time.monotonic() - t4, 2) + if cb["bound"] is None and k == 1 and route is None and str(cb.get("why")).startswith("no finite count over Q"): + # a count of one modulo the prime without a count over Q: once more with ten times the cap of msolve + t5 = time.monotonic() + with work.caps(msolve_work=10 * work.CAPS["msolve_work"]): + wide = count_certificate(fib, k, series.output_orders(2 * len(coords), PRIMES[0])) + timing["verified_wide"] = round(time.monotonic() - t5, 2) + if wide["bound"] is not None: + cb = wide + else: + limits.append(f"the count over Q with ten times the cap msolve_work: {wide['why']}") + if cb["bound"] is None and k == 1 and tw is None: + # a count of one modulo the prime that the count over Q does not verify: the stages may + tw = _tower(parts, coords, series, positive, cand, limits, timing) + if tw is not None and tw["complete"] and tw["bound"] is not None: + route, staged = None, True + cb = {"bound": tw["bound"], "why": tw["why"], "bits": tw["bits"], "count": 1, "bezout": None} if k is not None and orbit is not None and orbit < k: for c, g in power_coordinates(series).items(): limits.append( @@ -3553,8 +3723,21 @@ def analyze(parts, coords, positive, states, order=None, start=None, points=_POI "candidates": cinfo, "timing": timing, "monodromy": mono, - "certificate": certificate(out, orbit, k, counts, complete, cb, proof, route, _pinned_info(pinned)), + "certificate": certificate( + out, orbit, k, counts, complete, cb, proof, route, _pinned_info(pinned), _tower_info(tw) if staged else None + ), } + if tw is not None: + info["tower"] = _tower_info(tw) + if staged and tw.get("jumps"): + info["certificate"].setdefault("proven", []).append( + "the event times " + + ", ".join(tw["jumps"]) + + " take one value on the fiber: an output coefficient at the start differs before and after the " + "event, so the output is not analytic exactly at the event time (the lemma of the time of an event)" + ) + if staged and tw.get("premise"): + add_premise(info["certificate"], "generic_event_state", _EVENT_PREMISE) if me is not None: info["experiments"] = _route_info(me) if spow: @@ -3615,11 +3798,8 @@ def _start_power_info(info, spow): "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"] + for text in premises: + add_premise(cert, "start_power", text) def _experiments(parts, coords, series, positive, floor, experiments, timing): @@ -3701,6 +3881,63 @@ def _pinned_info(pinned): return out +def _tower(parts, coords, series, positive, cand, limits, timing): + """The result of tower.run() for a model without candidates within the hypotheses of the stage tower, with + "complete" where the stages modulo p pin every coordinate; None where it does not run.""" + from . import tower + + if cand or series.inputs: + return None + t = time.monotonic() + # one unit per segment: the coefficients at the start of a condition, and after an event at a known time + # with the starts not known as new coordinates; a unit outside the hypotheses is left out + units, ext, exact = tower.segment_units(parts, coords, positive) + keep = [u for u in units if tower.applies(u) is None] + if not keep: + return None + out = tower.run(keep, ext, positive, limits, need=range(len(coords)), exact=exact) + out["complete"] = set(range(len(coords))) <= set(out["pinned"]) + out["jumps"] = [coords[i] for i in exact] + timing["tower"] = round(time.monotonic() - t, 2) + return out + + +# a stage after an event draws the states there that are not known with the coordinates +def add_premise(cert, kind, text): + """Adds the premise {"kind", "text"} to certificate["premises"]: the count holds at the stated level where the + premise holds.""" + premises = cert.setdefault("premises", []) + if not any(p["kind"] == kind and p["text"] == text for p in premises): + premises.append({"kind": kind, "text": text}) + + +_EVENT_PREMISE = ( + "the states at an event that the stages after it read and do not know are a generic point for those " + "stages: the test over Q draws them with the coordinates, the model starts from their values" +) + + +def _tower_info(tw): + """The part of the result of tower.run() that the certificate reports.""" + if tw is None: + return None + claims = tw["claims"] + return { + "stages": len(claims), + "orders": sorted({c["order"] for c in claims}), + "pinned_modp": len(tw["pinned"]), + "accepted": len(tw["accepted"]), + "bits": tw["bits"], + "count_bound": tw["bound"], + "largest_system": max((c.get("largest", 0) for c in claims), default=0), + "free_jets": max(((c.get("structure") or {}).get("free_jets", 0) for c in claims), default=0), + "seconds": tw.get("seconds"), + "why": tw["why"], + "jumps": tw.get("jumps") or [], + "premise": bool(tw.get("premise")), + } + + 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") @@ -4019,11 +4256,12 @@ def count_certificate(fib, k, crit, within=None): return out -def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route=None, pinned=None): +def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route=None, pinned=None, tower=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 + count_certificate(), or checked: the count modulo the prime without an error bound. 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 @@ -4062,6 +4300,13 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= return out if pinned is not None: out["pinned"] = pinned + if tower is not None: + out["tower"] = tower + out["proven"].append( + "a coordinate with one value on the points of a system formed from the equations of one condition, the " + "pins of the stages before and a cut at rational values, all in the field of the output coefficients, " + "lies in that field and takes one value on the fiber (the pin by descent of the stage tower)" + ) used = pinned is not None and pinned["count_bound"] is not None and route is None if used: out["proven"].append( @@ -4098,8 +4343,8 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= 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 " + out["unbounded"] = ( + "the number of solutions modulo the prime at a random point stands for 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] @@ -4117,6 +4362,12 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= else "" ) ) + elif tower is not None: + out["bounded"] = ( + f"the {tower['stages']} stages modulo the prime pin every coordinate, and the test over Q at a random " + f"integer point of {tower['bits']} bits accepts every claim, so the fiber at a generic point is the point, " + f"except with probability at most {bound:.3g} (the verified pin of the stage tower)" + ) elif route is not None: n = cb["count"] out["bounded"] = ( @@ -4131,7 +4382,7 @@ def certificate(entries, orbit, k, counts, complete, cb=None, exact=None, route= f"{bound:.3g} (the count over Q at a random integer point)" ) out["complete"] = ( - ("verified" if bound is not None else "axiom") + ("verified" if bound is not None else "checked") if complete else ("no" if k is not None and orbit is not None and orbit < k else "open") ) @@ -4152,6 +4403,34 @@ def observed_states(f, g, events=()): return [x for x in f if x in seen] +def resting_exchange(f, ic, inputs, coords, chart, fixed=(), positive=True): + """{state: resting value} of a condition at rest where the balances have no closed form: the resting values + become coordinates, and coordinates entering the balances linearly are solved in exchange (restchart. + rest_exchange). `chart` is shared by the conditions and filled by the first; a condition with other balances + at rest raises a ValueError.""" + from .restchart import rest_exchange + + zero = {spy.Symbol(u): spy.Integer(0) for u in inputs} + rhs = {spy.Symbol(x): model_sympify(str(e)).xreplace(zero) for x, e in f.items()} + start = {} + for x, e in rhs.items(): + if str(x) in inputs: + start[x] = spy.Integer(0) + elif str(x) in coords: + start[x] = x + elif e == 0: + start[x] = model_sympify(str(ic.get(str(x), x))) + key = {str(x): str(e) for x, e in rhs.items() if x not in start} + if not chart: + R, exch = rest_exchange(rhs, start, sorted(coords), fixed, positive) + chart.update({"balances": key, "rest": R, "exchanged": exch}) + elif chart["balances"] != key: + raise ValueError("discrete() under equilibrate exchanges coordinates only where the conditions rest alike") + out = {str(x): str(v) for x, v in start.items()} + out.update({str(x): str(r) for x, r in chart["rest"].items()}) + return out + + 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 a free resting value, a state without dynamics rests at the initial value, and the others solve the balances over @@ -4182,6 +4461,10 @@ def resting_start(f, ic, inputs, coords): "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" ) + lin = _linear_rest(bal, U) + if lin is not None: + out.update({str(x): str(v) for x, v in lin.items()}) + return out 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: @@ -4218,6 +4501,30 @@ def resting_start(f, ic, inputs, coords): return out +def _linear_rest(bal, U): + """{state: resting value} where every balance has degree at most one in the states `U` and the linear system has + one solution over Q(theta), solved by elimination over that field; None otherwise.""" + from sympy.polys.matrices import DomainMatrix + + polys = [spy.Poly(e, *U) for e in bal] + if len(polys) != len(U) or any(P.total_degree() > 1 for P in polys): + return None + unit = [tuple(int(i == j) for i in range(len(U))) for j in range(len(U))] + A = [[P.coeff_monomial(m) for m in unit] for P in polys] + b = [-P.coeff_monomial((0,) * len(U)) for P in polys] + others = sorted(set().union(*[e.free_symbols for e in bal]) - set(U), key=str) + # a nonzero determinant at one integer point shows it nonzero over Q(theta); a zero there leaves the solver + rng = session.current().rng("linear rest", tuple(map(str, others))) + at = {s: spy.Integer(rng.randint(2, 10**6)) for s in others} + if spy.Matrix(A).xreplace(at).rank() < len(U): + return None + dom = spy.QQ[tuple(others)] if others else spy.QQ + M = DomainMatrix.from_Matrix(spy.Matrix(A)).convert_to(dom) + num, den = M.solve_den(DomainMatrix.from_Matrix(spy.Matrix(b)).convert_to(dom)) + num, den = num.to_Matrix(), dom.to_sympy(den) + return {u: spy.cancel(num[i, 0] / den) for i, u in enumerate(U)} + + 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.""" diff --git a/src/symident/detection/elim.py b/src/symident/detection/elim.py index e4765eb..029b331 100644 --- a/src/symident/detection/elim.py +++ b/src/symident/detection/elim.py @@ -17,9 +17,9 @@ 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`.""" + derivatives of the observables up to `order`, those of `naux` auxiliary observables last.""" - def __init__(self, rel, order): + def __init__(self, rel, order, naux=0): 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] @@ -32,7 +32,7 @@ def __init__(self, rel, order): + [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)] + + [f"si_y{r}_{k}" for r in range(len(rel.y) + naux) 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") @@ -82,24 +82,31 @@ def _deg(P, v): 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) + """The coefficient of variable v to the power k, a polynomial in the others: the k-th derivative in v at v = 0 + over k!, formed by flint without the terms as Python objects.""" + D = P + for _ in range(k): + D = D.derivative(v) + if _deg(D, v) > 0: + D = D.subs({P.context().names()[v]: 0}) + return D // math.factorial(k) if k > 1 else D + + +# the most terms of a polynomial the elimination factors +_FACTOR_TERMS = 200 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): + def __init__(self, rel, rng, terms=math.inf, saturate=False): 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] + # auxiliary observables [(r, j, N, D)]: the j-th Lie derivative N / D of observable r + self.aux = saturation(rel, _Ring(rel, ns + 1), self.p, rng) if saturate else [] + top = max((j for _, j, _, _ in self.aux), default=0) + self.R = R = _Ring(rel, ns + 1 + top, len(self.aux)) 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 = {} @@ -116,9 +123,14 @@ def __init__(self, rel, rng, terms=math.inf): for r, q in enumerate(rel.y): M, E = R.parts(q) self.y_eqs[r] = E * R.y(r, 0) - M + for i, (_, _, N, D) in enumerate(self.aux): + r = len(rel.y) + i + self.y_eqs[r] = _lift(D, R.ctx) * R.y(r, 0) - _lift(N, R.ctx) self.steps = [] # per state eliminated, (A, B) with A x + B = 0 along every trajectory, or None self.states = {} + # the states replaced by x + B / A in change() + self.changed = set() def _points(self): """Values of every variable at the start of trajectories at random coordinates modulo p.""" @@ -130,7 +142,7 @@ def _points(self): 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) + got = ioproj.trajectory(rel, vals, p, R.order + 2 + max((j for _, j, _, _ in self.aux), default=0)) if got is None: continue obs, states = got @@ -146,6 +158,9 @@ def _points(self): 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 + for i, (r, j, _, _) in enumerate(self.aux): + for k in range(R.order + 1): + pt[R.at[f"si_y{len(rel.y) + i}_{k}"]] = int(obs[r][j + k]) * math.factorial(j + k) % p out.append(pt) return out @@ -169,7 +184,7 @@ def derive(self, P): 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 r in range(len(self.rel.y) + len(self.aux)): for k in range(R.order + 1): v = R.at[f"si_y{r}_{k}"] if _deg(P, v) > 0: @@ -184,8 +199,8 @@ 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(): + self._within(f, g) if _deg(f, v) > _deg(g, v): f, g = g, f df, dg = _deg(f, v), _deg(g, v) @@ -212,7 +227,7 @@ def eliminate(self, f, g, v): d = math.gcd(*exps) if d > 1: f, g = (_deflate(P, v, d) for P in (f, g)) - res, extra = _resultant(f, g, v) + res, extra = _resultant(f, g, v, self.terms) return self.keep(res, extra) return self.keep(res) @@ -225,7 +240,8 @@ def keep(self, P, extra=()): self._within(P, *extra) facs = [] for Q in [P] + list(extra): - for F, _ in Q.factor()[1]: + # past _FACTOR_TERMS the polynomial is kept whole: it vanishes along every trajectory as well + for F in [F for F, _ in Q.factor()[1]] if len(Q) <= _FACTOR_TERMS else [Q]: 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)] @@ -270,16 +286,94 @@ def run(self): ) v = cand[0][2] vi = R.at[f"si_x{v}"] + if len(self.y_eqs) < 3 and _deg(self.y_eqs[r], vi) == 1: + nxt = self.change(r, v, nxt) 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) + # a state changed by change() has no relation of the start + self.states[v] = None if v in self.changed else 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 change(self, r, v, nxt): + """The change of variables of StructuralIdentifiability.jl before the state v leaves the equation of + observable r, linear in v: where the coefficient of v is A x + B in another state x, with A free of the + states and B nonzero, x becomes x + B / A in every equation and test point, and x' becomes x' + (B / A)'. + Returns the prolonged equation `nxt` in the new variables.""" + R = self.R + AyB = _coeff(self.y_eqs[r], R.at[f"si_x{v}"], 1) + states = {R.at[f"si_x{j}"] for j in self.x_eqs} | {R.at[f"si_d{j}"] for j in self.x_eqs} + for x in self.x_eqs: + xi = R.at[f"si_x{x}"] + if x == v or _deg(AyB, xi) != 1: + continue + A, B = _coeff(AyB, xi, 1), _coeff(AyB, xi, 0) + h = A.gcd(B) + A, B = A // h, B // h + if B.is_zero() or any(_deg(A, s_) > 0 for s_ in states): + continue + try: + dA, dB = self.derive(A), self.derive(B) + except ValueError: + continue + nd, dd = A * dB - dA * B, A * A + h = nd.gcd(dd) + nd, dd = nd // h, dd // h + pts = [] + for pt in self.points: + a, d = self.value(A, pt), self.value(dd, pt) + if not a or not d: + break + q = list(pt) + q[xi] = (pt[xi] + self.value(B, pt) * pow(a, -1, self.p)) % self.p + di = R.at[f"si_d{x}"] + q[di] = (pt[di] + self.value(nd, pt) * pow(d, -1, self.p)) % self.p + pts.append(q) + if len(pts) != len(self.points): + continue + self.points = pts + di = R.at[f"si_d{x}"] + # x' -> x' - (B / A)', then x -> x - B / A, each over the denominator + self.x_eqs[x] = _subst(self.x_eqs[x], di, dd * R.gens[di] - nd, dd) + sub = (A * R.gens[xi] - B, A) + self.x_eqs = {j: _subst(eq, xi, *sub) for j, eq in self.x_eqs.items()} + self.y_eqs = {j: _subst(eq, xi, *sub) for j, eq in self.y_eqs.items()} + nxt = _subst(nxt, xi, *sub) + for xx in list(self.x_eqs): + if xx != x: + self.x_eqs[x] = self.eliminate(self.x_eqs[x], self.x_eqs[xx], R.at[f"si_d{xx}"]) + self.changed.add(x) + break + return nxt + + def restore(self, R): + """The map of a polynomial of this ring into the ring R without the auxiliary observables: the k-th derivative + of the auxiliary observable of (r, j) becomes the (j + k)-th of observable r.""" + S, ny = self.R, len(self.rel.y) + to = {} + for i, (r, j, _, _) in enumerate(self.aux): + for k in range(S.order + 1): + to[S.at[f"si_y{ny + i}_{k}"]] = R.at[f"si_y{r}_{j + k}"] if j + k <= R.order else None + n = len(R.names) + + def back(P): + out = {} + for m, c in P.to_dict().items(): + e = list(m[:n]) + for v, w in to.items(): + if m[v]: + if w is None: + raise ValueError("an auxiliary observable past the order of the ring") + e[w] += m[v] + out[tuple(e)] = out.get(tuple(e), 0) + c + return R.ctx.from_dict(out) + + return back + 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.""" @@ -291,12 +385,170 @@ def linear(self, f, g, 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) + pair = _subresultant1(f, g, v, self.terms) 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 +# the most degree in the states and the most total degree of an auxiliary observable, as in +# StructuralIdentifiability.jl (saturate_outputs) +_AUX_DEGREE = (3, 10) + + +def _lift(P, ctx): + """P, a polynomial in the coordinates and the states, in the ring `ctx` whose first variables are those of P.""" + n = len(ctx.names()) + return ctx.from_dict({tuple(m) + (0,) * (n - len(m)): c for m, c in P.to_dict().items()}) + + +def saturation_orders(rel, R): + """{observable: order}: two plus the most steps along the graph of the states read until a step reaches more + states whose right-hand side reads a known state, zero where none does (propose_orders of + StructuralIdentifiability.jl).""" + reads, with_u = {}, set() + for j in R.unknown: + N, D = R.parts(rel.f[j]) + used = {v for P in (N, D) for m in P.monoms() for v, k in enumerate(m) if k} + reads[j] = {i for i in R.unknown if R.at[f"si_x{i}"] in used} + if any(R.at[f"si_u{i}"] in used for i in R.known): + with_u.add(j) + out = {} + for r, q in enumerate(rel.y): + M, E = R.parts(q) + used = {v for P in (M, E) for m in P.monoms() for v, k in enumerate(m) if k} + cur = {i for i in R.unknown if R.at[f"si_x{i}"] in used} + reached = len(cur & with_u) + out[r] = 2 if reached else 0 + step = 1 + while True: + new = cur.union(*(reads[i] for i in cur)) + if new == cur: + break + cur = new + if len(cur & with_u) > reached: + out[r] = step + 2 + reached = len(cur & with_u) + step += 1 + return out + + +def saturation(rel, R, p, rng, split=()): + """[(r, j, N, D)]: Lie derivatives N / D of the observables, in R, algebraically independent of the observables + and of each other over the coordinates and the known states, fewest degree and terms first (saturate_outputs of + StructuralIdentifiability.jl); empty without known states. Each is the j-th derivative of observable r along + every trajectory, or with `split`, known states, a coefficient in these of one.""" + if not R.known: + return [] + xs = [R.at[f"si_x{j}"] for j in R.unknown] + one = R.ctx.from_dict({(0,) * len(R.names): 1}) + Q, rhs = one, {} + for j in R.unknown: + N, D = R.parts(rel.f[j]) + rhs[R.at[f"si_x{j}"]] = (N, D) + Q = Q * D // Q.gcd(D) + for j in R.known: + N, D = R.parts(rel.f[j]) + if not D.is_constant(): + return [] + rhs[R.at[f"si_u{j}"]] = (N, D) + Q = Q * D // Q.gcd(D) + cut = {R.at[f"si_u{j}"] for j in getattr(rel, "cut", ())} + F = {v: N * (Q // D) for v, (N, D) in rhs.items()} + + def flow(P): + out = R.ctx.from_dict({}) + for v, f in F.items(): + if _deg(P, v) > 0: + out += P.derivative(R.names[v]) * f + return out + + def x_degree(P): + return max((sum(m[v] for v in xs) for m in P.monoms()), default=0) + + pt = [rng.randrange(1, p) for _ in R.names] + + def grad(N, D): + n, d = int(N(*pt)) % p, int(D(*pt)) % p + if not d: + return None + inv = pow(d, -2, p) + return [(int(N.derivative(R.names[v])(*pt)) * d - n * int(D.derivative(R.names[v])(*pt))) * inv % p for v in xs] + + basis = [] + + def raises(g): + g = list(g) + for piv, row in basis: + if g[piv]: + c = g[piv] + g = [(a - c * b) % p for a, b in zip(g, row)] + piv = next((i for i, a in enumerate(g) if a), None) + if piv is None: + return False + inv = pow(g[piv], -1, p) + basis.append((piv, [a * inv % p for a in g])) + return True + + us = [R.at[f"si_u{j}"] for j in split] + + def pieces(N, D): + """N / D, or with `split` the coefficients of N in the known states over D where D reads none.""" + if not us or any(_deg(D, v) > 0 for v in us): + return [(N, D)] + out = {} + for m, c in N.to_dict().items(): + key = tuple(m[v] for v in us) + e = list(m) + for v in us: + e[v] = 0 + out.setdefault(key, {})[tuple(e)] = c + return [(R.ctx.from_dict(d), D) for d in out.values()] + + cands = [] + orders = saturation_orders(rel, R) + for r, q in enumerate(rel.y): + N, D = R.parts(q) + g = grad(N, D) + if g is not None: + raises(g) + cur = [(N, D)] + for j in range(1, orders[r] + 1): + nxt = [] + for N0, D0 in cur: + if any(_deg(P, v) > 0 for P in (N0, D0) for v in cut): + continue + N1, D1 = flow(N0) * D0 - N0 * flow(D0), Q * D0 * D0 + h = N1.gcd(D1) + for N, D in pieces(N1 // h, D1 // h): + h = N.gcd(D) + N, D = N // h, D // h + if N.is_constant() and D.is_constant(): + continue + nxt.append((N, D)) + deg = max(N.total_degree(), D.total_degree()) + if max(x_degree(N), x_degree(D)) <= _AUX_DEGREE[0] and deg <= _AUX_DEGREE[1]: + cands.append((deg, len(N) + len(D), r, j, N, D)) + cur = nxt if us else [(N, D) for N, D in nxt[:1] if max(x_degree(N), x_degree(D)) <= _AUX_DEGREE[0]] + out = [] + for _, _, r, j, N, D in sorted(cands, key=lambda c: c[:4]): + g = grad(N, D) + if g is not None and raises(g): + out.append((r, j, N, D)) + return out + + +def _subst(P, v, num, den): + """P with the variable v replaced by num / den, times den^(degree of P in v): sum_k c_k num^k den^(d - k).""" + cs = _coeffs(P, v) + d = len(cs) - 1 + out = P.context().from_dict({}) + for k, c in enumerate(cs): + if not c.is_zero(): + out += c * num**k * den ** (d - k) + return out + + def _deflate(P, v, d): """P(v^(1/d)) for a polynomial in v^d.""" out = {} @@ -309,20 +561,14 @@ def _deflate(P, v, d): 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] + return [_coeff(P, v, k) for k in range(_deg(P, v) + 1)] -def _resultant(f, g, v): +def _resultant(f, g, v, cap=math.inf): """(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.""" + times their product is the resultant times a power of a leading coefficient, as in StructuralIdentifiability.jl. + A ValueError where a minor has more than `cap` terms.""" if _deg(f, v) > _deg(g, v): f, g = g, f df, dg = _deg(f, v), _deg(g, v) @@ -359,11 +605,12 @@ def _resultant(f, g, v): for i, j in nz: M[i][j] = M[i][j] // h removed.append(h) - return _det(M), removed + return _det(M, cap), 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.""" +def _subresultant1(f, g, v, cap=math.inf): + """(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; a + ValueError where a minor has more than `cap` terms.""" m, n = _deg(f, v), _deg(g, v) cf, cg = _coeffs(f, v), _coeffs(g, v) zero = f.context().from_dict({}) @@ -379,14 +626,16 @@ def entry(row, power): 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])) + out.append(_det([[entry(row, q) for q in powers] for row in rows], cap)) return out[0], out[1] -def _det(M): - """The determinant by expansion along the rows, the minors cached.""" +def _det(M, cap=math.inf): + """The determinant by expansion along the rows, the minors cached; a ValueError where a product in it or the + cached minors together have more than `cap` terms.""" n = len(M) cache = {} + held = [0] one = M[0][0].context().from_dict({(0,) * M[0][0].context().nvars(): 1}) def minor(row, cols): @@ -403,9 +652,12 @@ def minor(row, cols): 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 + if len(t) > cap or held[0] + len(out) > cap: + raise ValueError(f"minors of more than {int(cap):,} terms, the cap elimination_terms") sign = -sign out = out if out is not None else one - one cache[key] = out + held[0] += len(out) return out return minor(0, 0) @@ -524,4 +776,10 @@ def eliminate_relations(rel, rng, terms=math.inf): "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} + if not el.aux: + return {"relations": eqs, "orders": orders, "ring": el.R, "steps": el.steps, "states": el.states} + R = _Ring(rel, el.R.order) + back = el.restore(R) + eqs = {r: back(P) for r, P in eqs.items()} + states = {j: None if ab is None else tuple(back(P) for P in ab) for j, ab in el.states.items()} + return {"relations": eqs, "orders": orders, "ring": R, "steps": el.steps, "states": states} diff --git a/src/symident/detection/fewcoef.py b/src/symident/detection/fewcoef.py index 2f6e027..92b4330 100644 --- a/src/symident/detection/fewcoef.py +++ b/src/symident/detection/fewcoef.py @@ -109,58 +109,56 @@ 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) + entries = list(entries) + alive = set(entries) + rg, gr, other = {e: [] for e in entries}, {e: [] for e in entries}, 0 + for v, (ts, vals) in enumerate(lines): + den = vals[:, r0] + if not den.all(): + alive = set() + break + cols = [e for e in entries if e in alive] + inv = np.array([pow(int(d), -1, p) for d in den], dtype=np.int64) + W = vals[:, cols] % p * inv[:, None] % p + for e, got in zip(cols, ioproj.ratrec_columns(ts, W, p)): if got is None: - break + alive.discard(e) + continue 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 a is None or not nz: + other += a is None + alive.discard(e) + continue + rg[e].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] + t0 = beta[v] 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 + gr[e].append((dN * t0 - a * N) * pow(pow(t0, a + 1, p), -1, p) % p) + out = {e: rg[e] for e in entries if e in alive} + grads = {e: gr[e] for e in out} 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 + """The first entry, least degree first, whose coefficient is a monomial in the parameters: 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) + polynomial there; [] where none of the eight of least degree is.""" + tot = dict.fromkeys(range(r), 0) + for ts, vals in lines: + for e, got in zip(range(r), ioproj.ratrec_columns(ts, vals, 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]: + if e in tot and a is None: + del tot[e] + elif e in tot: + tot[e] += a + for e in sorted(tot, key=lambda e: (tot[e], e))[:8]: found, other = _ranges(lines, p, e, range(r)) if not other and len(found) > 1: - out.append((e, found)) - return out + return [(e, found)] + return [] class _BT: @@ -298,13 +296,13 @@ def __init__(self, pr): funcs = pr.base.funcs def deg(P): - return max((sum(m) for m in P.itermonoms()), default=0) + return max((int(sum(m)) for m in P.monoms()), 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()] + dens = [int(c.denominator) for c in P.coeffs()] 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()))) + return math.log2(max(1, sum(abs(int(c.numerator) * (L // int(c.denominator))) for c in P.coeffs()))) dN = [deg(f.numer) for f in funcs] hN = [height(f.numer) for f in funcs] diff --git a/src/symident/detection/fieldproof.py b/src/symident/detection/fieldproof.py index a5f0d50..c0681e9 100644 --- a/src/symident/detection/fieldproof.py +++ b/src/symident/detection/fieldproof.py @@ -6,7 +6,9 @@ import pickle import random import re +import subprocess import sys +import threading import time from fractions import Fraction @@ -1051,8 +1053,8 @@ def _covers(a, b): 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) + base = ioproj.Base(rel, ms) + mons = _monomials(base.nb, degree) return (base, _parents(mons)), mons @@ -1099,22 +1101,22 @@ def _ring_coeffs(rel, syms, lam): 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} + return {j: J.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 + return ioproj.combine(J, list(co.values()), [phis[j] for j in co])[0].is_zero() -def _phis(rel, ms, degree, extra=()): +def _phis(rel, ms, degree, extra=(), stop=None): """The monomials phi in the base functions as ioproj.Quo, then each state of `extra` times those of one degree - less.""" + less; ioproj.JetTooLargeError where the clock of the search passes `stop` while they are formed.""" J = ioproj.jets_of(rel) base = _base(rel, ms) - phis = ioproj.products(J, base, _monomials(len(base), degree)) + phis = ioproj.products(J, base, _monomials(len(base), degree), stop) 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] @@ -1158,7 +1160,7 @@ def state_relation(series, syms, coord, rng, stop, cap=None): continue jets = _compiled(rel, ms, degree) nmon = len(jets[1]) - nlow = math.comb(len(_base(rel, ms)) + degree - 1, degree - 1) + nlow = math.comb(ioproj.Base(rel, ms).nb + 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 @@ -1184,13 +1186,16 @@ def values(xp, p, piv=piv, free=free, jets=jets, col=col, ext=ext, nmon=nmon, nl lam = {free[col]: spy.Integer(1)} lam.update(zip(piv, exprs)) J = ioproj.jets_of(rel) - phis = _phis(rel, ms, degree, [i]) + try: + phis = _phis(rel, ms, degree, [i], stop) + except ioproj.JetTooLargeError: + continue # 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] + J, list(mu.values()), [ioproj.Quo(J.exquo(phis[j].numer, J.X[i]), phis[j].exps) for j in mu] ) - if den == 0 or not _identity(rel, syms, lam, phis): + if den.is_zero() or not _identity(rel, syms, lam, phis): continue # and not zero at the start of the trajectory, with the factors of the denominator start = { @@ -1198,7 +1203,7 @@ def values(xp, p, piv=piv, free=free, jets=jets, col=col, ext=ext, nmon=nmon, nl 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]): + if any(spy.cancel(J.as_expr(P).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()]), @@ -1255,7 +1260,11 @@ def values(xp, p, piv=piv, free=free, jets=jets, nmon=nmon): exprs = _rebuild(inter, [syms[k] for k in idx]) if exprs is None: continue - phis = _phis(rel, ms, degree) + try: + phis = _phis(rel, ms, degree, stop=stop) + except ioproj.JetTooLargeError: + log.append(f"relations at orders {ms}, degree {degree}: products past the cap") + continue # 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) @@ -1350,12 +1359,71 @@ def projection_functions(series, syms, rng, stop, log, found=None): yield new +def free_inputs(rel): + """The known states that are jets of a known input without assumed form: a chain of known states, each the + derivative of the one before, that ends in a jet cut.""" + out = [] + for j in rel.known: + k, seen = j, set() + while k not in rel.cut and k not in seen: + seen.add(k) + nxt = [i for i in rel.known if rel.f[k] == rel.X[i]] + if not nxt: + break + k = nxt[0] + if k in rel.cut: + out.append(j) + return out + + +def saturated(rel): + """`rel` with auxiliary observables (elim.saturation()): the coefficients in the jets of the known inputs without + assumed form of Lie derivatives of the observables. These lie in the field of the observables and the inputs for a + generic course of the inputs; taken only where every start of a state is a separate coordinate.""" + from . import elim + + free = free_inputs(rel) + seg = rel.part["segs"][0] + starts = [seg["x0"][j][0] for j in range(rel.ns) if rel.X[j] is not None and j not in rel.known] + if not free or not all(isinstance(x, spy.Symbol) for x in starts) or len(set(starts)) != len(starts): + return rel + # a start must be a coordinate that no right-hand side and no observable reads + pars = [str(p) for p in rel.series.params] + eqs = [seg["F"][j] for j in range(rel.ns) if rel.f[j] is not None] + list(seg["G"]) + read = {pars[i - rel.ns] for N, D in eqs for P in (N, D) for m in P for i, e in enumerate(m) if e and i >= rel.ns} + if read & {str(x) for x in starts}: + return rel + R = elim._Ring(rel, 1) + aux = elim.saturation(rel, R, all_primes()[0], random.Random(0), split=free) + if not aux: + return rel + inv = {v: g for g, v in R.map.items()} + gens = rel.R.gens + + def back(P): + out = rel.R.zero + for m, c in P.to_dict().items(): + t = rel.R(int(c)) + for v, k in enumerate(m): + if k: + t = t * gens[inv[v]] ** int(k) + out = out + t + return out + + new = rel.__class__.__new__(rel.__class__) + new.__dict__ = {k: v for k, v in rel.__dict__.items() if not k.startswith("_")} + one = R.ctx.from_dict({(0,) * len(R.names): 1}) + new.y = list(rel.y) + [back(N) if D == one else back(N) / back(D) for _, _, N, D in aux] + new.observed = list(rel.observed) + return 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) + rel = saturated(_relations(series, syms)) try: got = elim.eliminate_relations(rel, random.Random(seed), terms) except ValueError as exc: @@ -1407,7 +1475,8 @@ def elimination_functions(series, syms, rng, stop, log, found=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"]) + srel = saturated(rel) + R = elim._Ring(srel, got["order"]) _elimination_states(rel, R, got.get("states") or {}) p0 = all_primes()[0] gens = [spy.Symbol(n) for n in R.params] @@ -1417,13 +1486,13 @@ def expr(co): for obs, d in got["relations"].items(): P = R.ctx.from_dict(d) - built = elim.relation_projection(rel, R, P) + built = elim.relation_projection(srel, 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) + rk = ioproj.series_rank(srel, pr, support, syms, rng, p0) if rk != len(support) - 1: log.append(f"{where}: rank {rk} of {len(support)} terms along the trajectory") continue @@ -1593,47 +1662,72 @@ def exact_fiber(series, orders, grp, syms, inputs=(), known=(), pre=()): 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), + return ExactSearch(series, orders, grp, syms, inputs, known, pre).result() + + +# the exact_fiber() of the package; discrete.analyze() races it with the count over Q only where it is this one +EXACT_FIBER = exact_fiber + + +class ExactSearch: + """The search of exact_fiber() in a separate process, started at once; result() waits for it.""" + + def __init__(self, series, orders, grp, syms, inputs=(), known=(), pre=()): + self.t0 = time.monotonic() + self.out = {"exact": False, "why": None, "generators": [], "seconds": 0.0} + self.proc = self.thread = None + self.got = None + if len(grp) > _GROUP: + self.out["why"] = f"the group of the exact maps has more than {_GROUP} elements" + return + 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): + self.out["why"] = "the model holds constants that are no coordinates, taken at drawn values" + return + 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 + self.proc = subprocess.Popen( + [sys.executable, "-c", "from symident.detection.fieldproof import _child; _child()"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, ) - 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 + self.thread = threading.Thread(target=self._talk, args=(payload,), daemon=True) + self.thread.start() + + def _talk(self, payload): + try: + stdout, _ = self.proc.communicate(payload) + self.got = pickle.loads(stdout) if self.proc.returncode == 0 and stdout else None + except (pickle.UnpicklingError, EOFError, OSError, ValueError): + self.got = None + + def result(self): + if self.thread is not None: + self.thread.join() + if self.got is not None: + self.out = self.got + elif self.out["why"] is None: + self.out["why"] = "the search failed" + self.out["seconds"] = round(time.monotonic() - self.t0, 2) + return self.out def _child(): @@ -1699,13 +1793,18 @@ def _search(series, orders, grp, syms, cap, inputs, rng, known=(), pre=()): out["relations"], out["io_functions"] = log, [] found = set() + rel = _relations(series, syms) + early = rel.ok and saturated(rel) is not rel + def relations(end): # the small dense configurations, the projections, the relations by elimination, the large dense - # configurations + # configurations; the elimination before the projections where saturated relations keep it small + first = [elimination_functions(series, syms, rng, end, log, found)] if early else [] return itertools.chain( io_functions(series, syms, rng, min(end, work.ticks() + _DENSE * cap), log, cap=_FIRST, found=found), + *first, projection_functions(series, syms, rng, end, log, found), - elimination_functions(series, syms, rng, end, log, found), + *([] if early else [elimination_functions(series, syms, rng, end, log, found)]), io_functions(series, syms, rng, end, log, floor=_FIRST, found=found), ) diff --git a/src/symident/detection/fields.py b/src/symident/detection/fields.py index 7b0f510..9c65182 100644 --- a/src/symident/detection/fields.py +++ b/src/symident/detection/fields.py @@ -938,9 +938,9 @@ def event_space(V, evi, evm, fixed, n_states, p): def _sz_term(deg, n_cols, K, draws=None, rest=1): """Schwartz-Zippel numerator of a block: per segment the closure stop and a maximal minor per order up to K, each - composed with the start of degree d0, times the Bezout number of a resting variety, plus the parameters off its - component; each term times the points drawn for its random point, `draws` per segment stop and generic point, - `rest` for the resting point. None without degrees.""" + composed with the start of degree d0, times the Bezout number of a resting variety, plus the parameters off the + component; each term times the points drawn for the random point of the term, `draws` per segment stop and + generic point, `rest` for the resting point. None without degrees.""" if deg is None: return None if not isinstance(deg, dict): @@ -1091,7 +1091,7 @@ def values(): break V = np.asarray(rr["R"], dtype=np.int64).reshape(int(rr["rank"]), n_states) Vs.append(V.copy()) - # the point that ends U is the accepted one of its draws + # the point that ends U is the accepted one of the draws of U stops.append(n_drawn) # a uniform point of the set: random coordinates, and per segment a random shift of the start lv_g, Qg, n_gen = values() diff --git a/src/symident/detection/gauge.py b/src/symident/detection/gauge.py index edc66e9..829dd36 100644 --- a/src/symident/detection/gauge.py +++ b/src/symident/detection/gauge.py @@ -207,7 +207,7 @@ def split(s): s2 = symmetry_detection(**a2) res["symmetries"] = scal + s2["symmetries"] res["info"]["verification"] = s2["info"].get("verification") - # the second pass reconstructs the general directions: its proofs, attempts and bound + # the second pass reconstructs the general directions: the proofs, attempts and bound of the pass res["info"]["attempts"] = s2["info"].get("attempts") or [] res["info"]["proof"] = list(s1info.get("proof") or []) + list(s2["info"].get("proof") or []) res["info"]["bound"] = _joint_bound(s1info.get("bound"), s2["info"].get("bound")) diff --git a/src/symident/detection/hybrid.py b/src/symident/detection/hybrid.py index 8415c36..9cd2aa2 100644 --- a/src/symident/detection/hybrid.py +++ b/src/symident/detection/hybrid.py @@ -176,7 +176,7 @@ def _check_unknown(self): if shared: raise HybridError( f"the unknown input {shared[0]} enters several conditions; with switches each " - "condition needs an input of its own, renamed in `conditions`" + "condition needs a separate input, renamed in `conditions`" ) def _conditions(self): diff --git a/src/symident/detection/ioproj.py b/src/symident/detection/ioproj.py index e4490eb..3684a08 100644 --- a/src/symident/detection/ioproj.py +++ b/src/symident/detection/ioproj.py @@ -9,6 +9,7 @@ import tempfile from fractions import Fraction +import flint import numpy as np import sympy as spy @@ -26,6 +27,26 @@ _DENSE = 1500 # the most terms of a derivative whose next derivative a profile reads _JET = 5000 +# the term products of one product in the jets of the observables +_JET_PRODUCTS = _JET**2 + + +class JetTooLargeError(ValueError): + """A product in the jets of the observables past _JET_PRODUCTS term products.""" + + +def _mul(*ps): + """The product of the polynomials `ps`; JetTooLargeError before a product of more term products than + _JET_PRODUCTS. The term products count on the clock of the searches (work.tick()).""" + out = ps[0] + for q in ps[1:]: + if len(out) * len(q) > _JET_PRODUCTS: + raise JetTooLargeError(_JET_PRODUCTS) + work.tick(len(out) * len(q)) + out = out * q + return out + + # the largest total degree of a projection tried _DEGREE = 14 # the most candidate monomials of a projection taken from bounds on the Newton polytope @@ -93,18 +114,21 @@ class Jets: 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) + # the arithmetic of the jets runs in FLINT; the relations of `rel` are read once + self.R = flint.fmpq_mpoly_ctx.get(tuple(rel.names), "degrevlex") + self.zero, self.one = self.R.from_dict({}), self.R.constant(1) + gens = list(self.R.gens()) self.X = [None if x is None else gens[rel.names.index(str(x))] for x in rel.X] + self._index = {id(g): k for k, g in enumerate(gens)} 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) + n, d = (q.numer, q.denom) if hasattr(q, "numer") else (q, None) + n = self.from_sympy(n) + d = self.one if d is None else self.from_sympy(d) + c = d.leading_coefficient() + if d.is_constant(): + return n * (1 / c), None + return n * (1 / c), d * (1 / c) self._parts = parts fs = [None if f is None else parts(f) for f in rel.f] @@ -112,7 +136,7 @@ def parts(q): 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 + Q = self.one for d in dens: Q = Q * d self.Fh = [] @@ -127,18 +151,56 @@ def parts(q): 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._Qt = None self.fac = [] if self.Q is None else [self.Q] self._obs = {} + def from_sympy(self, P): + """A polynomial of a SymPy ring over the names of the relations, in the FLINT context of the jets.""" + return self.R.from_dict({m: flint.fmpq(int(c.numerator), int(c.denominator)) for m, c in P.terms()}) + + def from_expr(self, e): + """A SymPy polynomial expression in the names of the relations, in the FLINT context of the jets.""" + syms = [spy.Symbol(n) for n in self.rel.names] + P = spy.Poly(spy.expand(e), *syms) + return self.R.from_dict({m: flint.fmpq(int(spy.fraction(c)[0]), int(spy.fraction(c)[1])) for m, c in P.terms()}) + + def as_expr(self, P): + """The polynomial P as a SymPy expression in the names of the relations.""" + syms = [spy.Symbol(n) for n in self.rel.names] + return spy.Add( + *[ + spy.Rational(int(c.numerator), int(c.denominator)) * spy.Mul(*[s_ ** int(e) for s_, e in zip(syms, m)]) + for m, c in P.terms() + ] + ) + + def exquo(self, a, b): + """a / b for a polynomial b that divides a.""" + q, r = divmod(a, b) + if not r.is_zero(): + raise ValueError("the division is not exact") + return q + + def diff(self, P, g): + """The derivative of P in the variable `g`, a generator of the context or the index of one.""" + return P.derivative(g if isinstance(g, int) else self._index[id(g)]) + + @property + def Qt(self): + """Q~ of the common denominator, formed where a derivative needs it.""" + if self._Qt is None and self.Q is not None: + self._Qt = self.tilde(self.Q) + return self._Qt + 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): + out = self.zero + for k, (x, F) in enumerate(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 + d = P.derivative(self.rel.names.index(str(self.rel.X[k]))) + if not d.is_zero(): + out = out + _mul(d, F) return out def _factor(self, E): @@ -153,7 +215,8 @@ def observable(self, r, m): 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)] + # y = M / E: the derivative of order 0 is M over E^1 + self._obs[key] = [[(M, 0, 0 if E is None else 1)], 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: @@ -162,20 +225,28 @@ def observable(self, r, m): 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)) + lst.append((_mul(Nt, E) - _mul(N, Et) * b if b else _mul(Nt, E), 0, b + 1)) elif E is None: - lst.append((Nt * self.Q - N * self.Qt * a, a + 2, 0)) + # Q~ is formed only where the factor a is not zero + lst.append((_mul(Nt, self.Q) - _mul(N, self.Qt) * a if a else _mul(Nt, self.Q), a + 2, 0)) else: - lst.append((Nt * self.Q * E - N * (self.Qt * E * a + Et * self.Q * b), a + 2, b + 1)) + rest = (_mul(self.Qt, E) * a if a else self.zero) + (_mul(Et, self.Q) * b if b else self.zero) + lst.append((_mul(Nt, self.Q, E) - _mul(N, rest), 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 + terms, computed up to the first that has more, and the derivatives of order ms[r] within _JET_PRODUCTS term + products of each product.""" + try: + 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 + if m >= 0: + self.observable(r, m) + except JetTooLargeError: + return False return True def quo(self, N, a=0, ie=None, b=0): @@ -190,7 +261,7 @@ def state(self, k): return Quo(self.X[k], []) def denom(self, q): - out = self.R.one + out = self.one for k, e in q.exps: out = out * self.fac[k] ** e return out @@ -204,29 +275,68 @@ def jets_of(rel): class Base: - """The base functions of a projection, Quo over the factors of their Jets, evaluated together at many points - modulo p.""" + """The base functions of a projection: the derivatives of observable r up to order ms[r], the input states read + and the state `extra`. Their values at many points modulo p come from the Taylor coefficients of the trajectories + that start there, in C++ (_lie_terms()); `funcs`, the same functions as Quo over the factors of the Jets, is + formed only where an identity over Q needs them.""" - def __init__(self, rel, funcs): + def __init__(self, rel, ms, extra=None): + self.rel, self.ms, self.extra = rel, list(ms), extra 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) + self.inputs = rel.inputs(max(self.ms)) + self.nb = sum(m + 1 for m in self.ms if m >= 0) + len(self.inputs) + (extra is not None) + self._funcs = None + + @property + def funcs(self): + if self._funcs is None: + J = self.J + self._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 self.inputs + ] + if self.extra is not None: + self._funcs.append(J.state(self.extra)) + return self._funcs 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 + rel, names = self.rel, self.rel.names + pts = np.ascontiguousarray(pts, dtype=np.int64) % p + cols = [] + ok = np.ones(len(pts), dtype=bool) + m = max(self.ms) + if m >= 0: + exps, coef, off, states = _lie_terms(rel, p) + L = _core.io_lie_values(exps, coef, off, states, pts, m, p, _threads()) + ok = L[:, 0] >= 0 if len(L) else ok + for r, mr in enumerate(self.ms): + if mr >= 0: + cols.append(L[:, r * (m + 1) : r * (m + 1) + mr + 1]) + for k in self.inputs + ([self.extra] if self.extra is not None else []): + cols.append(pts[:, [names.index(str(rel.X[k]))]]) + V = np.hstack(cols) if cols else np.zeros((len(pts), 0), dtype=np.int64) + return ok, V[ok] + + +def _lie_terms(rel, p): + """The term layout of io_lie_values() for the relations `rel` modulo p: the right-hand sides F_s of the states + kept over their common denominator Q, then M_r, E_r of each observable; built once per prime and number of + observables.""" + J = jets_of(rel) + key = (p, len(rel.y)) + cache = rel.__dict__.setdefault("_lie_terms", {}) + if key not in cache: + kept = [j for j in range(rel.ns) if J.X[j] is not None] + polys = [J.Fh[j] for j in kept] + [J.Q if J.Q is not None else J.one] + for y in rel.y: + M, E = J._parts(y) + polys += [M, E if E is not None else J.one] + P = _Polys(polys, len(rel.names)) + coef = np.array([a % p * pow(b, -1, p) % p for a, b in P.coefs], dtype=np.int64) + states = np.array([rel.names.index(str(rel.X[j])) for j in kept], dtype=np.int32) + cache[key] = (P.exps, coef, P.off, states) + return cache[key] def _monomials(nb, degree, top=None, cap_top=None): @@ -276,14 +386,10 @@ class Projection: def __init__(self, rel, ms, pos, rng, top=None, extra=None): self.rel, self.ms, self.pos, self.rng = rel, list(ms), list(pos), rng - J = jets_of(rel) - funcs = [q for r, m in enumerate(self.ms) if m >= 0 for q in J.observable(r, m)] + [ - J.state(k) for k in rel.inputs(max(self.ms)) - ] + self.base = Base(rel, self.ms, extra) if extra is not None: - top, funcs = len(funcs), funcs + [J.state(extra)] - self.base = Base(rel, funcs) - self.nb = len(funcs) + top = self.base.nb - 1 + self.nb = self.base.nb self.top = top self.mons = None self.capped = None @@ -455,7 +561,7 @@ def _gf_terms(P, sub, p): 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): + for g, e in enumerate(int(e_) for e_ in m): if not e: continue if g in sub: @@ -470,7 +576,7 @@ def _gf_terms(P, sub, p): 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.""" + many, the system is past the caps of msolve (a tenth of msolve_work) or msolve fails.""" from ..sym.msolve import MsolveMissingError, _msolve_binary def text(d): @@ -493,7 +599,7 @@ def text(d): 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): + with work.local_caps(msolve_work=work.cap("msolve_work") / 10): r = work.run_msolve([binary, "-f", fi, "-o", fo, "-P", "1", "-t", str(_threads())]) work.tick(int(r.entries)) txt = "" @@ -529,7 +635,7 @@ def __init__(self, pr, theta, p, rng, stop): 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) + rows = _gradients(J, funcs, list(appear), pt, p) if rows is None: return free = [] @@ -595,9 +701,9 @@ def _gradients(J, funcs, gens, pt, p): 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] + polys = [q.numer] + [J.diff(q.numer, x) for x in gens] for f, _ in q.exps: - polys += [J.fac[f]] + [J.fac[f].diff(x) for x in gens] + polys += [J.fac[f]] + [J.diff(J.fac[f], 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 @@ -751,6 +857,12 @@ def ratrec1(ts, vs, p): return [x * c % p for x in r1], [x * c % p for x in s1] +def ratrec_columns(ts, V, p): + """ratrec1() per column of V, the values at the points ts, in one call of the engine.""" + V = np.ascontiguousarray(np.asarray(V, dtype=np.int64).reshape(len(ts), -1)) + return _core.io_ratrec(np.asarray(ts, dtype=np.int64), V, p, _threads()) + + def _pgcd(a, b, p): while b: a, b = b, _pdivmod(a, b, p)[1] @@ -775,13 +887,8 @@ def _line(vec, base, direction, p, npts, start=1): 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 + out = ratrec_columns(ts, np.array(vals, dtype=np.int64), p) + return None if any(g is None for g in out) else out def _common_denominator(fracs, p): @@ -1186,11 +1293,14 @@ def profiles(rel, unknown, p, rng, limit=6): def row(r, k): if (r, k) not in memo: - if k and len(J.observable(r, k - 1)[k - 1].numer) > _JET: + try: + 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] + except JetTooLargeError: 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 = [] @@ -1312,7 +1422,7 @@ def trajectory(rel, values, p, K): 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 + Q = J.Q if J.Q is not None else J.one S = _Series([J.Fh[kept[a]] for a in unknown] + [Q], vars_, vals, p, K) q0 = None dser = {a: [] for a in unknown} @@ -1335,7 +1445,7 @@ def trajectory(rel, values, p, 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) + T = _Series([M, E if E is not None else J.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)] @@ -1447,9 +1557,9 @@ def combine(J, coeffs, quos): for k, x in q.exps: T[k] = max(T.get(k, 0), x) pw = {} - total = J.R.zero + total = J.zero for c, q in zip(coeffs, quos): - if not c: + if c.is_zero(): continue term = c * q.numer have = dict(q.exps) @@ -1463,18 +1573,21 @@ def combine(J, coeffs, quos): return total, T -def products(J, base, mons): - """The monomials of the base functions as Quo.""" +def products(J, base, mons, stop=None): + """The monomials of the base functions as Quo; JetTooLargeError as _mul(), or where the clock of the searches + passes `stop`.""" pw = {} out = [] for m in mons: - num, ex = J.R.one, {} + if stop is not None and work.ticks() > stop: + raise JetTooLargeError("the clock of the search") + num, ex = J.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)] + pw[(v, e)] = _mul(*[base[v].numer] * e) + num = _mul(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()))) @@ -1486,24 +1599,23 @@ def identity(rel, proj, coef, params_pos): 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 + ng = J.R.nvars() mons = proj.mons def ring_poly(co): - out = R.zero + d = {} 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 + d[tuple(e)] = d.get(tuple(e), 0) + flint.fmpq(int(c.numerator), int(c.denominator)) + return J.R.from_dict(d) 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 + return combine(J, coeffs, products(J, proj.base.funcs, mons))[0].is_zero() def coefficient_values(coef, theta, p): diff --git a/src/symident/detection/multiexp.py b/src/symident/detection/multiexp.py index 5a22c5e..72eaf51 100644 --- a/src/symident/detection/multiexp.py +++ b/src/symident/detection/multiexp.py @@ -18,24 +18,29 @@ 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.""" + # a switch or a fixed start excludes the route whatever the number of conditions, so it is named first + for part in series.parts: + seg = part["segs"][0] + if seg.get("free") or seg.get("on") is not None: + return None, "the route takes a model without switches" + for i, x in enumerate(part["st"]): + v = seg["x0"][i][0] + if i not in set(part["known"]) and (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 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): + for i in range(len(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 @@ -61,6 +66,64 @@ def eligible(series): return starts, None +def absorbed_starts(parts, coords): + """({state: (new state, coordinate)}, parts): each state x with a fixed start s that enters, with a coordinate c, + only as c x (then Z = c x / s) or as c + x (then Z = x + c - s) becomes the state Z with the start c, and c leaves + the right-hand sides and the observables; the map of the states is invertible for c != 0, so the new model has the + same fiber. ({}, parts) where no state is so.""" + from ..sym.parse import model_sympify + from .rationalize import _str + + if len(parts) != 1 or len(parts[0]["segments"]) != 1: + return {}, parts + seg = parts[0]["segments"][0] + f = {x: model_sympify(str(e)) for x, e in seg["f"].items()} + g = {y: model_sympify(str(e)) for y, e in seg["g"].items()} + ic = {x: model_sympify(str(e)) for x, e in seg["ic"].items()} + taken = set(coords) | set(f) | {str(s_) for e in list(f.values()) + list(g.values()) for s_ in e.free_symbols} + starts = {s_ for e in ic.values() for s_ in e.free_symbols} + out, used = {}, set() + for x in list(f): + s0 = ic.get(x) + if s0 is None or not s0.is_number: + continue + X = spy.Symbol(x) + near = set().union(*[e.free_symbols for e in list(f.values()) + list(g.values()) if X in e.free_symbols]) + for c in sorted((spy.Symbol(c_) for c_ in coords), key=str): + if c not in near or c in starts or str(c) in used: + continue + k = 1 + while f"si_Z{k}" in taken: + k += 1 + Z = spy.Symbol(f"si_Z{k}") + forms = [(s0 * Z / c, c / s0)] if s0 != 0 else [] + forms.append((Z - c + s0, spy.Integer(1))) + for sub, rate in forms: + f2 = {y: spy.cancel(e.subs(X, sub)) for y, e in f.items() if y != x} + f2[str(Z)] = spy.cancel(rate * f[x].subs(X, sub)) + g2 = {y: spy.cancel(e.subs(X, sub)) for y, e in g.items()} + if all(c not in e.free_symbols for e in list(f2.values()) + list(g2.values())): + break + else: + continue + f = {y: f2[y] for y in [y_ if y_ != x else str(Z) for y_ in f]} + g = g2 + ic = {(str(Z) if y == x else y): (c if y == x else e) for y, e in ic.items()} + out[x] = (str(Z), str(c)) + used.add(str(c)) + taken.add(str(Z)) + break + if not out: + return {}, parts + seg2 = dict( + seg, + f={y: _str(e) for y, e in f.items()}, + g={y: _str(e) for y, e in g.items()}, + ic={y: _str(e) for y, e in ic.items()}, + ) + return out, [dict(parts[0], segments=[seg2])] + + 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 @@ -168,6 +231,18 @@ def count(parts, coords, series, positive, floor, experiments=None): t0 = time.monotonic() starts, why = eligible(series) + absorbed = {} + if why is not None and "is fixed" in why: + # a fixed start next to a coordinate that enters only with that state: the coordinate is the start + absorbed, new = absorbed_starts(parts, coords) + if absorbed: + from .discrete import Series + + series2 = Series(new, coords, positive) + series2.pins = series.pins + starts, why = eligible(series2) + if why is None: + parts, series = new, series2 if why is not None: return {"why": why} st = [str(x) for x in series.parts[0]["st"]] @@ -199,6 +274,7 @@ def count(parts, coords, series, positive, floor, experiments=None): "fiber": fib, "crit": crit, "series": sk, + "absorbed": absorbed, "seconds": round(time.monotonic() - t0, 2), } if cc is None: diff --git a/src/symident/detection/observability/analysis.py b/src/symident/detection/observability/analysis.py index dc780bc..4b519af 100644 --- a/src/symident/detection/observability/analysis.py +++ b/src/symident/detection/observability/analysis.py @@ -157,6 +157,7 @@ def __init__( self.rank_cap = self.nz self.scal_ws = None self.stacked_first = self.stacked_quick = False + self.stack_order = None self.static_rows = None # ---- kernels ---------------------------------------------------------------------- @@ -396,6 +397,10 @@ def _lower_caps(self, cap0, cap_rank): levels = sorted(set(cap0), reverse=True) if ref is None or len(levels) < 2: return False + if self.stack_order is not None: + run.nt_cap = [min(c, self.stack_order) for c in cap0] + if cap_rank() == ref: + return True lo, hi = 0, len(levels) - 1 while lo < hi: mid = (lo + hi + 1) // 2 @@ -517,7 +522,8 @@ def saturate(self): 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)), + # at rest the stacked pass may end certified: it runs the checks of the block pass + checks=self.joint or not (self.stacked_first and (not self.stacked_quick or run.ss_constraint)), longest_first=run.has_gaps and not self.joint, stacked_profile=sys.stacked_profile() if self.stacked_first else None, ) @@ -652,8 +658,13 @@ def certify(self, sc): sc["order_draws"] = hint.get("order_draws") # a power of a state at 0 has no rows of D_k at the start (method: series at a singular start) start_pow = any(10 in list(t["op"]) for t in self.multi["tapes"]) - if not sc["certified"] and not self.stacked_first and not run.nuis_cols and not start_pow: + if not sc["certified"] and not run.nuis_cols and not start_pow and (self.joint or not self.stacked_first): + if self.stacked_first: + self.stack_order = int(sc["nt_used"]) self._certificate(sc) + if self.stacked_first and sc.get("certified"): + # the certified orders replace the block scans: the pass goes on as a block pass + self.stacked_first = self.stacked_quick = False nb = self.sys.kc if self.joint else (len(run.chain_groups) if run.chain_groups else -1) if ( run.has_gaps @@ -820,11 +831,17 @@ def _certificate(self, sc): ) ordv = [bo[i] + _plateau() if o is None else int(o) for i, o in enumerate(orders)] need = max([1, *ordv]) + caps = run.nt_cap + if self.joint and run.has_gaps and len(ordv) == self.sys.kc: + # each block at the certified order of the block + run.nt_cap = list(ordv) try: rc = self.kcall4(sc["point0"], P1, need, sc.get("mtot_used") or 0) except Exception as exc: swallow(exc, "certified kernel") rc = None + if not ok(rc) or rank_of(rc) < rank_of(sc["ref"]): + run.nt_cap = caps if ok(rc) and rank_of(rc) < rank_of(sc["ref"]): # an order below the one the scan needed cannot be sufficient session.note( diff --git a/src/symident/detection/observability/joint.py b/src/symident/detection/observability/joint.py index 970af63..dd001a4 100644 --- a/src/symident/detection/observability/joint.py +++ b/src/symident/detection/observability/joint.py @@ -14,6 +14,9 @@ from .rest import RestingStates from .start import DiagonalStart +# the diagonal start depends on the models only: passes and pivot sets of one model share it +_diag_memo: dict = {} + # the series order of the curve samples is doubled at most this often where a kernel at eps = 1 needs more coefficients _CURVE_RAISES = 2 @@ -188,8 +191,22 @@ def diagonal_start(self): for n in self.solve_param_names if run.slot(n) is not None and n not in self.l_names and n not in self.fwd_banned ] + conds = list(dict.fromkeys([*reps, self.fwd_cond])) + key = ( + tuple(tuple(self.models[ci]) for ci in conds), + tuple(reps), + self.fwd_cond, + tuple(tuple(self.held_of(ci)) for ci in conds), + tuple(sorted(cand)), + tuple(sorted(self.held_names)), + ) try: - ds = DiagonalStart(self.models, reps, self.fwd_cond, self.held_of, cand, keep=self.held_names) + ds = _diag_memo.get(key) + if ds is None: + ds = DiagonalStart(self.models, reps, self.fwd_cond, self.held_of, cand, keep=self.held_names) + if len(_diag_memo) >= 32: + _diag_memo.clear() + _diag_memo[key] = ds except SYMPY_FAILS as exc: sympy_fail(exc) return None @@ -471,7 +488,10 @@ def _project(self, locs, p, cores): np.asarray(loc["S"], dtype=np.int64), int(self.nz_local), int(loc["N"]), p, list(st_l), int(cores) ) r_ps += int(sp["r1"]) - QS.append(np.asarray(sp["Q"], dtype=np.int64).reshape(-1, len(sh_l) * int(loc["N"]))) + width = len(sh_l) * int(loc["N"]) + q = np.asarray(sp["Q"], dtype=np.int64) + # without shared columns the projection has no entries, and reshape(-1, 0) has no row count + QS.append(q.reshape(-1, width) if width else np.zeros((0, 0), dtype=np.int64)) prec.extend(ints(sp["prec"])) return r_p, Q, r_ps, QS, prec, series diff --git a/src/symident/detection/observability/proof.py b/src/symident/detection/observability/proof.py index d3bb429..cdac6b8 100644 --- a/src/symident/detection/observability/proof.py +++ b/src/symident/detection/observability/proof.py @@ -752,7 +752,7 @@ def _lines_dict(lines): def _jet_forms(tapes, ch): - """(fs, g, x0, events, times) of the chain `ch` from the jets of its tapes, or why there are none.""" + """(fs, g, x0, events, times) of the chain `ch` from the jets of the tapes of the chain, or why there are none.""" if any(not tapes[i].get("jet_f") for i in ch): return "no rational form of the kernel" t = tapes[ch[0]] @@ -819,8 +819,8 @@ def _checked_at_random(route): def _rests_read(an, v, ci, rest): - """Bezout numbers of the resting systems the identity of condition `ci` with the closed form `v` reads: its own, - those of the states x_c, and the largest for a state read by its plain name.""" + """Bezout numbers of the resting systems the identity of condition `ci` with the closed form `v` reads: that of + the condition, those of the states x_c, and the largest for a state read by the plain name.""" sys = an.sys states = set(sys.real_state_names) toks = {t for x in v.values() for t in _IDENT.findall(str(x))} @@ -854,7 +854,7 @@ def prove_exact(an, result): except Exception as exc: swallow(exc, "exact proof") return _fail(dirs, f"field setup failed: {type(exc).__name__}") - # L = log(b) of a recast holds no state of its own; its field F(b)/b enters the identities + # L = log(b) of a recast holds no separate state; the field F(b)/b enters the identities for r in an.recast or []: for rg in light["regimes"]: F = dict(line.split("=", 1) for line in rg["f"]) @@ -867,7 +867,7 @@ def prove_exact(an, result): _exact_scalings(an, dirs) return _fail([d for d in dirs if not d.get("exact")], "no exact proof with these nuisance coordinates") if nuis: - # the input itself starts the chain (log_ under a log chart); its component is free as well + # the input itself starts the chain (log_ under a log chart); the component of the input is free as well starts = [] for w in strs(an.multi.get("nuisance_kept")): starts += [x for x in light["states"] if x == w or re.fullmatch(f"log_{re.escape(w)}_*", x)] diff --git a/src/symident/detection/relax.py b/src/symident/detection/relax.py index c46e22b..da7c368 100644 --- a/src/symident/detection/relax.py +++ b/src/symident/detection/relax.py @@ -448,6 +448,135 @@ def reads(lfs): return None +def _orbit_rates(symmetries, leaves, dropped): + """(reason, fields, rates): the exact directions that move a leaf W or a coordinate a start reads, as fields + {symbol: component}, and per leaf the rates X(c_W) at which each changes c_W = Lambda(W) - Lambda(omega_W(theta)), + Lambda the logarithm for a product leaf and the identity for a log leaf; the reason where the directions are not + exact or do not commute.""" + rows = [lf for lf in leaves if lf["absorbs"] is None] + names = {lf["name"] for lf in rows} + every = set() + for lf in rows: + every |= {str(x) for x in lf["value"].free_symbols} + every -= set(dropped) + fields = [] + for s in symmetries: + sup = set(s.get("support") or []) + if not sup & (names | every): + continue + if s.get("level") != "exact": + return ( + f"the direction on {', '.join(sorted(sup))} that moves a new coordinate or a start is not exact", + [], + [], + ) + gen = s.get("generator") or {} + fields.append({spy.Symbol(k): model_sympify(str(v)) for k, v in gen.items() if str(v) != "0"}) + for i, X in enumerate(fields): + for Y in fields[i + 1 :]: + for x in set(X) | set(Y): + if spy.simplify(_apply(X, Y.get(x, 0)) - _apply(Y, X.get(x, 0))) != 0: + return "the directions that move the new coordinates or their starts do not commute", [], [] + rates = [] + for lf in rows: + W, w = spy.Symbol(lf["name"]), lf["value"] + lam = (lambda e: e) if lf["kind"] == "log" or isinstance(w, spy.log) else spy.log + rates.append([spy.simplify(spy.expand_log(_apply(X, lam(W)) - _apply(X, lam(w)), force=True)) for X in fields]) + return None, fields, rates + + +def _apply(X, e): + return spy.together(sum((v * spy.diff(e, x) for x, v in X.items()), spy.Integer(0))) + + +def affine_on_orbits(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: the directions of _orbit_rates() change each c_W at a rate they do not move; + then c is affine in the group parameters on every orbit, and the solutions of c = 0 form an affine subspace.""" + why, fields, rates = _orbit_rates(symmetries, leaves, dropped) + if why is not None: + return why + for row in rates: + for rate in row: + if any(spy.simplify(_apply(Y, rate)) != 0 for Y in fields): + return "a direction changes the condition of a new coordinate at a rate that moves along the orbit" + return None + + +def _sign_on_orthant(e, syms): + """+1 or -1 where the rational function e has this sign wherever the symbols are positive, by the signs of the + coefficients of numerator and denominator; else 0.""" + num, den = spy.fraction(spy.together(e)) + out = 1 + for p in (num, den): + if not p.free_symbols <= syms: + return 0 + if p.is_number: + if p == 0: + return 0 + out *= 1 if p > 0 else -1 + continue + cs = spy.Poly(spy.expand(p), *sorted(p.free_symbols, key=str)).coeffs() + if all(c > 0 for c in cs): + continue + if all(c < 0 for c in cs): + out = -out + continue + return 0 + return out + + +def monotone_on_orbits(symmetries, leaves, dropped, positive, limit=5000): + """None if each orbit of the continuous directions of the relaxed model meets the starts of the leaves in one point + at most, else the reason. The directions of _orbit_rates() are scalings or shifts, so their orbits are images of + R^r; where r of the conditions c_W, with signs, have a matrix of rates X_i(c_W) whose principal minors are positive + wherever the coordinates they read are positive, t -> c(g_t q) is injective on R^r (Gale and Nikaido).""" + why, fields, rates = _orbit_rates(symmetries, leaves, dropped) + if why is not None: + return why + if not fields: + return None + for X in fields: + for x, v in X.items(): + if not (v.is_number or (v / x).is_number): + return "a direction that moves a new coordinate or a start is neither a scaling nor a shift" + rows = [lf for lf in leaves if lf["absorbs"] is None] + pos = {spy.Symbol(lf["name"]) for lf in rows if lf["kind"] != "log"} + pos |= {x for row in rates for e in row for x in e.free_symbols} if positive is True else set() + if positive is not True: + pos |= {spy.Symbol(str(p)) for p in positive or ()} + r = len(fields) + sign = {(j, i): _sign_on_orthant(rates[j][i], pos) for j in range(len(rates)) for i in range(r)} + tried = 0 + + def search(i, used, chosen): + nonlocal tried + if i == r: + tried += 1 + M = spy.Matrix([[sg * rates[j][k] for k in range(r)] for j, sg in chosen]) + return all( + _sign_on_orthant(M.extract(list(sub), list(sub)).det(), pos) > 0 + for size in range(2, r + 1) + for sub in _subsets(r, size) + ) + for j in range(len(rates)): + if j in used or not sign[(j, i)] or tried > limit: + continue + if search(i + 1, used | {j}, chosen + [(j, sign[(j, i)])]): + return True + return False + + if search(0, frozenset(), []): + return None + return "no conditions of the new coordinates have rates whose principal minors keep one sign" + + +def _subsets(r, size): + from itertools import combinations + + return combinations(range(r), size) + + 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)).""" @@ -469,6 +598,29 @@ def keeps_leaves(sigma, leaves, dropped): return True +def private_leaves(leaves, coords): + """Whether every leaf has a coordinate that no other leaf reads and on which the leaf is transcendental over the + rational functions of it: the exponent of exp(psi0), the argument of log(psi0), the exponent of b0^mu with b0 not + reading it. Then the leaves are algebraically independent over the rational functions of the coordinates, by + induction on the leaves (docs/method/global.rst, "Rational form of the fiber").""" + cs = {spy.Symbol(c) for c in coords} + vals = [lf["value"] for lf in leaves] + for k, w in enumerate(vals): + others = set().union(*[v.free_symbols for j, v in enumerate(vals) if j != k]) + if isinstance(w, (spy.exp, spy.log)): + u, base = w.args[0], spy.Integer(0) + elif w.is_Pow: + u, base = w.exp, w.base + if base == 1: + return False + else: + return False + own = (u.free_symbols & cs) - others - base.free_symbols + if not any(spy.diff(u, c) != 0 for c in own): + 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.""" diff --git a/src/symident/detection/restchart.py b/src/symident/detection/restchart.py index 7b894be..c604aac 100644 --- a/src/symident/detection/restchart.py +++ b/src/symident/detection/restchart.py @@ -162,3 +162,123 @@ def sub(e): "positive": new_pos, "coordinates": [c for c in coords if spy.Symbol(c) not in exch] + [str(R[x]) for x in H], } + + +def rest_exchange(rhs, start, coords, fixed=(), positive=True): + """({state: resting coordinate}, {coordinate: value}) for balances with no closed form in the states: the + resting value of each state not in `start` is a new coordinate, and as many coordinates entering the balances + linearly, with a coefficient matrix invertible at a random point, are solved from them. `rhs` holds the + right-hand sides at rest as SymPy expressions, `start` the states with a resting value already. A ValueError + where no such coordinates exist.""" + rng = random.Random("rest exchange") + U = [x for x in rhs if x not in start] + cs = {spy.Symbol(c) for c in coords} - set(rhs) + taken = {str(s) for e in rhs.values() for s in e.free_symbols} | {str(x) for x in rhs} | set(coords) + R = {x: _fresh(f"si_{x}_rest", taken) for x in U} + held = {**start, **R} + hb = [spy.fraction(spy.together(rhs[x].xreplace(held)))[0] for x in U] + pos = None if positive is True else {str(p) for p in (positive or ())} + + def candidates(e): + return [p for p in sorted(e.free_symbols & cs, key=str) if 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} + syms = set(cs) | set(R.values()) + 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: + return R, exch + raise ValueError( + "no coordinates enter the balances of " + ", ".join(map(str, U)) + " linearly with an invertible " + "coefficient matrix" + ) + + +def _half_powers(e): + """The subexpressions b^(k/2) of `e` with k odd.""" + return [a for a in spy.preorder_traversal(e) if a.is_Pow and a.exp.is_Rational and a.exp.q == 2] + + +def _reduce(E, w, P): + """(a, b) with E = a + b w modulo w^2 - P, E a polynomial in w.""" + q = spy.Poly(spy.expand(E), w).rem(spy.Poly(w**2 - P, w)) + return q.coeff_monomial(1), q.coeff_monomial(w) + + +def root_chart(parts, coords, positive=True, fixed=()): + """{"rest", "exchanged", "kind"} where the starts hold the square root w of one polynomial P of the coordinates: + the start R of one state is a new coordinate, and a coordinate p of degree one in the factor of the relation of + R and P that the start satisfies is solved from it. In the starts of `parts` the root is replaced by w as a + rational function of R and the coordinates. None where no start holds a root; a ValueError where the roots are + not of this form or no such coordinate exists. A count of one in the chart is one for the model: the map from + the coordinates to the chart is injective, p being rational in the chart (docs/method/global.rst).""" + cs = {spy.Symbol(c) for c in coords} + starts = [seg["ic"] for part in parts for seg in part["segments"][:1] if seg.get("ic")] + exprs = [(ic, k, model_sympify(str(v))) for ic in starts for k, v in ic.items() if v is not None] + pows = [a for _, _, e in exprs for a in _half_powers(e)] + if not pows: + return None + rads = {spy.expand(a.base) for a in pows} + if len(rads) > 1: + raise ValueError("discrete() handles starts with the square root of one polynomial of the coordinates") + P = rads.pop() + if not P.free_symbols <= cs or not P.is_polynomial(*sorted(P.free_symbols, key=str)): + raise ValueError(f"discrete() handles square roots of polynomials of the coordinates, not of {_str(P)}") + w = spy.Dummy("w") + + def in_w(e): + return e.replace( + lambda a: a.is_Pow and a.exp.is_Rational and a.exp.q == 2 and spy.expand(a.base) == P, + lambda a: w ** int(2 * a.exp), + ) + + # the start of least size that depends on the root + best = None + for _, k, e in sorted(exprs, key=lambda t: spy.count_ops(t[2])): + N, D = spy.fraction(spy.together(in_w(e))) + (a, b), (c, d) = _reduce(N, w, P), _reduce(D, w, P) + if b != 0 or d != 0: + best = (k, e, a, b, c, d) + break + k, e, a, b, c, d = best + taken = {str(s) for _, _, x in exprs for s in x.free_symbols} | set(coords) | {kk for _, kk, _ in exprs} + R = _fresh(f"si_{k}_start", taken) + # w = (a - R c) / (R d - b); the factor of (a - R c)^2 - P (R d - b)^2 that the start satisfies + Q = spy.expand((a - R * c) ** 2 - P * (R * d - b) ** 2) + at = spy.together(in_w(e)) + F = None + for f, _ in spy.factor_list(Q)[1]: + if R not in f.free_symbols: + continue + num = spy.fraction(spy.together(f.xreplace({R: at})))[0] + if _reduce(spy.expand(num), w, P) == (0, 0): + F = f + break + if F is None: + raise ValueError("discrete(): no factor of the relation of the start and the root vanishes at the start") + pos = None if positive is True else {str(p) for p in (positive or ())} + cand = [p for p in sorted(F.free_symbols & cs, key=str) if str(p) not in fixed and spy.Poly(F, p).degree() == 1] + if not cand: + raise ValueError(f"discrete(): no coordinate enters the relation of the start of {k} and the root linearly") + p = sorted(cand, key=lambda q: (pos is not None and str(q) not in pos, spy.count_ops(F.coeff(q)), str(q)))[0] + L = spy.Poly(F, p) + value = spy.cancel(-L.coeff_monomial(1) / L.coeff_monomial(p)) + root = (a - R * c) / (R * d - b) + for ic, kk, x in exprs: + if kk == k and x != e and in_w(x) != x: + raise ValueError(f"discrete() needs the start of {k} with the root alike in every condition") + if kk == k and x == e: + ic[kk] = str(R) + elif in_w(x) != x: + ic[kk] = _str(spy.cancel(in_w(x).xreplace({w: root}))) + return {"rest": {k: str(R)}, "exchanged": {p: value}, "kind": "root", "root": _str(spy.sqrt(P))} diff --git a/src/symident/detection/tower.py b/src/symident/detection/tower.py new file mode 100644 index 0000000..ee1d4f8 --- /dev/null +++ b/src/symident/detection/tower.py @@ -0,0 +1,1046 @@ +"""The stage tower (docs/method/global.rst, "The stage tower"): every segment of a condition alone at rising +orders, the free directions cut at random values, and a coordinate with one value on the points of the cut system +pinned for every later stage. A run modulo a prime makes the list of claims, each with the set E of the original +equations that the system of the claim was formed from; a test over Q at an integer point drawn after the list +accepts a claim where the system of E has finitely many points, at least one, and the claimed coordinate has the +value of the point on all of them (the pin by descent and the verified pin).""" + +import contextlib +import math +import sys +import time +from fractions import Fraction + +import sympy as spy + +from .. import session +from ..gfp import PRIMES +from ..sym.degrees import Atoms, Deg +from ..sym.parse import model_sympify +from . import work + +# the closed parts of a block taken to msolve, and the points of a cut system kept +_MAX_PART = 250 +_MAX_POINTS = 64 +# the terms of the triangular elimination: the whole system, and one polynomial that grows +_TRI_TOTAL = 200000 +_TRI_EACH = 4000 + + +def applies(series): + """None where every condition is one segment without switch, free start, free power of a state at 0 and unknown + input, with every start a number, a coordinate or a rational function of the coordinates; else the reason.""" + if series.inputs: + return "the stage tower covers models without unknown inputs" + if series.start_powers: + return "the stage tower covers models without a free power of a state at 0" + for part in series.parts: + if len(part["segs"]) > 1: + return "the stage tower covers models without events" + seg = part["segs"][0] + if seg.get("free") or seg.get("on") is not None: + return "the stage tower covers models without switches and free starts" + for v, _num, _den in seg["x0"]: + if v is None: + return "the stage tower covers models without free starts" + return None + + +def _constant_states(f, known): + """The states of `known` ({symbol: value}) that stay at their value along the segment of the right-hand + sides `f` ({symbol: expression}): the largest set C whose right-hand sides vanish with the states of C at their + values, whatever the other states do.""" + C = {x for x in known if x in f} + while True: + at = {x: known[x] for x in C} + drop = {x for x in C if spy.cancel(f[x].xreplace(at)) != 0} + if not drop: + return C + C -= drop + + +def _jump_pins(part, coords, positive, p, rng, order=4): + """The event time of the first event of a condition as a coordinate pinned without a random step: a + coordinate read nowhere else in the condition, where an output coefficient at the start differs between the + right-hand sides and the states before and after the event (the lemma of the time of an event); else None.""" + from .conditions import compose_event + from .discrete import Series + + segs = part["segments"] + if len(segs) < 2: + return None + t = str(segs[1]["t"]).strip("() ") + if t not in coords: + return None + texts = [str(v) for seg in segs for d in (seg["f"], seg["g"], seg.get("ic") or {}) for v in d.values() if v] + texts += [str(e["value"]) for seg in segs[1:] for e in seg.get("events") or []] + if any(spy.Symbol(t) in model_sympify(x).free_symbols for x in texts): + return None + ic = dict(segs[0]["ic"]) + if any(v is None for v in ic.values()): + return None + after = dict(ic) + sub = {spy.Symbol(x): model_sympify(f"({v})") for x, v in ic.items()} + for e in segs[1].get("events") or []: + v = model_sympify(str(e["value"])).xreplace(sub) + after[e["var"]] = compose_event(after[e["var"]], e["method"], f"({v})") + a = {**segs[0], "ic": ic} + b = {"f": segs[1]["f"], "g": segs[1]["g"], "ic": after, "t": segs[0]["t"], "label": ""} + point = {spy.Symbol(c): spy.Integer(rng.randint(2, p - 1)) for c in coords} + try: + ya = Series([{"segments": [a]}], coords, positive).numeric(point, order, p=p) + yb = Series([{"segments": [b]}], coords, positive).numeric(point, order, p=p) + except (ValueError, ZeroDivisionError): + return None + if ya is None or yb is None or len(ya) != len(yb): + return None + return coords.index(t) if any(u != v for u, v in zip(ya, yb)) else None + + +def segment_units(parts, coords, positive): + """(units, coordinates, exact): the units of the stage tower, each one segment of a condition, over the + coordinates and a new coordinate for each start after an event that is not known, and the event times pinned + by their jump. A start after an event is known where the state stays constant on the segment before from a + known value, or an event sets it from known values. A unit after an event at a time neither a number nor + pinned is left out. Each Series has `free_starts`, the new coordinates it reads.""" + from .conditions import compose_event, time_value + from .discrete import Series + + rng = session.current().rng("discrete jumps", tuple(coords)) + p = PRIMES[0] + ext = list(coords) + exact = [] + plan = [] + for c, part in enumerate(parts): + segs = part["segments"] + plan.append(({**part, "segments": segs[:1]}, [])) + if len(segs) < 2 or any(v is None for v in segs[0]["ic"].values()): + continue + tau = _jump_pins(part, coords, positive, p, rng) + if tau is not None and tau not in exact: + exact.append(tau) + known = {spy.Symbol(x): model_sympify(f"({v})") for x, v in segs[0]["ic"].items()} + for j in range(1, len(segs)): + prev, seg = segs[j - 1], segs[j] + fp = {spy.Symbol(x): model_sympify(f"({v})") for x, v in prev["f"].items()} + pre = {x: known[x] for x in _constant_states(fp, known)} + if "time" in seg["f"]: + pre[spy.Symbol("time")] = model_sympify(f"({seg['t']})") + start = dict(pre) + for e in seg.get("events") or []: + x, v = spy.Symbol(e["var"]), model_sympify(f"({e['value']})") + if v.free_symbols - {spy.Symbol(c_) for c_ in coords} - set(pre): + start.pop(x, None) + continue + v = v.xreplace(pre) + if e["method"] == "replace": + start[x] = v + elif x in start: + start[x] = model_sympify(compose_event(f"({start[x]})", e["method"], f"({v})")) + ic, new = {}, [] + for x in seg["f"]: + if spy.Symbol(x) in start: + ic[x] = str(start[spy.Symbol(x)]) + else: + ic[x] = f"si_s{c}_{j}_{x}" + new.append(ic[x]) + known = dict(start) + tname = str(seg["t"]).strip("() ") + # the coefficients after an event are invariants of the output where the event time is + if time_value(str(seg["t"])) is None and not (tname in coords and coords.index(tname) in exact): + break + unit = {"f": seg["f"], "g": seg["g"], "ic": ic, "t": seg["t"], "label": seg.get("label", "")} + ext += [x for x in new if x not in ext] + plan.append(({**part, "segments": [unit]}, new)) + units = [] + for unit, new in plan: + u = Series([unit], ext, positive if positive is True else list(positive) + new) + u.free_starts = new + units.append(u) + return units, ext, exact + + +# sparse polynomials {((variable, exponent), ...): coefficient}, modulo p (p > 0) or over Q (p = 0) + + +def _vars(P): + return {v for mm in P for v, _ in mm} + + +def _deg(P): + return max((sum(e for _, e in mm) for mm in P), default=0) + + +def _norm(c, p): + return c % p if p else c + + +def _div(a, b, p): + return a * pow(b, -1, p) % p if p else Fraction(a) / b + + +def _mul(a, b, p): + out = {} + for ma, ca in a.items(): + da = dict(ma) + for mb, cb in b.items(): + d = dict(da) + for v, e in mb: + d[v] = d.get(v, 0) + e + mm = tuple(sorted(d.items())) + out[mm] = _norm(out.get(mm, 0) + ca * cb, p) + return {m: c for m, c in out.items() if c} + + +def _sub(P, v, expr, p): + """P with the variable v replaced by the polynomial expr.""" + if v not in _vars(P): + return P + out = {} + for mm, c in P.items(): + e = dict(mm).get(v) + if not e: + out[mm] = _norm(out.get(mm, 0) + c, p) + continue + t = {tuple(x for x in mm if x[0] != v): c} + for _ in range(e): + t = _mul(t, expr, p) + for m2, c2 in t.items(): + out[m2] = _norm(out.get(m2, 0) + c2, p) + return {m: c for m, c in out.items() if c} + + +def _eval(P, vals, p): + acc = 0 + for mm, c in P.items(): + t = c + for v, e in mm: + if v not in vals: + return None + t = t * pow(vals[v], e, p) % p if p else t * vals[v] ** e + acc = _norm(acc + t, p) + return acc + + +class _System: + """Equations with the set of original equations each was formed from, the saturation, and the variables solved: + {variable: (polynomial in the variables left, provenance)}. Every step is an equivalence away from the + saturation.""" + + def __init__(self, eqs, sat, p, n): + self.eqs = [(P, frozenset([j])) for j, P in enumerate(eqs) if P] + self.sat, self.p, self.n = [dict(f) for f in sat], p, n + self.solved = {} + self.empty = False + + def _apply(self, v, expr, prov, skip=None): + p = self.p + self.solved = { + w: ((_sub(e, v, expr, p), pr | prov) if v in _vars(e) else (e, pr)) for w, (e, pr) in self.solved.items() + } + self.solved[v] = (expr, prov) + out = [] + for k, (P, pr) in enumerate(self.eqs): + if k == skip: + continue + if v in _vars(P): + P, pr = _sub(P, v, expr, p), pr | prov + if P: + if list(P) == [()]: + self.empty = True + out.append((P, pr)) + self.eqs = out + self.sat = [_sub(f, v, expr, p) for f in self.sat] + if any(not f for f in self.sat): + self.empty = True + + def fix(self, keep=frozenset()): + """The variables that an equation a*v + b fixes, in turn; jets alone and linear in one equation, in no factor + of the saturation and not kept, leave with it.""" + while not self.empty: + hit = None + for j, (P, pr) in enumerate(self.eqs): + vs = {mm[0][0] for mm in P if mm} + if len(vs) == 1 and all(not mm or (len(mm) == 1 and mm[0][1] == 1) for mm in P): + v = vs.pop() + hit = (j, v, {(): _div(-P.get((), 0), P[((v, 1),)], self.p)}, pr) + break + if hit is None: + break + j, v, expr, pr = hit + self._apply(v, expr, pr, skip=j) + insat = set().union(*[_vars(f) for f in self.sat]) if self.sat else set() + while not self.empty: + count = {} + for P, _ in self.eqs: + for v in _vars(P): + count[v] = count.get(v, 0) + 1 + hit = next( + ( + j + for j, (P, _) in enumerate(self.eqs) + for mm in P + if len(mm) == 1 + and mm[0][1] == 1 + and mm[0][0] >= self.n + and mm[0][0] not in insat + and mm[0][0] not in keep + and count[mm[0][0]] == 1 + ), + None, + ) + if hit is None: + break + self.eqs.pop(hit) + + def monomials(self, keep=frozenset()): + """v = c*m for an equation a*v + b*m with m free of v; a coordinate only for a monomial in coordinates.""" + while not self.empty: + hit = None + for P, pr in self.eqs: + if len(P) != 2: + continue + 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 v in keep or any(w == v for w, _ in mo): + continue + if v >= self.n or all(w < self.n for w, _ in mo): + hit = (v, {mo: _div(-b, a, self.p)}, pr) + break + if hit: + break + if hit is None: + break + self._apply(*hit) + + def linear(self, keep=frozenset()): + """The equations of degree one, each solved for the unknown of largest (is a jet, index).""" + while not self.empty: + hit = None + for j, (P, pr) in enumerate(self.eqs): + if _deg(P) == 1: + cands = [v for v in _vars(P) if v not in keep] + if cands: + v = max(cands, key=lambda w: (w >= self.n, w)) + a = P[((v, 1),)] + hit = (j, v, {mm: _div(-c, a, self.p) for mm, c in P.items() if mm != ((v, 1),)}, pr) + break + if hit is None: + break + j, v, expr, pr = hit + self._apply(v, expr, pr, skip=j) + + def triangular(self, keep=frozenset()): + """The jets that an equation holds in one term only, a number times the jet, replaced by the rest of the + equation, the shortest equation first, within the caps on the terms.""" + skipped = set() + while not self.empty: + best = None + for j, (P, _) in enumerate(self.eqs): + for v in _vars(P): + if v < self.n or v in keep or (j, v) in skipped: + continue + if [mm for mm in P if any(w == v for w, _ in mm)] == [((v, 1),)]: + if best is None or len(P) < best[0]: + best = (len(P), j, v) + if best is None: + break + _, j, v = best + P, pr = self.eqs[j] + a = P[((v, 1),)] + expr = {mm: _div(-c, a, self.p) for mm, c in P.items() if mm != ((v, 1),)} + total, ok = 0, True + for k, (Q, _) in enumerate(self.eqs): + if k == j or v not in _vars(Q): + total += len(Q) + continue + R = _sub(Q, v, expr, self.p) + if len(R) > _TRI_EACH and len(R) > len(Q): + ok = False + break + total += len(R) + if not ok or total > _TRI_TOTAL: + skipped.add((j, v)) + continue + self._apply(v, expr, pr, skip=j) + skipped = {(a_ - (1 if a_ > j else 0), b_) for a_, b_ in skipped if a_ != j} + + def value(self, v, sol, depth=0): + if v in sol: + return sol[v] + if v not in self.solved or depth > 200: + return None + e, _ = self.solved[v] + vals = {} + for w in _vars(e): + x = self.value(w, sol, depth + 1) + if x is None: + return None + vals[w] = x + return _eval(e, vals, self.p) + + def prov_of(self, v): + return self.solved[v][1] if v in self.solved else frozenset() + + +def _components(keep, polys, sat): + 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 _matching(adj): + """A maximum matching of the equations (lists of variables) with the variables: {variable: equation}.""" + mv, me = {}, {} + for e0 in range(len(adj)): + parent, seen, stack, end = {}, {e0}, [e0], None + while stack and end is None: + e = stack.pop() + for v in adj[e]: + if v in parent: + continue + parent[v] = e + if v not in mv: + end = v + break + if mv[v] not in seen: + seen.add(mv[v]) + stack.append(mv[v]) + if end is None: + continue + v = end + while True: + e = parent[v] + prev = me.get(e) + mv[v], me[e] = e, v + if e == e0: + break + v = prev + return mv + + +def _closure(seeds, adj, mv): + """The unknowns reached from `seeds` through the matched equations; None where one is unmatched.""" + c, todo = set(seeds), list(seeds) + if any(v not in mv for v in c): + return None + while todo: + for w in adj[mv[todo.pop()]]: + if w not in c: + if w not in mv: + return None + c.add(w) + todo.append(w) + return c + + +def _parts(eqs, sat, keep, need): + """Per component of the unknowns `keep` that holds one of `need`: the closed parts to try, smallest first.""" + out = [] + for sub in _components(keep, [P for P, _ in eqs], sat) if keep else []: + if not set(sub) & need: + continue + sp = [(P, pr) for P, pr in eqs if _vars(P) & set(sub)] + adj = [sorted(_vars(P)) for P, _ in sp] + mv = _matching(adj) + seeds = [v for v in sub if v in need] + small = min((c for c in (_closure([v], adj, mv) for v in seeds) if c), key=len, default=None) + tries = [c for c in (small, _closure(seeds, adj, mv)) if c and len(c) < len(sub)] + [set(sub)] + out.append((sub, sp, tries)) + return out + + +def _local_blocks(beq, loc, tv, need, n, p): + """[(equations, unknowns)]: per coordinate of `need` in `loc`, the equations within a set A grown from it by the + equation with the fewest unknowns outside A, at the first A where the Jacobian at the true values `tv` is zero in + that coordinate on the kernel and the kernel is free in coordinates only; smallest first, each smaller than `loc`. + The stage runs on such a block as on a component.""" + vs = [_vars(P) for P, _ in beq] + out = {} + for i in sorted(v for v in loc if v < n and v in need): + A = {i} + while len(A) < len(loc): + inA = [j for j, V in enumerate(vs) if V <= A] + if inA and all(v in tv for v in A): + cols = sorted(A, key=lambda v: (v < n, v)) + rows = _jacobian_rows([beq[j][0] for j in inA], cols, tv, p) + free, clean = _kernel_structure(rows, len(cols), p) + if cols.index(i) in clean and all(cols[j] < n for j in free): + out.setdefault(frozenset(A), [beq[j] for j in inA]) + break + touch = [V - A for V in vs if V & A and not V <= A] + if not touch: + break + A |= min(touch, key=len) + return [(out[A], set(A)) for A in sorted(out, key=len)] + + +# the kernel of the Jacobian of a block at the point + + +def _jacobian_rows(polys, cols, vals, p): + at = {v: j for j, v in enumerate(cols)} + rows = [] + for Q in polys: + r = {} + for mm, c in Q.items(): + for v, e in mm: + if v not in at: + continue + t = c * e % p + for w, f in mm: + t = t * pow(vals[w], f - (1 if w == v else 0), p) % p + if t: + r[at[v]] = (r.get(at[v], 0) + t) % p + rows.append({j: x for j, x in r.items() if x}) + return rows + + +def _kernel_structure(rows, ncols, p): + """(free, clean): the columns without pivot of the reduced row echelon form, pivots in the order of the columns, + and the pivot columns whose reduced row has no entry in a free column, which are zero on the kernel.""" + piv = {} + for r in rows: + r = dict(r) + while r: + j = min(r) + if j not in piv: + inv = pow(r[j], -1, p) + piv[j] = {k: x * inv % p for k, x in r.items()} + break + f = r[j] + for k, x in piv[j].items(): + y = (r.get(k, 0) - f * x) % p + if y: + r[k] = y + else: + r.pop(k, None) + free = [j for j in range(ncols) if j not in piv] + red = {} + for j in sorted(piv, reverse=True): + r = dict(piv[j]) + for k in [k for k in r if k != j and k in red]: + f = r.pop(k) + for k2, x in red[k].items(): + if k2 != k: + y = (r.get(k2, 0) - f * x) % p + if y: + r[k2] = y + else: + r.pop(k2, None) + red[j] = r + clean = [j for j, r in red.items() if all(k == j for k in r)] + return free, clean + + +class _Unit: + """One condition at one order: the original equations at a point as a list with a tag each, ("static", j), + ("row", r, k), ("pin", j), and the degree bounds of the rows.""" + + def __init__(self, series, order, positive): + from .discrete import Fiber, _fiber_degrees + + self.series, self.order = series, order + self.fib = Fiber(series, order, positive) + self.n = len(self.fib.names) + self.too_large = getattr(self.fib, "too_large", None) + self._rows = self._degrees = None + self._free = {} + self._fd = _fiber_degrees if not self.too_large else None + + def raw(self, point, p): + """[(polynomial, tag)] of the equations at `point`, modulo p or over Q; None at a pole.""" + from .discrete import _clear + + fib = self.fib + vals = fib.values(point, p) + if vals is None: + return None + out = [(_clear(P, p), ("static", j)) for j, P in enumerate(fib.static)] + for r, ((E, M), b, n) in enumerate(zip(fib.outs, vals, fib.orders)): + for k in range(n + 1): + P = {mm: -c for mm, c in M[k][0].items()} + for l_ in range(k + 1): + for mm, c in E[l_][0].items(): + P[mm] = P.get(mm, 0) + c * b[k - l_][0] + out.append((_clear({mm: c for mm, c in P.items() if c}, p), ("row", r, k))) + out += [(_clear(P, p), ("pin", j)) for j, P in enumerate(fib.pin_polys(point, p))] + return out + + def degrees(self): + """({(r, k): (numerator, denominator degree)} of every row, degree of the saturation with the starts, + [degrees of the pins]): bounds from the recursion of the series, a number (0, 0).""" + if self._degrees is None: + s = self.series + A = Atoms() + outs = s._outputs([Deg(A, 1) for _ in s.cs], self.order, 0, Deg.const(A, 1), Deg.const(A, 0)) + rd = _row_pairs(outs, self.order, A) + fd = self._fd(self.fib) + ns = len(self.fib.static) + satdeg = int(fd[ns]) + pins = [int(x) for x in fd[ns + 1 : ns + 1 + len(s.pins)]] + starts = [(num, den) for part in s.parts for v, num, den in part["segs"][0]["x0"] if num] + sdeg = max([1] + [max((sum(m) for m in num), default=0) for num, _ in starts]) + # the starts over the product L of their distinct denominators: deg s' <= deg s (max(1, q) + deg L) + dens = {tuple(sorted(den.items())) for _, den in starts if den and max(sum(m) for m in den) > 0} + dl = sum(max(sum(m) for m, _ in d) for d in dens) + self._degrees = (rd, (sdeg + dl) * (satdeg - 1), pins) + return self._degrees + + def free_degrees(self, free): + """{(r, k): (numerator, denominator degree)} of every row with the jets `free` unknowns of degree one.""" + key = frozenset(free) + if key not in self._free: + s = self.series + A = Atoms() + names = self.fib.allnames + s.given = {tuple(int(x) for x in names[v].split("_")[3:5]): Deg(A, 1) for v in free} + try: + outs = s._outputs([Deg(A, 1) for _ in s.cs], self.order, 0, Deg.const(A, 1), Deg.const(A, 0)) + finally: + s.given = None + self._free[key] = _row_pairs(outs, self.order, A) + return self._free[key] + + +def _row_pairs(outs, order, A): + out = {} + for r, y in enumerate(outs or []): + for k in range(order + 1): + v = y[k][0] if y[k] else None + if v is not None: + out[(r, k)] = (0, 0) if v.c is not None else (v.dn, A.of(v.den)) + return out + + +def _defined_jet(P, n, jkey): + """The jet of highest order in an equation of the model: the jet whose equation it is.""" + js = [(jkey[v], v) for v in _vars(P) if v >= n] + if not js: + return None + top = max(o for o, _ in js) + tops = [v for o, v in js if o == top] + return tops[0] if len(tops) == 1 else None + + +def _jet_orders(fib, n): + out = {} + for i, nm in enumerate(fib.allnames[n:], n): + out[i] = int(nm.rsplit("_", 1)[1]) + return out + + +def claim_bound(unit, raw, E, pins, cut): + """The numerator of eps of the verified pin for the system of the original equations E, with the jets that E reads + without their equation counted as open unknowns: max(D_1, (m + deg s' + 2 delta_x) delta).""" + n = unit.n + jkey = _jet_orders(unit.fib, n) + tags = [t for _, t in raw] + read = {v for j in E for v in _vars(raw[j][0]) if v >= n} + have = {_defined_jet(raw[j][0], n, jkey) for j in E if tags[j][0] == "static"} + free = read - have + fixed = set(pins) | set(cut) + opn = {v for j in E for v in _vars(raw[j][0]) if v < n} - fixed + m = len(opn) + len(free) + rd, ds, pindeg = unit.degrees() + rx = unit.free_degrees(free) + rows = [tags[j][1:] for j in E if tags[j][0] == "row"] + info = {"open": len(opn), "free_jets": len(free), "rows": len(rows)} + if any(r not in rd or r not in rx for r in rows): + return None, info + # f_k = A(x) B(theta) - B(x) A(theta): the free jets enter A(x) and B(x) only + e = [max(rx[r][0] + rd[r][1], rx[r][1] + rd[r][0]) for r in rows] + ex = [max(rx[r]) for r in rows] + npin = [tags[j][1] for j in E if tags[j][0] == "pin"] + e = sorted(e + [pindeg[i] for i in npin if i < len(pindeg)], reverse=True) + ex = sorted(ex + [pindeg[i] for i in npin if i < len(pindeg)], reverse=True) + q = min(m, len(e)) + delta, dx = math.prod(e[:q]), math.prod(ex[:q]) + d1 = math.prod(sorted(e + [1 + ds], reverse=True)[: min(m + 2, len(e) + 1)]) + info["rows"] = len(e) + return max(d1, (m + ds + 2 * dx) * delta), info + + +def _stage(unit, point, truth, tv, pins, p, rng, need_all): + """The claims of one unit at one order modulo p with the coordinates `pins` known: [claim], each {"pinned", + "pins", "cut", "E", "points"}.""" + from .discrete import _stage_points + + n = unit.n + raw = unit.raw(point, p) + if raw is None: + return [] + base = [P for P, _ in raw] + extra_tags = [] + for i in sorted(pins): + base.append({((i, 1),): 1, (): (-truth[i]) % p}) + extra_tags.append(("x", i)) + nraw = len(raw) + sat = [{m: c % p for m, c in f.items()} for f in unit.fib.sat] + S = _System(base, sat, p, n) + S.fix() + S.monomials() + S.fix() + if S.empty: + return [] + claims = [] + newly = [i for i in need_all if i in S.solved and not _vars(S.solved[i][0])] + for i in newly: + if S.solved[i][0].get((), 0) % p == truth[i]: + claims.append( + { + "pinned": [i], + "pins": sorted(pins), + "cut": {}, + "E": _tags(S.prov_of(i), nraw, extra_tags), + "points": 1, + } + ) + if claims: + return claims + keep = sorted({v for P, _ in S.eqs for v in _vars(P)}) + blocks = [] + for idx in _components(keep, [P for P, _ in S.eqs], S.sat): + loc = set(idx) + if not any(i < n for i in loc): + continue + beq = [(P, pr) for P, pr in S.eqs if _vars(P) & loc] + blocks += _local_blocks(beq, loc, tv, need_all, n, p) + [(beq, loc)] + for beq, loc in blocks: + T = _System([], [f for f in S.sat if _vars(f) & loc], p, n) + T.eqs, T.solved = list(beq), {} + T.linear() + if T.empty: + continue + cols = sorted({v for P, _ in T.eqs for v in _vars(P)}, key=lambda v: (v < n, v)) + if any(v not in tv for v in cols): + continue + free, clean = _kernel_structure(_jacobian_rows([P for P, _ in T.eqs], cols, tv, p), len(cols), p) + det = {cols[j] for j in clean} + q = sorted( + {i for i in det if i < n and i in need_all} + | {v for v, (e, _) in T.solved.items() if v < n and v in need_all and _vars(e) <= det} + ) + if not q: + continue + cut = {cols[j]: rng.randint(2, 2**32) for j in free} + if any(v >= n for v in cut): + # a jet in the cut: Theorem 1 cuts the kernel by coordinates + continue + U = _System([], T.sat, p, n) + U.eqs = list(T.eqs) + [({((v, 1),): 1, (): (-x) % p}, frozenset([("c", v)])) for v, x in cut.items()] + U.solved = dict(T.solved) + U.fix(keep=set(q)) + U.linear(keep=set(q)) + U.triangular(keep=set(q)) + if U.empty: + continue + need = set(q) + grown = True + while grown: + grown = False + for v in list(need): + if v in U.solved and not _vars(U.solved[v][0]) <= need: + need |= _vars(U.solved[v][0]) + grown = True + used = {v for P, _ in U.eqs for v in _vars(P)} + keepu = [v for v in sorted(used) if v not in U.solved] + sols, E, ok = [dict()], set(), True + for _sub, sp, tries in _parts(U.eqs, U.sat, keepu, need): + pts = None + for A in tries: + if len(A) > _MAX_PART: + continue + inA = [(P, pr) for P, pr in sp if _vars(P) <= A] + got = _stage_points(unit.fib, A, [P for P, _ in inA], [f for f in U.sat if _vars(f) <= A], p) + if got: + pts, EA = got, set().union(*[pr for _, pr in inA]) + # a part that fixes one of the coordinates sought is enough for a claim + if len(got) == 1 or any(len({pt.get(v) for pt in got}) == 1 for v in need & A if v < n): + break + if not pts or len(sols) * len(pts) > _MAX_POINTS: + ok = False + break + E |= EA + sols = [{**a, **b} for a in sols for b in pts] + if not ok: + continue + one = [] + for i in q: + vs = {S.value(i, s) if i in S.solved else U.value(i, s) for s in sols} + if len(vs) == 1 and None not in vs and next(iter(vs)) % p == truth[i]: + one.append(i) + E |= U.prov_of(i) + if one: + E = _tags(E, nraw, extra_tags) + claims.append( + {"pinned": one, "pins": sorted(pins), "cut": cut, "E": E, "points": len(sols), "largest": len(E)} + ) + return claims + return claims + + +def _tags(E, nraw, extra_tags): + """The provenance as indices of the raw equations and tags of the pins and the cut.""" + out = set() + for j in E: + if isinstance(j, tuple): + out.add(j) + elif j >= nraw: + out.add(extra_tags[j - nraw]) + else: + out.add(j) + return frozenset(out) + + +def _true_values(unit, point, truth, p): + """{variable: value} of the coordinates and jets at the point, modulo p; None where a jet is not fixed.""" + raw = unit.raw(point, p) + if raw is None: + return None + eqs = [P for P, _ in raw] + [{((i, 1),): 1, (): (-truth[i]) % p} for i in range(unit.n)] + S = _System(eqs, [{m: c % p for m, c in f.items()} for f in unit.fib.sat], p, unit.n) + S.fix(keep=set(range(len(unit.fib.allnames)))) + return {v: e.get((), 0) % p for v, (e, _) in S.solved.items() if not _vars(e)} + + +def run(series_parts, coords, positive, limits, log=None, need=None, exact=()): + """{"claims", "pinned", "bound", "bits", "accepted", "why", "premise", "seconds"}: the stages modulo p, the bound + of the list, and the test over Q. `series_parts` are the Series of the units, one segment each; `need` the + indices of the coordinates to pin (all by default), `exact` those pinned before without a random step. A unit + with the attribute `free_starts` reads starts drawn as coordinates; "premise" says an accepted claim rests on + one.""" + t0 = time.monotonic() + out = {"claims": [], "pinned": [], "bound": None, "bits": None, "accepted": [], "why": None} + n = len(coords) + p = PRIMES[0] + rng = session.current().rng("discrete tower", tuple(coords)) + point = {spy.Symbol(c): spy.Integer(rng.randint(2, p - 1)) for c in coords} + truth = {i: int(point[spy.Symbol(c)]) % p for i, c in enumerate(coords)} + cap = 2 * n + goal = set(range(n)) if need is None else set(need) + known = {i: truth[i] for i in exact} + dead = set() + # a unit past the terms at one order is past them at every higher order + large = set() + units = {} + reads = {} + N = 1 + meter = work.Meter("the stage tower", work.CAPS["tower_stages"], "stages") + # the calls of msolve of all stages share one budget of work + with work.shared_work(most=work.cap("tower_work"), what="tower_work of the stage tower") as budget: + while ( + not goal <= set(known) + and N <= cap + and not meter.over + and budget.spent < budget.cap + and len(large) < len(series_parts) + ): + new = {} + for u, s in enumerate(series_parts): + if budget.spent >= budget.cap: + break + key = (u, N, frozenset(i for i in reads.get((u, N), ()) if i in known)) + if u in large or key in dead or (u, N) in dead or ((u, N) in reads and reads[(u, N)] <= set(known)): + continue + if (u, N) not in units: + units[(u, N)] = _Unit(s, N, positive) + unit = units[(u, N)] + if unit.too_large: + large.add(u) + continue + if (u, N) not in reads: + # the coordinates read grow with the order + reads[(u, N)] = {v for P in unit.fib.static for mm in P for v, _ in mm if v < n} + for E_, M_ in unit.fib.outs: + for rows in (E_, M_): + for row in rows: + for P in row: + reads[(u, N)] |= {v for mm in P for v, _ in mm if v < n} + key = (u, N, frozenset(i for i in reads[(u, N)] if i in known)) + need = sorted(reads[(u, N)] - set(known)) + if not need: + continue + tv = _true_values(unit, point, truth, p) + if tv is None: + dead.add(key) + continue + meter.spend(1) + got = _stage(unit, point, truth, tv, dict(known), p, rng, set(need)) + if not got: + dead.add(key) + continue + for c in got: + # a coordinate that a unit before in this round claims already leaves the claim; the list is fixed + # before the point over Q, so the bound sums the claims kept + c["pinned"] = [i for i in c["pinned"] if i not in new] + if not c["pinned"]: + continue + c["unit"], c["order"] = u, N + if log: + log(f"unit {u} order {N}: pinned {[coords[i] for i in c['pinned']]}, {len(c['E'])} equations") + out["claims"].append(c) + new.update({i: truth[i] for i in c["pinned"]}) + if new: + known.update(new) + else: + for k_ in [k_ for k_ in units if k_[1] <= N]: + del units[k_] + N += 1 + out["pinned"] = sorted(known) + out["seconds_modp"] = round(time.monotonic() - t0, 2) + if meter.over: + limits.append(f"the stage tower stopped: {meter.reason()}") + if budget.spent >= budget.cap: + limits.append(f"the stage tower stopped: the calls of msolve reached the cap {budget.what}") + if large and len(large) == len(series_parts) and not goal <= set(known): + limits.append("the stage tower stopped: the equations of every unit have more terms than a count takes") + if not goal <= set(known): + out["why"] = f"the stages modulo p pin {len(goal & set(known))} of {len(goal)} coordinates" + out["seconds"] = round(time.monotonic() - t0, 2) + return out + _verify(out, series_parts, coords, positive, rng, log, goal, exact) + out["seconds"] = round(time.monotonic() - t0, 2) + return out + + +def _verify(out, series_parts, coords, positive, rng, log=None, need=None, exact=()): + """The test over Q of the claims at one integer point drawn after the list, with the bits for the sum of the + bounds of every claim below _VERIFIED_AIM.""" + from .discrete import _MIN_BITS, _VERIFIED_AIM, _VERIFIED_BITS + + n = len(coords) + need = set(range(n)) if need is None else set(need) + p = PRIMES[0] + units = {} + total = 0 + probe = {spy.Symbol(c): spy.Integer(rng.randint(2, p - 1)) for c in coords} + for c in out["claims"]: + key = (c["unit"], c["order"]) + if key not in units: + units[key] = _Unit(series_parts[c["unit"]], c["order"], positive) + unit = units[key] + raw = unit.raw(probe, p) + E = [j for j in c["E"] if not isinstance(j, tuple)] + b, info = claim_bound(unit, raw, E, c["pins"], c["cut"]) + c["bound_numerator"], c["structure"] = b, info + if b is None: + # a row without a degree bound: not counted, not tested, the coordinates stay open + c["bounded"] = False + continue + total += b + if not total: + if need <= set(exact): + out["accepted"], out["bound"], out["premise"] = sorted(exact), 0.0, False + else: + out["why"] = "no claim has a degree bound" + return + bits = max(_MIN_BITS, math.ceil(math.log2(total) - 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["bits"] = bits + pt = {spy.Symbol(x): spy.Integer(rng.randint(1, 2**bits)) for x in coords} + val = {i: Fraction(int(pt[spy.Symbol(x)])) for i, x in enumerate(coords)} + accepted = set(exact) + premise = False + for c in out["claims"]: + if c.get("bounded") is False or not set(c["pins"]) <= accepted: + continue + unit = units[(c["unit"], c["order"])] + t = time.monotonic() + with _long_integers(): + got = _test_q(unit, pt, val, c) + if got: + accepted |= set(c["pinned"]) + c["accepted"] = True + premise = premise or bool(getattr(series_parts[c["unit"]], "free_starts", None)) + if log: + log(f"over Q: unit {c['unit']} order {c['order']} {got} ({time.monotonic() - t:.1f}s)") + out["accepted"] = sorted(accepted) + out["premise"] = premise + if need <= accepted: + out["bound"] = 2.0 ** (math.log2(total) - bits) + else: + out["why"] = f"the test over Q accepts {len(need & accepted)} of {len(need)} coordinates" + + +@contextlib.contextmanager +def _long_integers(): + """Lifts the limit on the digits of int and str conversions, which the systems over Q exceed.""" + get = getattr(sys, "get_int_max_str_digits", None) + if get is None: + yield + return + old = get() + sys.set_int_max_str_digits(0) + try: + yield + finally: + sys.set_int_max_str_digits(old) + + +def _test_q(unit, pt, val, c): + """Whether the system of the original equations of the claim at the integer point has finitely many points over + Q, at least one, and the claimed coordinates have the values of the point on all of them.""" + from .discrete import _stage_points + + n = unit.n + raw = unit.raw(pt, 0) + if raw is None: + return False + eqs = [] + for j in c["E"]: + if not isinstance(j, tuple): + eqs.append(raw[j][0]) + elif j[0] == "x": + eqs.append({((j[1], 1),): 1, (): -val[j[1]]}) + elif j[0] == "c": + eqs.append({((j[1], 1),): 1, (): -Fraction(c["cut"][j[1]])}) + want = set(c["pinned"]) + sat = [dict(f) for f in unit.fib.sat] + for tri in (True, False): + S = _System(eqs, sat, 0, n) + S.fix(keep=want) + S.linear(keep=want) + if tri: + S.triangular(keep=want) + if S.empty: + return False + used = sorted({v for P, _ in S.eqs for v in _vars(P)}) + keep = [v for v in used if v not in S.solved] + sols, ok = [dict()], True + for idx in _components(keep, [P for P, _ in S.eqs], S.sat): + A = set(idx) + if len(A) > _MAX_PART: + ok = False + break + inA = [P for P, _ in S.eqs if _vars(P) & A] + with work.shared_work(): + pts = _stage_points(unit.fib, A, inA, [f for f in S.sat if _vars(f) <= A], 0) + if not pts or len(sols) * len(pts) > _MAX_POINTS: + ok = False + break + sols = [{**a, **{k: Fraction(v) for k, v in b.items()}} for a in sols for b in pts] + if not ok: + continue + for i in want: + vs = {S.value(i, s) for s in sols} if i not in sols[0] else {s[i] for s in sols} + if vs != {val[i]}: + return False + return True + return False diff --git a/src/symident/detection/work.py b/src/symident/detection/work.py index 671df7d..dcc0941 100644 --- a/src/symident/detection/work.py +++ b/src/symident/detection/work.py @@ -99,17 +99,17 @@ def run(cmd, input=None, text=False, memory=None): # the work caps of the global analysis; discrete() sets the public ones for one call (caps()) CAPS = { - # nonzero entries of the matrices of the F4 rounds of one call of msolve, and the unknowns and terms of the input - "msolve_entries": 4 * 10**8, + # the work of the F4 rounds of one call of msolve (f4_work()), and the unknowns and terms of the input + "msolve_work": 10**10, "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_work": 15 * 10**8, "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, + "search_entries": 2 * 10**9, "verified_entries": 2 * 10**8, # terms of a polynomial of the elimination of the states "elimination_terms": 3 * 10**6, @@ -119,6 +119,9 @@ def run(cmd, input=None, text=False, memory=None): "candidates": 20000, # points of the fiber that the reconstruction of the maps solves "map_points": 200, + # stages of the stage tower, one unit at one order each, and the work of F4 of all calls of msolve of the tower + "tower_stages": 2000, + "tower_work": 5 * 10**10, # 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 @@ -165,10 +168,10 @@ def local_caps(**kw): @contextlib.contextmanager def quick_msolve(): - """The short caps of msolve (quick_entries, quick_unknowns, quick_terms) within the block, at most those in + """The short caps of msolve (quick_work, 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")} + **{k: min(cap(k), cap("quick" + k[6:])) for k in ("msolve_work", "msolve_unknowns", "msolve_terms")} ): yield @@ -194,20 +197,88 @@ def msolve_too_large(names, eqs): 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 +@contextlib.contextmanager +def shared_work(factor=2, most=None, what=None): + """The calls of msolve within the block in this thread spend on one meter of `factor` times the cap msolve_work, + or of `most` units, as well, each call within what is left of it and of every meter of an enclosing block: the + calls of one count together.""" + old = getattr(_LOCAL, "shared", None) + most = factor * cap("msolve_work") if most is None else most + what = what or f"of {_num(most)} units of work of F4 together" + _LOCAL.shared = Meter(what, most, "units of work", old) + try: + yield _LOCAL.shared + finally: + _LOCAL.shared = old + + +# the pieces of a round of F4 in the output of msolve -v 2, printed as they are reached: the header "degree, pairs +# selected, pairs" before the symbolic preprocessing, the matrix "rows x columns density%" before the linear algebra, +# then the new elements; a matrix without header is one of the normal forms +_F4 = re.compile( + rb"(?m)^[ \t]*(\d+)[ \t]+(\d+)[ \t]+(\d+)(?:[ \t]+(\d+) x (\d+)[ \t]+[\d.]+%(?:[ \t]+(\d+) new)?)?" + rb"|^[ \t]+(\d+) x (\d+)[ \t]+[\d.]+%" +) + + +def f4_work(text): + """The peak of the work of the F4 rounds in the output `text` of msolve -v 2, in the order the output reaches + each piece: a round with s pairs selected, B elements of the basis before it and c columns costs c (s + B) for + the preprocessing and the linear algebra, charged at the header with the widest matrix so far and at the matrix + with the columns of that matrix, and the update of the pairs after the round the new elements times the pairs of + the next header. + The peak depends on the output alone, not on when it is read.""" + work = peak = 0 + basis = widest = new = 0 + for m in _F4.finditer(text): + if m.group(7): + work += int(m.group(7)) * int(m.group(8)) + peak = max(peak, work) + continue + sel, pairs = int(m.group(2)), int(m.group(3)) + peak = max(peak, work + (sel + basis) * widest) + if not m.group(5): + break + cols = int(m.group(5)) + work += new * pairs + cols * (sel + basis) + widest = max(widest, cols) + peak = max(peak, work) + if not m.group(6): + break + new = int(m.group(6)) + basis += new + return peak + + +# the matrix of a round of F4 or of the normal forms, rows x columns and density _MATRIX = re.compile(rb"(\d+) x (\d+)\s+([\d.]+)%") +def f4_entries(text): + """The nonzero entries of the matrices in the output `text` of msolve -v 2, rows times columns times density.""" + return sum(int(m.group(1)) * int(m.group(2)) * float(m.group(3)) / 100 for m in _MATRIX.finditer(text)) + + 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") + """work.run() of an msolve command, with the address space MSOLVE_MEMORY. The work of the F4 rounds (f4_work()) + counts against the cap msolve_work, and within shared_work() against what is left of that meter: the process + ends at the first piece of the output past it, and the result has returncode 1 and `capped` the reason. The work + of the whole output decides, so the outcome does not depend on when the output is read. `work` holds the work, + `entries` the nonzero entries of the matrices (f4_entries()), which the searches over GF(p) count.""" + shared = getattr(_LOCAL, "shared", None) + most = cap("msolve_work") + m = shared + while m is not None: + if m.cap - m.spent < most: + most, shared_end = m.cap - m.spent, m + m = m.parent + if most < cap("msolve_work"): + if most <= 0: + r = subprocess.CompletedProcess(cmd, 1, "" if text else b"", "" if text else b"") + r.capped, r.work, r.entries, r.shared = f"the calls of msolve reached the cap {shared_end.what}", 0, 0, True + return r out = [] - total, buf, done = 0, b"", 0 + total, buf = 0, b"" # leaving the block closes both pipes and waits for the process with subprocess.Popen( list(cmd) + ["-v", "2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=_limiter(MSOLVE_MEMORY) @@ -221,9 +292,7 @@ def run_msolve(cmd, text=True): 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() + total = f4_work(buf) if total > most: proc.kill() break @@ -235,13 +304,19 @@ def run_msolve(cmd, text=True): stdout, stderr = out[0] if out else b"", buf if text: stdout, stderr = stdout.decode(errors="replace"), stderr.decode(errors="replace") + if shared is not None: + shared.spend(total) + r = subprocess.CompletedProcess(cmd, 1 if total > most else proc.returncode, stdout, stderr) + r.capped, r.shared = None, False 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 + # the shared meter ended the call where what was left of it was below the cap of one call + r.shared = most < cap("msolve_work") + r.capped = ( + f"the calls of msolve reached the cap {shared_end.what}" + if r.shared + else f"msolve reached the cap msolve_work of {int(most):,} units of work of F4" + ) + r.work, r.entries = total, f4_entries(buf) return r diff --git a/src/symident/install.py b/src/symident/install.py index 0620412..e47d025 100644 --- a/src/symident/install.py +++ b/src/symident/install.py @@ -11,8 +11,8 @@ from . import state -MSOLVE_VERSION = "0.10.1" -_TESTED = "0.10." +MSOLVE_VERSION = "0.11.0" +_TESTED = "0.11." _EXE = "msolve.exe" if sys.platform == "win32" else "msolve" diff --git a/src/symident/petab.py b/src/symident/petab.py index ffeb28c..f9e0ae5 100644 --- a/src/symident/petab.py +++ b/src/symident/petab.py @@ -610,7 +610,7 @@ def _retotal(net, trafos, starts): def read_petab(path): - """A :class:`Model` from a PEtab problem. + r"""A :class:`Model` from a PEtab problem. Parameters ---------- @@ -654,7 +654,7 @@ def read_petab(path): A volume that a rate rule changes is a state, one that an assignment rule in time and parameters gives enters with the time derivative of the volume, and a concentration in either is - diluted by :math:`-[x] V'/V`. A volume that an event or a period resets keeps the amount + diluted by :math:`-[x] \dot V / V`. A volume that an event or a period resets keeps the amount of every species in it that the reset does not set. The noise model does not enter, nor does a log transformation of an observable. A placeholder of an observable takes the override from the measurement table; one observable measured with several overrides in an diff --git a/src/symident/reduction/branches.py b/src/symident/reduction/branches.py index 703927c..fff62c5 100644 --- a/src/symident/reduction/branches.py +++ b/src/symident/reduction/branches.py @@ -8,7 +8,7 @@ def _side_text(e): - """`e > 0` as an inequality between its positive and its negative terms, e.g. "k01 > k12".""" + """`e > 0` as an inequality between the positive and the negative terms of e, e.g. "k01 > k12".""" pos, neg = [], [] for t in spy.Add.make_args(spy.expand(e)): (neg if t.could_extract_minus_sign() else pos).append(t) diff --git a/src/symident/report.py b/src/symident/report.py index 4a5e114..be21f6e 100644 --- a/src/symident/report.py +++ b/src/symident/report.py @@ -289,10 +289,12 @@ def global_lines(res, width=None): 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" + else f"{k} values modulo a prime at a random point, without an error bound" + (f" ({cert['count_bound_why']})" if cert.get("count_bound_why") else "") ) out.append(_wrap(text, " ", width)) + for pr in cert.get("premises") or []: + out.append(_wrap(f"under the premise: {pr['text']}", " ", width)) if route: out.append( _wrap( @@ -849,7 +851,7 @@ def red_input_lines(x, width=None): 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 + """The branches of a discrete symmetry: per side of the fixed set the coordinate it solves, the chosen one marked; the boundary once.""" d = x.get("discrete") or {} bs = d.get("branches") or [] diff --git a/src/symident/sym/charts.py b/src/symident/sym/charts.py index 9c388ba..172ebe1 100644 --- a/src/symident/sym/charts.py +++ b/src/symident/sym/charts.py @@ -161,7 +161,7 @@ def sign_chart(f, gs, positive): def one(k, rhs): if any(t in rhs for t in ("max(", "min(", "pmax(", "pmin(", "ifelse(", "Heaviside(")): raise InapplicableError( - "%s: max, min and steps are not analytic; analyze each regime on its own, e.g. through `conditions`" % k + "%s: max, min and steps are not analytic; analyze each regime separately, e.g. through `conditions`" % k ) e = parse(rhs).xreplace(to_pos) if e.atoms(spy.Abs, spy.sign): diff --git a/src/symident/sym/exact.py b/src/symident/sym/exact.py index d940a62..4554818 100644 --- a/src/symident/sym/exact.py +++ b/src/symident/sym/exact.py @@ -362,7 +362,7 @@ def line_event_identities(events, field_from, field_to, states, others=(), skip= """(label, expression) of DE Y_from = nu Y_to + sum nu_j Z_j at E(x), E the event group; or None. Under [Y, F] = lam Y + ..., the flow moves the start along Y up to a factor and the fields `others`, - so an event keeps the argument where its derivative maps Y into the span after it.""" + so an event keeps the argument where the derivative of the argument maps Y into the span after it.""" Yf, Yt = _Field(field_from), _Field(field_to) Zs = [_Field(z) for z in others] E = {} diff --git a/src/symident/sym/recast.py b/src/symident/sym/recast.py index a9f8d29..f61e670 100644 --- a/src/symident/sym/recast.py +++ b/src/symident/sym/recast.py @@ -99,10 +99,10 @@ def pre_state_name(sym): def _series_events(S, ic, ev, chain_of, ln): """`ev` with the states before an event as pre_state() symbols, so that plain names in a value are initial - values as in `ic`, and every exp, log, non-integer power, sin, cos and tan of them as its value at zero gaps - times or plus a series in the _SERIES functions; or {'why': ...}. The value at zero gaps composes the events + values as in `ic`, and every exp, log, non-integer power, sin, cos and tan of them as the value of the term at zero + gaps times or plus a series in the _SERIES functions; or {'why': ...}. The value at zero gaps composes the events from the start of the chain; `ln(r)` is the logarithm of a positive number r. Values marked before stay, and - an event flagged `t0` takes its value at zero gaps. `plain` keeps the value as given, for the symbolic checks.""" + an event flagged `t0` takes the value at zero gaps. `plain` keeps the value as given, for the symbolic checks.""" states = set(S) sym_of = {str(x): x for x in S} out = [list(evs) for evs in ev] @@ -1287,7 +1287,7 @@ def _apply_func_recast(S, per_cond, ev_per, tm_per, taken, chain_of=None, at_res ic_sub = {s: ic[c][str(s)] for s in _func_arg(a).free_symbols & states} u0 = _func_arg(a).xreplace(ic_sub) if isinstance(a, (spy.Pow, spy.log)) and u0.is_number and u0.is_positive is not True: - # the auxiliary state of a power or logarithm divides by its argument, which must not + # the auxiliary state of a power or logarithm divides by the argument, which must not # start at zero or below return { "why": "the argument of %s starts at %s, but a logarithm, fractional power or " diff --git a/src/symident/sym/restforward.py b/src/symident/sym/restforward.py index eba94d1..96d5fb0 100644 --- a/src/symident/sym/restforward.py +++ b/src/symident/sym/restforward.py @@ -2,6 +2,7 @@ import contextlib import contextvars +import copy import sys import sympy as spy @@ -24,6 +25,11 @@ def excluding_rates(names): _excluded.reset(token) +def _divides(pv): + """Whether the rate of `pv` divides the balance: solved from it, the rate would be zero at every draw.""" + return pv.nth(0) == 0 + + def _forward_rate_pick(rhs_by_name, solve_states, param_names, forcings, keep_free=None): """One rate per solve state entering the balance of that state linearly, never from `keep_free`; None if no matching exists.""" @@ -48,7 +54,7 @@ def _forward_rate_pick(rhs_by_name, solve_states, param_names, forcings, keep_fr pv = spy.Poly(f, r) except spy.PolynomialError: continue - if pv.degree() != 1 or r in pv.nth(1).free_symbols: + if pv.degree() != 1 or r in pv.nth(1).free_symbols or _divides(pv): continue coef = pv.nth(1) turnover = s_sym in coef.free_symbols @@ -124,7 +130,7 @@ def _forward_plan_once(rhs_by_name, solve_states, param_names, forcings, keep_fr pv = spy.Poly(polys[s], r) except spy.PolynomialError: continue - if pv.degree() == 1 and r not in pv.nth(1).free_symbols: + if pv.degree() == 1 and r not in pv.nth(1).free_symbols and not _divides(pv): lst.append(str(r)) cand[s] = lst state_set = set(solve_states) @@ -282,6 +288,16 @@ def pick_basis(col_order): _forward_cache: dict = {} +# the plans depend on the balances only: every draw of one resting system shares them +_plan_cache: dict = {} + + +def _memo(key, make): + if key not in _plan_cache: + if len(_plan_cache) >= 256: + _plan_cache.clear() + _plan_cache[key] = make() + return copy.deepcopy(_plan_cache[key]) def _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve=(), held=()): @@ -374,10 +390,24 @@ def solve_forward_modular( (_ps, _ss, _polys, *_r) = _ss_compile(model, state_names, param_names, forcings, linear=False) rhs_by_name = {str(_ss[i]): _polys[i] for i in range(len(_ss))} ss_names = [str(s) for s in _ss if str(s) not in held] - solve_rates = _forward_rate_pick(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) + key = ( + session.current().seed("restforward.basis"), + tuple(model), + tuple(ss_names), + tuple(param_names), + tuple(sorted(forcings)), + tuple(sorted(keep_free)), + ) + + def planned(): + return _memo(("plan", *key), lambda: _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free)) + + solve_rates = _memo( + ("pick", *key), lambda: _forward_rate_pick(rhs_by_name, ss_names, param_names, forcings, keep_free) + ) state_solve = [] if solve_rates is None: - plan = _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) + plan = planned() if plan is None: return {"ok": False, "why": "no complete forward rate matching"} state_solve, solve_rates = plan @@ -385,7 +415,7 @@ def solve_forward_modular( c = _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve, held) if "bad" in c and picked: # the direct pick holds two rates of one product: use the planned matching - plan = _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) + plan = planned() if plan is not None: state_solve, solve_rates = plan c = _forward_compile(model, state_names, param_names, forcings, solve_rates, state_solve, held) @@ -417,7 +447,7 @@ def cvfree(nm): if X is None and picked and not state_solve: # a matching of the direct pick is singular where a sum of balances holds none of the picked rates; # the plan takes a column basis of the coefficient matrix at a random point - plan = _forward_plan(rhs_by_name, ss_names, param_names, forcings, keep_free=keep_free) + plan = planned() if plan is not None and list(plan[1]) != list(solve_rates): return solve_forward_modular( model, diff --git a/src/symident/sym/tape.py b/src/symident/sym/tape.py index ac1df2d..7e0809e 100644 --- a/src/symident/sym/tape.py +++ b/src/symident/sym/tape.py @@ -988,7 +988,7 @@ def _rat(e): paramset |= set(held_param_syms) # held-variable initial-value parameters # coordinates a trafo absorbed stay coordinates paramset |= {local.get(_s(n), spy.Symbol(_s(n))) for n in _as_list(keep_coords)} - # one coordinate per name: a leaf read off a relation by name is the leaf with its assumptions + # one coordinate per name: a leaf read off a relation by name is the leaf with the assumptions on it params = sorted( {_s(x): x for x in sorted(paramset, key=lambda x: (_s(x), bool(x.assumptions0)))}.values(), key=spy.default_sort_key, diff --git a/src/symident/tools/build-msolve.sh b/src/symident/tools/build-msolve.sh index c3112db..bb08a18 100644 --- a/src/symident/tools/build-msolve.sh +++ b/src/symident/tools/build-msolve.sh @@ -4,7 +4,7 @@ set -eu CACHE=${SYMIDENT_LIBS_CACHE:?} -MSOLVE=${SYMIDENT_MSOLVE_VERSION:-0.10.1} +MSOLVE=${SYMIDENT_MSOLVE_VERSION:-0.11.0} GMP=${SYMIDENT_GMP_VERSION:-6.3.0} MPFR=${SYMIDENT_MPFR_VERSION:-4.2.1} FLINT=${SYMIDENT_FLINT_VERSION:-3.3.1} @@ -55,7 +55,23 @@ cat > config.h < src/msolve/msolve-version.h +fi mkdir -p ompstub obj +# OpenMP where the compiler has it, so that msolve -t runs threads; else a stub of one thread +printf '#include \nint main(void) { return omp_get_max_threads() > 0 ? 0 : 1; }\n' > omptest.c +if $CC -fopenmp omptest.c -o omptest >/dev/null 2>&1 && ./omptest; then + OMP=-fopenmp + LOMP=-fopenmp +else + OMP=-Iompstub + LOMP= +fi cat > ompstub/omp.h <<'EOF' #ifndef SYMIDENT_OMP_STUB_H #define SYMIDENT_OMP_STUB_H @@ -70,11 +86,11 @@ static inline double omp_get_wtime(void) { EOF # one translation unit per library; main.c includes libmsolve.c for u in src/usolve/usolve.c src/fglm/fglm_core.c src/neogb/gb.c src/msolve/main.c; do - $CC -O2 -DHAVE_CONFIG_H -I. -Isrc -Iompstub -I"$PREFIX/include" -w \ + $CC -O2 $OMP -DHAVE_CONFIG_H -I. -Isrc -I"$PREFIX/include" -w \ -c "$u" -o "obj/$(basename "$u" .c).o" done # the thread pool of FLINT needs pthread, a library of its own before glibc 2.34 -$CC -pthread obj/main.o obj/gb.o obj/fglm_core.o obj/usolve.o -o "$PREFIX/bin/msolve" \ +$CC -pthread $LOMP obj/main.o obj/gb.o obj/fglm_core.o obj/usolve.o -o "$PREFIX/bin/msolve" \ "$PREFIX/lib/libflint.a" "$PREFIX/lib/libmpfr.a" "$PREFIX/lib/libgmp.a" -lm strip "$PREFIX/bin/msolve" 2>/dev/null || true diff --git a/tests/test_discrete.py b/tests/test_discrete.py index f1a54c0..87659a4 100644 --- a/tests/test_discrete.py +++ b/tests/test_discrete.py @@ -175,11 +175,11 @@ def test_a_block_past_an_eighth_of_the_cap_of_msolve_goes_by_stages(monkeypatch) orig = discrete._block_count def record(*a): - caps.append(work.cap("msolve_entries")) + caps.append(work.cap("msolve_work")) return None if len(caps) == 1 else orig(*a) monkeypatch.setattr(discrete, "_block_count", record) - with work.caps(msolve_entries=800): + with work.caps(msolve_work=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)] @@ -473,7 +473,7 @@ def test_a_fiber_whose_invariants_are_output_functions_is_exact(): 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) + assert cert["count_bound"] is None and "unbounded" not in cert and "proven" in repr(r) def test_a_known_constant_is_a_symbol_of_the_base_field_of_the_exact_count(): @@ -483,6 +483,25 @@ def test_a_known_constant_is_a_symbol_of_the_base_field_of_the_exact_count(): assert cert["complete"] == "exact" and cert["orbit"] == 2 +def test_a_count_of_one_without_a_count_over_q_is_taken_again_with_ten_times_the_cap(monkeypatch): + from symident.detection import discrete, fieldproof, work + + monkeypatch.setattr( + fieldproof, "exact_fiber", lambda *a, **k: {"exact": False, "why": "off", "generators": [], "seconds": 0.0} + ) + orig, caps = discrete.q_count, [] + + def first_fails(fib, pt): + caps.append(work.CAPS["msolve_work"]) + return None if len(caps) == 1 else orig(fib, pt) + + monkeypatch.setattr(discrete, "q_count", first_fails) + m = si.Model({"x": "-k*x"}, {"y": "x"}, trafo={"x": "x0"}) + info = si.detect(m, mode="global", cores=1).info["discrete"] + assert info["count"] == 1 and info["certificate"]["complete"] == "verified" + assert caps[1] == 10 * caps[0] + + def test_a_point_where_the_fiber_leaves_the_domain_counts_none_and_is_not_verified(monkeypatch): from symident.detection import discrete, fieldproof @@ -500,7 +519,7 @@ def at_zero(fib, point): 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 cert["complete"] == "checked" and cert["count_bound"] is None and "unbounded" in cert assert "no finite count over Q at the random integer point" in cert["count_bound_why"] @@ -530,7 +549,7 @@ def test_the_fixed_field_of_a_swap_is_generated_by_the_symmetric_functions(): 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): +def test_a_bezout_number_past_the_bits_of_the_point_leaves_the_count_checked(monkeypatch): from symident.detection import discrete, fieldproof monkeypatch.setattr( @@ -541,7 +560,7 @@ def test_a_bezout_number_past_the_bits_of_the_point_leaves_the_axiom(monkeypatch 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"] + assert cert["complete"] == "checked" and "bits" in cert["count_bound_why"] def test_msolve_output_over_q_is_read_exactly(): @@ -641,6 +660,51 @@ def test_a_leaf_the_output_does_not_fix_leaves_the_count_open(): assert info["certificate"]["complete"] == "open" and "new coordinate" in info["relaxed"]["why"] +def _leaf(name, value): + return {"name": name, "kind": "exp", "value": spy.sympify(value), "absorbs": None} + + +def _direction(gen): + return {"level": "exact", "support": sorted(gen), "generator": gen} + + +def test_a_shift_and_scalings_that_move_the_leaves_affinely_meet_the_starts_in_a_connected_set(): + from symident.detection.relax import affine_on_orbits + + leaves = [_leaf("W1", "exp(-V/k1)"), _leaf("W2", "exp(V/k2)"), _leaf("W3", "exp(V/k3)")] + dirs = [ + _direction({"a1": "a1", "W1": "-W1"}), + _direction({"a2": "a2", "W2": "-W2"}), + _direction({"V": "1", "E": "1"}), + ] + assert affine_on_orbits(dirs, leaves, {}) is None + + +def test_a_rate_that_changes_along_the_orbit_is_not_affine(): + from symident.detection.relax import affine_on_orbits + + leaves = [_leaf("W1", "exp(-V/k1)")] + dirs = [_direction({"k1": "k1", "W1": "-W1"}), _direction({"V": "1", "E": "1"})] + assert "rate" in affine_on_orbits(dirs, leaves, {}) + + +def test_a_condition_monotone_along_the_orbit_meets_the_starts_once(): + from symident.detection.relax import affine_on_orbits, monotone_on_orbits + + leaves = [_leaf("W1", "exp(-1/p)")] + dirs = [_direction({"p": "p", "W1": "-W1", "a": "a"})] + assert affine_on_orbits(dirs, leaves, {}) is not None + assert monotone_on_orbits(dirs, leaves, {}, True) is None + + +def test_a_condition_without_one_sign_along_the_orbit_is_not_monotone(): + from symident.detection.relax import monotone_on_orbits + + leaves = [_leaf("W1", "exp(-1/p)")] + dirs = [_direction({"p": "p", "W1": "W1", "a": "a"})] + assert "one sign" in monotone_on_orbits(dirs, leaves, {}, True) + + 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") @@ -690,6 +754,22 @@ def test_a_coefficient_without_a_sign_on_the_domain_is_a_premise(): _start_power_series({"y": "si_N1 + x"}, positive=["m", "p", "q", "r"]) +def test_a_premise_is_listed_once_and_leaves_the_level_of_the_count(): + from symident.api import _level_rank + from symident.detection.discrete import add_premise + + cert = {"complete": "verified"} + add_premise(cert, "generic_event_state", "the states at the event are generic") + add_premise(cert, "generic_event_state", "the states at the event are generic") + assert cert["complete"] == "verified" + assert cert["premises"] == [{"kind": "generic_event_state", "text": "the states at the event are generic"}] + + def rank(c): + return _level_rank({"info": {"certificate": c}}) + + assert rank({"complete": "verified"}) > rank(cert) > rank({"complete": "checked"}) > rank({"complete": "open"}) + + 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"}) @@ -924,17 +1004,101 @@ def test_resting_balances_past_the_bezout_cap_end_with_a_reason(): ) 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"] + why = r.info["discrete"]["unsupported"] + assert "Bezout number 8 in the states is past the cap rest_bezout of 4" in why + assert "no resting chart" in why -def test_resting_balances_past_the_block_cap_end_with_a_reason(): +def test_resting_balances_past_the_block_cap_exchange_coordinates_for_the_resting_values(): + from symident.detection import work + + tc = {"x1": "p - k21*x1^2 - k01*x1 + k12*x2", "x2": "k21*x1^2 - 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): + r = si.detect(m, equilibrate=True, mode="global", cores=1) + assert sorted(r.info["discrete"]["rest_exchange"]["rest"]) == ["x1", "x2"] + + +def test_a_start_with_a_square_root_is_a_coordinate_in_exchange_for_one_solved_from_it(): + tc = {"x": "-k*x + b", "y": "x - c*y"} + m = si.Model(tc, {"o": "y"}, trafo={"x": "(-b + sqrt(b^2 + 4*k))/(2*k)", "y": "0"}, positive=["k", "b", "c"]) + out = si.detect(m, reconstruct=True).discrete() + rest = out["info"]["rest_exchange"] + assert rest["kind"] == "root" and list(rest["rest"]) == ["x"] and list(rest["exchanged"]) == ["b"] + assert out["info"]["certificate"]["complete"] == "exact" + + +def test_starts_with_roots_of_two_polynomials_end_with_a_reason(): + from symident.detection.restchart import root_chart + + parts = [{"segments": [{"ic": {"x": "sqrt(a)", "y": "sqrt(b)"}}]}] + with pytest.raises(ValueError, match="square root of one polynomial"): + root_chart(parts, ["a", "b"]) + + +def test_a_switch_on_the_clock_is_an_indicator_set_by_an_event(): + from symident.detection.clock import clock_events + + rate = "piecewise(b0, time < t1, piecewise(b1, time < t2, b1))" + f, gs, starts, events = clock_events({"x": f"-{rate}*x"}, [{"y": "x"}], [], ["b0", "b1", "t1", "t2"]) + (ev,) = events + s = ev["var"] + assert ev["time"] == "t1" and ev["value"] == "1" and starts == {s: "0"} and f[s] == "0" + assert same(f["x"], f"-(b0 + (b1 - b0)*{s})*x") + # a threshold that is no positive coordinate and a switch on a state stay switches + assert clock_events({"x": "-piecewise(k, time < c, 1)*x"}, [{"y": "x"}], [], ["k"]) is None + assert clock_events({"x": "-piecewise(k, x < 1, 1)*x"}, [{"y": "x"}], [], ["k"]) is None + # an interval of the clock is a product of indicators, a comparison linear in the clock a threshold + f, _, _, events = clock_events({"x": "piecewise(a, (time > 4) & (time <= 22), 0) - x"}, [{"y": "x"}], [], True) + on = {e["time"]: e["var"] for e in events} + assert same(f["x"], f"a*{on['4']}*(1 - {on['22']}) - x") + assert clock_events({"x": "piecewise(0, (time - 3/2) < 0, 1)"}, [{"y": "x"}], [], True)[3][0]["time"] == "3/2" + # a switch between equal pieces needs no indicator, whatever the threshold + assert clock_events({"x": "-piecewise(k, time < c, k)*x"}, [{"y": "x"}], [], ["k"])[3] == [] + + +def test_a_switch_at_a_coordinate_time_is_counted_through_the_event(): + f = {"x": "-piecewise(k1, time < tau, k2)*x"} + m = si.Model(f, {"y": "x"}, trafo={"x": "a"}, positive=["k1", "k2", "tau", "a"]) + out = si.detect(m, reconstruct=True).discrete() + assert out["info"]["count"] == 1 and out["symmetries"] == [] + + +def test_resting_balances_without_a_linear_coordinate_end_with_a_reason(): + from symident.detection import discrete, work + + f = {"x1": "p^2 - k*x1^2 + x2", "x2": "k^2*x1^2 - x2^2", "u": "0"} + with work.caps(rest_block=1), pytest.raises(ValueError, match="enter the balances of x1, x2 linearly"): + discrete.resting_exchange(f, {}, ["u"], {"p", "k"}, {}) + + +def test_linear_resting_balances_are_solved_past_the_block_cap(): + from symident.detection import discrete, work + + f = {"x1": "p - (k21 + k01)*x1 + k12*x2", "x2": "k21*x1 - k12*x2", "x3": "k32*x2 - k03*x3", "u": "0"} + with work.caps(rest_block=1): + rest = discrete.resting_start(f, {}, ["u"], {"p", "k21", "k01", "k12", "k32", "k03"}) + p, k01, k12, k21, k32, k03 = spy.symbols("p k01 k12 k21 k32 k03") + want = {"x1": p / k01, "x2": k21 * p / (k01 * k12), "x3": k32 * k21 * p / (k01 * k12 * k03)} + assert all(spy.cancel(spy.sympify(rest[x]) - v) == 0 for x, v in want.items()) + + +def test_linear_resting_balances_with_a_singular_matrix_are_left_to_the_solver(): + from symident.detection import discrete + + x, y, k = spy.symbols("x y k") + assert discrete._linear_rest([k * x - k * y, k * y - k * x], [x, y]) is None + assert discrete._linear_rest([k - x**2, y - x], [x, y]) is None + + +def test_the_global_analysis_runs_on_linear_balances_past_the_block_cap(): 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"): + with work.caps(rest_block=1): 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"] + assert not r.info["discrete"].get("unsupported") def test_a_transcendental_balance_at_rest_is_named_without_a_search(): @@ -1014,11 +1178,11 @@ def test_msolve_ends_at_the_cap_on_the_entries_of_its_matrices(): 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): + with work.caps(msolve_work=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 "msolve reached the cap msolve_work of 1 units of work of F4" in why + with work.local_caps(msolve_work=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 @@ -1057,8 +1221,12 @@ def test_the_orders_of_the_count_rise_a_fixed_number_of_times(monkeypatch): 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 + # each observable starts one order above the order of the observable in the rank criterion; the orders rise together + assert given[:2] == [[2, 4], [3, 5]] and len(given) == discrete._ORDER_RAISES + 1 + given.clear() + discrete.choose_order(series, True, 1, 20, lowest=False) + # without lowest, one above the highest order of the rank criterion + assert given[:2] == [[4, 4], [5, 5]] def test_a_count_past_the_caps_of_msolve_ends_the_rise_of_the_orders(monkeypatch): @@ -1077,7 +1245,7 @@ def count(fib, point, p): ) 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]] + assert discrete.choose_order(series, True, 1, 20)[2] is None and given == [[2, 4]] def test_a_count_that_msolve_ends_out_of_memory_is_named_so(monkeypatch): @@ -1416,3 +1584,73 @@ def test_a_result_of_reduce_cq_is_counted_on_the_level_sets_of_the_totals(): 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" + + +def test_the_global_analysis_of_a_model_without_shared_columns_ends_with_a_reason(): + tc = {"x1": "p - k21*x1*x2 - k01*x1 + k12*x2", "x2": "k21*x1*x2 - k12*x2"} + m = si.Model(tc, {"y": "x2"}, events=[{"var": "x1", "time": 1, "value": "D", "method": "add"}], fixed=["D"]) + with pytest.warns(UserWarning, match="global analysis not done"): + r = si.detect(m, equilibrate=True, mode="global", cores=1) + assert "resting state" in r.info["discrete"]["unsupported"] + + +def test_the_calls_of_msolve_of_one_count_share_twice_the_cap_of_one_call(tmp_path): + from symident.detection import work + + fi = tmp_path / "in.ms" + fi.write_text("x,y,z\n65521\nx^3+y^2+z-1,\nx*y*z-2,\nx^2-y^2+z^3-3\n") + cmd = [_msolve_binary(), "-f", str(fi), "-o", str(tmp_path / "out.ms")] + with work.caps(msolve_work=10), work.shared_work() as meter: + first = work.run_msolve(cmd) + second = work.run_msolve(cmd) + third = work.run_msolve(cmd) + # one call past the cap of a call, the next past the shared meter, and none starts after it + assert first.capped and not first.shared + assert second.shared and "together" in second.capped and meter.over + assert third.shared and third.work == 0 + + +def test_the_work_of_f4_is_charged_at_the_header_before_the_matrix_is_printed(): + from symident.detection import work + + rounds = ( + b" 1 1 202 3 x 30 38.89% 1 new 0 zero 0.00 | 0.00\n" + b" 2 29 201 50 x 149 5.76% 29 new 0 zero 0.00 | 0.00\n" + ) + done = 30 * 1 + (201 * 1 + 149 * (29 + 1)) + assert work.f4_work(rounds) == done + # a header whose preprocessing has not ended is charged with the widest matrix so far + stalled = rounds + b" 3 150 271" + assert work.f4_work(stalled) == done + 149 * (150 + 30) + # a matrix of the normal forms has no header + assert work.f4_work(rounds + b"normal forms\n 18 x 25 9.33% 8 new") == done + 18 * 25 + + +def test_leaves_with_a_coordinate_of_their_own_are_independent(): + import sympy as spy + + from symident.detection.relax import private_leaves + + b, c, n1, n2, a = spy.symbols("b c n1 n2 a") + leaves = [{"value": (b / (1 + c)) ** n1}, {"value": c**n2}, {"value": spy.exp(a * b)}] + assert private_leaves(leaves, ["a", "b", "c", "n1", "n2"]) + # one exponent in two leaves + assert not private_leaves([{"value": b**n1}, {"value": c**n1}], ["b", "c", "n1"]) + + +def test_a_product_of_three_states_is_a_chain_of_product_jets_with_the_same_count(monkeypatch): + from symident.detection.discrete import PRIMES, Fiber, Series, complex_count + + seg = {"f": {"x": "a - k*x^2*z", "z": "-c*z"}, "g": {"y1": "x", "y2": "z"}, "ic": {"x": "x0", "z": "z0"}, "t": "0"} + + def fiber(): + return Fiber(Series([{"segments": [seg]}], ["a", "c", "k", "x0", "z0"], True), 4) + + point = {spy.Symbol(c): spy.Integer(v) for c, v in zip(["a", "c", "k", "x0", "z0"], (3, 5, 7, 2, 11))} + fib = fiber() + assert any(n.startswith("si_q") for n in fib.allnames) + n = complex_count(fib, point, PRIMES[0]) + monkeypatch.setattr(Series, "_product_nodes", lambda self, pi, orders, need: {}) + plain = fiber() + assert not any(n_.startswith("si_q") for n_ in plain.allnames) + assert n is not None and complex_count(plain, point, PRIMES[0]) == n diff --git a/tests/test_exact.py b/tests/test_exact.py index 3c56d87..4d217da 100644 --- a/tests/test_exact.py +++ b/tests/test_exact.py @@ -702,3 +702,47 @@ def test_an_unknown_input_under_a_log_chart_and_free_powers_is_exact(): reconstruct=True, ) assert r.info["rank_status"]["status"] == "proven" and [s.level for s in r.symmetries] == ["exact"] * 6 + + +def test_the_determinant_of_the_elimination_is_the_expansion_within_the_term_cap(): + import flint + + from symident.detection import elim + + ctx = flint.fmpz_mpoly_ctx.get(("a", "b", "c"), "lex") + a, b, c = ctx.gens() + one = ctx.from_dict({(0, 0, 0): 1}) + M = [[a + b, c, one], [b, a + c, b], [one, c, a + b + c]] + want = (a + b) * ((a + c) * (a + b + c) - b * c) - c * (b * (a + b + c) - b) + (b * c - (a + c)) + assert elim._det(M) == want + assert elim._det(M, 10**6) == want + with pytest.raises(ValueError, match="the cap elimination_terms"): + elim._det(M, 5) + + +def test_a_product_in_the_jets_past_the_term_products_is_not_formed(monkeypatch): + import sympy as spy + + from symident.detection import ioproj + + R, x, y = spy.ring("x,y", spy.QQ) + a, b = (1 + x + y) ** 3, (1 - x) ** 2 + assert ioproj._mul(a, b) == a * b + monkeypatch.setattr(ioproj, "_JET_PRODUCTS", len(a) * len(b) - 1) + with pytest.raises(ioproj.JetTooLargeError): + ioproj._mul(a, b) + + +def test_a_monomial_of_the_base_functions_past_the_term_products_is_not_formed(monkeypatch): + import flint + + from symident.detection import ioproj + + ctx = flint.fmpq_mpoly_ctx.get(("x", "y"), "degrevlex") + x, y = ctx.gens() + J = type("J", (), {"R": ctx, "one": ctx.constant(1)})() + base = [ioproj.Quo(1 + x + y, []), ioproj.Quo(1 - x, [])] + assert ioproj.products(J, base, [(2, 1)])[0].numer == (1 + x + y) ** 2 * (1 - x) + monkeypatch.setattr(ioproj, "_JET_PRODUCTS", 8) + with pytest.raises(ioproj.JetTooLargeError): + ioproj.products(J, base, [(2, 1)]) diff --git a/tests/test_experiments.py b/tests/test_experiments.py index 8dd3cc9..f4edfca 100644 --- a/tests/test_experiments.py +++ b/tests/test_experiments.py @@ -155,7 +155,7 @@ def test_two_compartments_count_their_swap_on_several_experiments(): 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 cert["complete"] in ("verified", "checked") 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) @@ -204,3 +204,18 @@ def test_two_experiments_on_one_level_set_count_a_globally_identifiable_exchange 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"] + + +def test_a_fixed_start_next_to_a_coordinate_it_scales_becomes_a_free_start(): + from symident.detection.discrete import Series + from symident.detection.multiexp import absorbed_starts, eligible + + seg = {"f": {"x": "a - b*x", "nu": "-k*nu*x"}, "g": {"y": "W*nu", "z": "x"}, "ic": {"x": "x0", "nu": "1"}, "t": "0"} + coords = ["a", "b", "k", "W", "x0"] + parts = [{"segments": [seg]}] + assert eligible(Series(parts, coords, True))[1].startswith("the start of nu is fixed") + absorbed, new = absorbed_starts(parts, coords) + assert absorbed == {"nu": ("si_Z1", "W")} + s2 = new[0]["segments"][0] + assert s2["ic"] == {"x": "x0", "si_Z1": "W"} and s2["g"]["y"] == "si_Z1" + assert "W" not in s2["f"]["si_Z1"] and eligible(Series(new, coords, True))[1] is None diff --git a/tests/test_install.py b/tests/test_install.py index 53fead7..0be8aa9 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -15,7 +15,7 @@ posix_only = pytest.mark.skipif(sys.platform == "win32", reason="runs a shell script") -def fake_msolve(path, version="0.10.1", answer=GOOD): +def fake_msolve(path, version=install.MSOLVE_VERSION, answer=GOOD): # a script that answers the test system of msolve_check and reports `version` os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as fh: @@ -55,7 +55,7 @@ def test_cache_dir_per_platform(monkeypatch): def test_msolve_check(tmp_path): assert install.msolve_check(None) is None assert install.msolve_check(str(tmp_path / "missing")) is None - assert install.msolve_check(fake_msolve(str(tmp_path / "a" / "msolve"))) == "0.10.1" + assert install.msolve_check(fake_msolve(str(tmp_path / "a" / "msolve"))) == install.MSOLVE_VERSION assert install.msolve_check(fake_msolve(str(tmp_path / "b" / "msolve"), answer="[1]")) is None @@ -73,7 +73,7 @@ def test_find_msolve_order(monkeypatch, tmp_path): for v in ("0.9.9", "0.10.1"): fake_msolve(str(cache / f"deps-msolve-{v}" / "bin" / "msolve")) (cache / f"deps-msolve-{v}" / ".msolve-complete").touch() - fake_msolve(str(cache / "deps-msolve-0.11.0" / "bin" / "msolve")) + fake_msolve(str(cache / "deps-msolve-99.0.0" / "bin" / "msolve")) assert install.find_msolve() == (str(cache / "deps-msolve-0.10.1" / "bin" / "msolve"), "cache") env = fake_msolve(str(tmp_path / "env" / "msolve")) monkeypatch.setenv("SYMIDENT_MSOLVE", env) @@ -140,7 +140,7 @@ def test_install_msolve_builds_into_the_cache(monkeypatch, tmp_path, capsys): stub_build(monkeypatch) monkeypatch.setattr("builtins.input", lambda prompt: "") path = install.install_msolve(ask=True, jobs=2) - expected = str(tmp_path / "cache" / "deps-msolve-0.10.1" / "bin" / "msolve") + expected = str(tmp_path / "cache" / f"deps-msolve-{install.MSOLVE_VERSION}" / "bin" / "msolve") assert path == expected assert "msolve installed in" in capsys.readouterr().out assert install.find_msolve() == (expected, "cache") diff --git a/tests/test_projections.py b/tests/test_projections.py index 16480e5..05de6da 100644 --- a/tests/test_projections.py +++ b/tests/test_projections.py @@ -73,6 +73,26 @@ def ev(c, t): 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_rational_reconstruction_per_column_is_that_of_one_variable(): + p = all_primes()[0] + rng = random.Random(3) + ts = list(range(1, 21)) + + def ev(c, t): + return sum(x * pow(t, k, p) for k, x in enumerate(c)) % p + + cols = [] + for dn, dd in [(3, 2), (0, 0), (12, 9), (5, 0), (0, 4)]: + N = [rng.randrange(1, p) for _ in range(dn + 1)] + D = [rng.randrange(1, p) for _ in range(dd)] + [1] + cols.append([ev(N, t) * pow(ev(D, t), -1, p) % p for t in ts]) + cols.append([0] * len(ts)) + V = np.array(cols, dtype=np.int64).T + got = [None if g is None else (list(g[0]), list(g[1])) for g in ioproj.ratrec_columns(ts, V, p)] + assert got == [ioproj.ratrec1(ts, [int(x) for x in V[:, e]], p) for e in range(V.shape[1])] + assert got[2] is None and got[5] == ([], [1]) + + 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} @@ -388,3 +408,72 @@ def test_the_exact_search_ends_at_its_cap_on_entries_with_the_cap_named(monkeypa assert out["why"].endswith( "before the end of the search: the search reached the cap search_entries of 0 entries of the matrices reduced" ) + + +def test_the_base_functions_at_a_point_are_those_of_the_symbolic_jets(monkeypatch): + # rational right-hand sides and observables: the Taylor coefficients of the trajectory from the point give the + # derivatives along the flow that the jets give as quotients + m = si.Model({"x": "(a - b*x)/(1 + z)", "z": "-c*z*x"}, {"y": "x/(1 + z)", "w": "z"}, trafo={"x": "x0", "z": "z0"}) + args, _ = _captured(m, monkeypatch) + series, syms = args[0], args[3] + fieldproof._REL.clear() + rel = fieldproof._relations(series, syms) + p = all_primes()[0] + rng = random.Random(3) + base = ioproj.Base(rel, [3, 2]) + pts = np.array([[rng.randrange(1, p) for _ in rel.names] for _ in range(5)], dtype=np.int64) + ok, got = base.values(pts, p) + funcs, J = base.funcs, base.J + num = ioproj._Polys([q.numer for q in funcs] + list(J.fac), len(rel.names))(pts, p) + want = [] + for row in num[ok]: + vals = [] + for v, q in enumerate(funcs): + den = 1 + for k, e in q.exps: + den = den * pow(int(row[len(funcs) + k]), e, p) % p + vals.append(int(row[v]) * pow(den, -1, p) % p) + want.append(vals) + assert ok.all() and base.nb == len(funcs) == 7 and got.tolist() == want + + +def test_a_substitution_of_the_elimination_is_the_polynomial_over_a_power_of_the_denominator(): + import flint + + from symident.detection.elim import _subst + + ctx = flint.fmpz_mpoly_ctx.get(("x", "a", "b"), "lex") + x, a, b = ctx.gens() + P = 3 * x**2 + a * x + b + # x -> (a x - b) / a, times a^2 + assert _subst(P, 0, a * x - b, a) == 3 * (a * x - b) ** 2 + a * (a * x - b) * a + b * a**2 + + +def _input_model(**kw): + return si.Model({"x1": "-a*x1 + x2*u", "x2": "-c*x2"}, {"y": "x1"}, known_inputs=["u"], **kw) + + +def test_the_saturation_adds_the_input_coefficient_of_a_lie_derivative(monkeypatch): + import sympy as spy + + args, _ = _captured(_input_model(), monkeypatch) + fieldproof._REL.clear() + rel = fieldproof._relations(args[0], args[3]) + new = fieldproof.saturated(rel) + x2 = spy.Symbol("x2") + extra = [spy.sympify(str(q.as_expr())) for q in new.y[len(rel.y) :]] + assert any(spy.cancel(e / x2).is_number for e in extra) + + +def test_the_saturation_leaves_a_fixed_start_alone(monkeypatch): + args, _ = _captured(_input_model(trafo={"x2": "1"}), monkeypatch) + fieldproof._REL.clear() + rel = fieldproof._relations(args[0], args[3]) + assert fieldproof.saturated(rel) is rel + + +def test_the_saturation_leaves_a_start_that_enters_the_equations_alone(monkeypatch): + args, _ = _captured(_input_model(trafo={"x2": "c"}), monkeypatch) + fieldproof._REL.clear() + rel = fieldproof._relations(args[0], args[3]) + assert fieldproof.saturated(rel) is rel diff --git a/tests/test_rest_start.py b/tests/test_rest_start.py index c564213..faf53da 100644 --- a/tests/test_rest_start.py +++ b/tests/test_rest_start.py @@ -51,6 +51,20 @@ def test_forward_seed_with_a_pool_of_a_total(): assert int(spy.sympify(line.split("=", 1)[1]).subs(vals)) % P == 0 +def test_a_rate_that_divides_a_balance_is_never_solved_for(): + model = ["x1 = a - b*x1", "x2 = k*(x1 - x2)"] + rng = random.Random(2) + sv = {s: rng.randrange(2, P) for s in ("x1", "x2")} + pv = {q: rng.randrange(2, P) for q in ("a", "b", "k")} + r = solve_forward_modular(model, ["x1", "x2"], ["a", "b", "k"], sv, pv, P) + assert r["ok"], r.get("why") + assert "k" not in r["solve_rates"] + assert all(v % P for v in r["rates"].values()) + vals = {spy.Symbol(n): v for n, v in {**pv, **sv, **r["rates"], **r["val_by"]}.items()} + for line in model: + assert int(spy.sympify(line.split("=", 1)[1]).subs(vals)) % P == 0 + + def test_diagonal_start_keeps_the_rates_of_states_at_zero(): ctrl = ["m = kt - kd*m", "r = kl*m - kdr*r", "s = kb - ks*s"] knd = ["m = kt - kdK*m", "r = kl*m - kdr*r", "s = kb - ks*s"] diff --git a/tests/test_tower.py b/tests/test_tower.py new file mode 100644 index 0000000..418d412 --- /dev/null +++ b/tests/test_tower.py @@ -0,0 +1,183 @@ +"""The stage tower: conditions alone, pins passed on, claims tested over Q.""" + +from fractions import Fraction + +import pytest +import sympy as spy + +from symident.detection import discrete, tower +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 _part(f, g, ic): + return {"segments": [{"f": f, "g": g, "ic": ic, "t": "0", "label": ""}]} + + +def _units(parts, coords): + return [discrete.Series([p], coords, True) for p in parts] + + +def test_a_coordinate_of_one_condition_is_a_pin_of_the_next(): + coords = ["a", "k", "p"] + parts = [ + _part({"x": "-k*x"}, {"y": "x"}, {"x": "a"}), + _part({"x": "-k*x + p*x^2"}, {"y": "x"}, {"x": "1"}), + ] + out = tower.run(_units(parts, coords), coords, True, []) + assert out["pinned"] == [0, 1, 2] + assert out["accepted"] == [0, 1, 2] + assert out["bound"] is not None and out["bound"] < 1e-6 + last = out["claims"][-1] + assert last["unit"] == 1 and coords.index("k") in last["pins"] + + +def test_a_start_with_a_denominator_is_staged_with_the_denominator_in_the_saturation(): + coords = ["a", "k"] + parts = [_part({"x": "-k*x"}, {"y": "x"}, {"x": "a/(1 + k)"})] + units = _units(parts, coords) + assert tower.applies(units[0]) is None + out = tower.run(units, coords, True, []) + assert out["pinned"] == [0, 1] and out["accepted"] == [0, 1] + assert out["bound"] is not None and out["bound"] < 1e-6 + + +def test_a_coordinate_read_at_a_higher_order_is_staged(): + coords = ["c", "k"] + parts = [_part({"x": "-k*x + z", "z": "c*w", "w": "x"}, {"y": "x"}, {"x": "1", "z": "0", "w": "0"})] + out = tower.run(_units(parts, coords), coords, True, []) + assert out["pinned"] == [0, 1] + assert out["accepted"] == [0, 1] + + +def test_a_scaling_leaves_the_coordinates_open(): + coords = ["a", "c", "k"] + parts = [_part({"x": "-k*x"}, {"y": "c*x"}, {"x": "a"})] + out = tower.run(_units(parts, coords), coords, True, []) + assert coords.index("k") in out["pinned"] + assert len(out["pinned"]) < 3 and out["bound"] is None + + +def _test_claim(f, ic, coords, values, claimed, cut=None, order=1): + """The test over Q of a claim on the whole system of one condition, with `cut` {coordinate: value}.""" + unit = tower._Unit(discrete.Series([_part(f, {"y": "x"}, ic)], coords, True), order, True) + pt = {spy.Symbol(x): spy.Integer(v) for x, v in zip(coords, values)} + val = {i: Fraction(v) for i, v in enumerate(values)} + cut = {coords.index(x): v for x, v in (cut or {}).items()} + claim = { + "E": list(range(len(unit.raw(pt, 0)))) + [("c", v) for v in cut], + "pinned": [coords.index(claimed)], + "pins": [], + "cut": cut, + } + return tower._test_q(unit, pt, val, claim) + + +def test_the_test_over_q_accepts_a_true_claim(): + assert _test_claim({"x": "-k*x"}, {"x": "a"}, ["a", "k"], [3, 5], "k") + + +def test_the_test_over_q_rejects_two_values(): + assert not _test_claim({"x": "-k^2*x"}, {"x": "1"}, ["k"], [3], "k") + + +def test_the_test_over_q_rejects_infinitely_many_points(): + assert not _test_claim({"x": "-k*x"}, {"x": "a*c"}, ["a", "c", "k"], [3, 7, 5], "a") + + +def test_the_test_over_q_rejects_one_value_other_than_the_point(): + assert not _test_claim({"x": "-k*x"}, {"x": "a*c"}, ["a", "c", "k"], [3, 7, 5], "a", cut={"c": 11}) + + +def test_the_first_segment_of_a_condition_with_events_is_a_unit(): + seg = {"f": {"x": "-k*x + p*x^2"}, "g": {"y": "x"}, "ic": {"x": "a"}, "t": "0", "label": ""} + ev = dict(seg, t="5", events=[{"var": "x", "value": "1", "method": "replace"}]) + coords = ["a", "k", "p"] + parts = [{"segments": [seg, ev]}] + out = discrete._tower(parts, coords, discrete.Series(parts, coords, True), True, [], [], {}) + assert out["complete"] and out["accepted"] == [0, 1, 2] + + +def _step(f, ic, t, coords): + seg = {"f": f, "g": {"y": "x"}, "ic": ic, "t": "0", "label": ""} + ev = dict(seg, t=t, events=[{"var": "u", "value": "1", "method": "replace"}]) + parts = [{"segments": [seg, ev]}] + return discrete._tower(parts, coords, discrete.Series(parts, coords, True), True, [], [], {}) + + +def test_a_start_after_an_event_that_is_not_known_rests_on_the_premise(): + out = _step({"x": "-k*x + q*u", "u": "0"}, {"x": "a", "u": "0"}, "5", ["a", "k", "q"]) + assert out["complete"] and out["premise"] + + +def test_a_state_at_rest_before_an_event_keeps_a_known_start(): + out = _step({"x": "-k*x*u", "u": "0"}, {"x": "a", "u": "0"}, "5", ["a", "k"]) + assert out["complete"] and not out["premise"] + + +def test_the_time_of_an_event_is_pinned_by_the_jump_of_the_output(): + out = _step({"x": "-k*x + q*u", "u": "0"}, {"x": "a", "u": "0"}, "tau", ["a", "k", "q", "tau"]) + assert out["jumps"] == ["tau"] and out["complete"] + + +def test_the_calls_of_msolve_of_the_stage_tower_share_one_budget(): + from symident.detection import work + + coords = ["k", "q"] + parts = [_part({"x": "-k*x - k*q*x^2"}, {"y": "x"}, {"x": "1"})] + assert tower.run(_units(parts, coords), coords, True, [])["bound"] is not None + limits = [] + with work.caps(tower_work=1): + out = tower.run(_units(parts, coords), coords, True, limits) + assert out["bound"] is None + assert any("tower_work" in x for x in limits) + + +def test_events_are_outside_the_count_by_stages(): + seg = {"f": {"x": "-k*x"}, "g": {"y": "x"}, "ic": {"x": "a"}, "t": "0", "label": ""} + ev = dict(seg, t="tau", events=[{"var": "x", "value": "1", "method": "add"}]) + series = discrete.Series([{"segments": [seg, ev]}], ["a", "k", "tau"], True) + assert "events" in tower.applies(series) + + +def test_a_coordinate_fixed_by_a_few_equations_gets_a_block_of_those(): + p = discrete.PRIMES[0] + eqs = [ + {((0, 1), (2, 1)): 1, (): -6}, + {((2, 1),): 1, (): -2}, + {((0, 1),): 1, ((1, 1),): 1, ((3, 1),): 1, (): -9}, + ] + beq = [(P, frozenset([j])) for j, P in enumerate(eqs)] + tv = {0: 3, 1: 1, 2: 2, 3: 5} + blocks = tower._local_blocks(beq, {0, 1, 2, 3}, tv, {0, 1}, 2, p) + assert blocks[0] == (beq[:2], {0, 2}) + + +def test_a_unit_past_the_terms_is_not_built_at_higher_orders(monkeypatch): + from symident import state + + built = [] + init = tower._Unit.__init__ + + def counted(self, series, order, positive): + built.append(order) + init(self, series, order, positive) + + monkeypatch.setattr(tower._Unit, "__init__", counted) + coords = ["k", "q"] + parts = [_part({"x": "-k*x - k*q*x^2"}, {"y": "x"}, {"x": "1"})] + limits = [] + with state.switches(FIBER_TERMS=1): + out = tower.run(_units(parts, coords), coords, True, limits) + assert built == [1] and out["bound"] is None + assert any("more terms than a count takes" in x for x in limits)