From 6d575ec2cb99afd777c7030c020460ab71b57e59 Mon Sep 17 00:00:00 2001 From: Simon Beyer <64092903+simonbeyer1@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:37:41 +0100 Subject: [PATCH] feat(detection): curve samples of the resting conditions, with order doubling, peeled scalings and the Lie order certified at resting points drawn forward; symident 0.18.2 Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 30 +++ docs/api.rst | 6 + docs/method/conditions.rst | 20 +- docs/method/local.rst | 7 + docs/method/proofs.rst | 23 ++ pyproject.toml | 2 +- src/symident/__init__.py | 2 +- src/symident/detection/classify.py | 20 +- src/symident/detection/core.py | 40 +++- src/symident/detection/fields.py | 2 + .../detection/observability/analysis.py | 46 +++- src/symident/detection/observability/joint.py | 114 ++++++++- src/symident/detection/observability/proof.py | 8 +- src/symident/detection/observability/rest.py | 218 +++++++++++++++++- src/symident/detection/observability/start.py | 10 + src/symident/options.py | 3 +- src/symident/state.py | 3 + src/symident/sym/restforward.py | 17 ++ tests/test_rest_curve.py | 153 ++++++++++++ tests/test_rest_start.py | 76 ++++++ 20 files changed, 764 insertions(+), 36 deletions(-) create mode 100644 tests/test_rest_curve.py create mode 100644 tests/test_rest_start.py diff --git a/NEWS.md b/NEWS.md index c8a3b9e..d086ed4 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,33 @@ +# symident 0.18.2 + +* Under `equilibrate` with a diagonal start, reconstruction and the kernel checks take curve + samples where a direct solve of the resting balances at a random point needs msolve past short + work limits: a point is reached on a line from a forward seed at Z = 0, each condition lifted as + a power series, and the kernel in the coordinates at eps = 1 is the Padé form of the series + kernel with the state columns eliminated. Every route, relevance probes, lines and checks + included, runs on them without a resting solve at the point or msolve. `SYMIDENT_RESTCURVE` + and `SYMIDENT_NORESTCURVE` force curve samples or direct solves. +* The exact scalings are peeled also on curve samples: the state entries of a tangent are those of + the kernel vector with the same coordinate entries. +* Where a kernel at eps = 1 needs more series coefficients, the curve samples double their order + for the rest of the analysis, at most twice from `gap_order_cap`; past that the point is skipped + and `info["limits"]` says so. +* Under `equilibrate`, the Lie order certificate ranks a continued condition at a resting point drawn + forward on the component of the continuation, also on curve samples, without an error bound; + before, it ranked at the start of the continuation, where the conditions coincide, and could + certify too low a block order. The resting Jacobian is checked at the seed of a lift. +* Under `equilibrate` with a diagonal start, the Lie orders of a continued condition are scanned on + the series instead of ranked at the start of the continuation, and the field proof refuses a + continued resting state with a reason instead of failing on it. +* The forward seed takes a column basis of the rate coefficients where the direct pick of the + turnover rates is singular, as for a pool of a total that no picked rate drains. +* The diagonal start leaves out the parameters the conditions coincide without, which could remove + the only rate of a state that rests at zero and make the resting Jacobian singular. +* Under `equilibrate`, states whose right-hand sides vanish together where all of them are zero, with + a Jacobian on them invertible at generic values, rest at zero, as a single state with a linear + right-hand side does; `info["branches"]` names them and `free_initial` takes another branch. +* The method chapter states the error bound of a check on curve samples. + # symident 0.18.1 * `discrete()` closes the output pipes of every msolve call and the output file of msolve in the diff --git a/docs/api.rst b/docs/api.rst index dd3681e..85689e6 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -82,6 +82,8 @@ Diagnostic output: the reduction solve. ``JOINTDIAG`` the joint resting-state rows. +``CURVEDIAG`` + the lines and kernels at eps = 1 of curve samples. Routes: @@ -95,6 +97,10 @@ Routes: no forward seed of the resting states. ``NODIAG`` no diagonal start: resting conditions continued from the forward one only. +``RESTCURVE`` + curve samples of the resting conditions also where a direct solve is cheap. +``NORESTCURVE`` + direct resting solves for reconstruction and checks, never curve samples. ``NOSHARED`` a tape per condition also where the conditions differ only in the values of symbols. ``NOSELECT`` diff --git a/docs/method/conditions.rst b/docs/method/conditions.rst index 9639832..b47c06d 100644 --- a/docs/method/conditions.rst +++ b/docs/method/conditions.rst @@ -79,7 +79,9 @@ as *conjugate* where the balances have an irreducible eliminant; conjugate roots 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``. +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. **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 @@ -113,6 +115,22 @@ invertible. The rank over the truncated series bounds the generic rank from belo ``info["series_certified"]`` says whether the *series order* is proven sufficient. ``SYMIDENT_NODIAG`` turns the diagonal start off. +**Curve samples.** Where a direct solve of the balances at a random point needs msolve past short +work limits, reconstruction and checks take *curve samples* instead of resting points. A point +:math:`\theta^\ast` is reached on the line :math:`\theta(\varepsilon) = \hat\theta + \varepsilon +(\theta^\ast - \hat\theta)` from a forward seed :math:`\hat z = (\hat\theta, \hat x)` at +:math:`Z = 0`: the seed of :math:`\theta^\ast` itself, whose turnover rates then move along the +line, or an earlier seed that differs from :math:`\theta^\ast` in fewer coordinates. Each +condition is lifted as above, the state columns are eliminated from the series rows, and the +kernel in the coordinates at :math:`\varepsilon = 1`, the kernel at :math:`\theta^\ast`, is the +Padé form of each entry, accepted where the known coefficients determine it with one to spare. +Only :math:`\xi_\theta` is read off: the state components follow from :math:`J_x \xi_{x_N} = +-J_\theta \xi_\theta`. Where an entry has no such form, the series order of the curve samples is +doubled for the rest of the analysis, at most twice from ``gap_order_cap``; past that the point is +skipped like a pole and ``info["limits"]`` says so. The Lie order of a continued condition is +certified at a resting point drawn forward (:ref:`sufficient-lie-order`). ``SYMIDENT_RESTCURVE`` +and ``SYMIDENT_NORESTCURVE`` force curve samples or direct solves. + **Existence of a resting state.** Before the analysis the balances are solved over :math:`\mathbb{Q}` at random rational parameter values. Balances without a complex solution raise an ``InputError``, unless the modular decision below proves a resting state; a warning is given where no real root lies diff --git a/docs/method/local.rst b/docs/method/local.rst index bc5b350..8a322b7 100644 --- a/docs/method/local.rst +++ b/docs/method/local.rst @@ -144,6 +144,13 @@ U\}`, with :math:`U` the smallest subspace for which :math:`F` stays in :math:`U :math:`S`. This covers a start at rest, states that stay at zero, fixed initial values, and linear relations the dynamics keeps. Under ``equilibrate`` :math:`S` is the resting variety of the condition (:ref:`steady-states`). In both cases the rank at the start is taken at the base point. +A continued condition rests at the base point as a power series only and is ranked at a resting +point drawn forward instead: random states and parameters, the turnover rates and the states of +the plan solved from the balances. Such points are generic on one irreducible component of the +resting variety, the closure of the points where the balances are regular in these unknowns. The +continued condition lies on it where the balances are regular in them along the continuation, a +rank over :math:`\mathbb{F}_p((\varepsilon))` that a truncated series can only lower; otherwise the +order is not certified. The draw has no error bound, and ``info["order_bound_why"]`` says so. Where the start does not reach :math:`\rho_S`, e.g., on the level set of a nonlinear conserved quantity, the order stops after a *plateau* of three orders without change of rank (``SYMIDENT_LIEPLATEAU``), and the result says that the Lie order is not proven sufficient. diff --git a/docs/method/proofs.rst b/docs/method/proofs.rst index 60dfdb6..e32e5e6 100644 --- a/docs/method/proofs.rst +++ b/docs/method/proofs.rst @@ -219,6 +219,29 @@ 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. +**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 + +.. math:: + :label: eq-curve-bound + + \Pr\big[\text{a wrong value at } \varepsilon = 1\big] \le + \frac{n_e\, \delta \big(1 + 2 (n - 1)(d - 1)\big)}{p} + +for :math:`n_e` entries read, per check point. ``info["bound"]`` holds no number for checks on +curve samples and names the reason. Proofs over :math:`\mathbb{Q}` that need :math:`J_x` +invertible on the component take the seed, where the lift requires it. + **What the bounds exclude.** The bounds above are probabilities over the points modulo :math:`p`. They exclude the chance that :math:`p` divides the *content* of an integer identity, the greatest common divisor of the coefficients, which then vanishes modulo :math:`p`, or that :math:`p` is diff --git a/pyproject.toml b/pyproject.toml index db5e319..cce4771 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build" [project] name = "symident" -version = "0.18.1" +version = "0.18.2" 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 de07c06..99b4f81 100644 --- a/src/symident/__init__.py +++ b/src/symident/__init__.py @@ -19,4 +19,4 @@ "install_msolve", "switches", ] -__version__ = "0.18.1" +__version__ = "0.18.2" diff --git a/src/symident/detection/classify.py b/src/symident/detection/classify.py index fab383b..d9d7c10 100644 --- a/src/symident/detection/classify.py +++ b/src/symident/detection/classify.py @@ -144,9 +144,21 @@ def report_physical(result, znames, aux_names, sc, nz, P, aux_field, flag_joint= return result -def peel_scalings(scal_res, znames, nz, zval, P, N, modulo=None, shifts=()): +def _completed(t, N, cols, P): + """The vector of the column span of N that agrees with `t` off the columns `cols`, or None.""" + if not N.shape[1]: + return None + known = [i for i in range(len(t)) if i not in set(cols)] + c = _core.sym_solve_mod(np.asarray(N, dtype=np.int64)[known, :] % P, np.asarray(t)[known] % P, P) + if c is None: + return None + return (np.asarray(N, dtype=object) @ np.asarray(c, dtype=object) % P).astype(np.int64) + + +def peel_scalings(scal_res, znames, nz, zval, P, N, modulo=None, shifts=(), unknown=()): """Independent scalings of all conditions with tangent in the nullspace (modulo `modulo`), exact per entry; a - coordinate in `shifts` is translated by the weight.""" + coordinate in `shifts` is translated by the weight. The tangent entries of the coordinates `unknown`, whose values + at the kernel point are not known, are those of the kernel vector that has the other entries.""" scaling = [] Bmat = np.zeros((nz, 0), dtype=np.int64) env = {z: int(v) for z, v in zip(znames, zval)} @@ -180,6 +192,10 @@ def eval_w(w): scale = np.asarray(zval, dtype=np.int64) % P scale[[zi[k] for k in moved]] = 1 tangent = (v * scale) % P + if unknown: + tangent = _completed(tangent, N, [zi[k] for k in unknown if k in zi], P) + if tangent is None: + continue if modulo is not None and N.shape[1]: free, nuis = modulo proj = (N.astype(object) @ tangent[free].astype(object)) % P diff --git a/src/symident/detection/core.py b/src/symident/detection/core.py index cef102d..eefd5f8 100644 --- a/src/symident/detection/core.py +++ b/src/symident/detection/core.py @@ -170,6 +170,37 @@ def vanishes(e): zero.update({spy.Symbol(k): 0 for k in new}) +def _zero_face(fdyn, forcings, known=(), nonzero=()): + """The largest set of states whose right-hand sides all vanish with the set, the inputs and `known` at zero, + with a Jacobian on the set invertible at generic values: an invariant face that rests at zero. States a left + kernel vector of that Jacobian reads, such as those of a conserved total, are left out. None of `nonzero`.""" + import random + + import sympy as spy + + from ..sym.parse import _make_local_parse + + _, parse = _make_local_parse([f"{k} = {v}" for k, v in fdyn.items()]) + rhs = {k: parse(str(v).replace("^", "**")) for k, v in fdyn.items()} + base = {spy.Symbol(u): 0 for u in list(forcings) + list(known)} + face = [k for k in rhs if k not in set(forcings) | set(known) | set(nonzero) and rhs[k] != 0] + rng = random.Random(1) + while face: + at = {**base, **{spy.Symbol(k): 0 for k in face}} + keep = [k for k in face if spy.cancel(spy.together(rhs[k].xreplace(at))) == 0] + if keep != face: + face = keep + continue + J = spy.Matrix([[spy.diff(rhs[k], spy.Symbol(j)).xreplace(at) for j in face] for k in face]) + vals = {x: spy.Integer(rng.randrange(2, 10**6)) for x in J.free_symbols} + left = J.xreplace(vals).T.nullspace() + if not left: + return face + drop = {face[i] for v in left for i in range(len(face)) if v[i] != 0} + face = [k for k in face if k not in drop] + return [] + + def _rest_zeros(fdyn, reactions, forcings, nonzero=()): """The states at zero at rest: those the network and the right-hand sides force, then one per branch, noted; none of `nonzero` (``free_initial``), whose resting value is free.""" @@ -184,7 +215,14 @@ def _rest_zeros(fdyn, reactions, forcings, nonzero=()): forced, open_ = _ode_zeros(fdyn, forcings, zero, nonzero) zero = list(dict.fromkeys(zero + forced)) if not open_: - return zero + face = _zero_face(fdyn, forcings, zero, nonzero) + if face: + session.note( + "branches", + f"the resting states {', '.join(face)}: their right-hand sides vanish where all of them are " + "zero; the result holds for them at zero, `free_initial` takes another branch", + ) + return list(dict.fromkeys(zero + face)) session.note( "branches", f"the resting states {', '.join(open_)}: the right-hand side of {open_[0]} " diff --git a/src/symident/detection/fields.py b/src/symident/detection/fields.py index e2a40b5..7b0f510 100644 --- a/src/symident/detection/fields.py +++ b/src/symident/detection/fields.py @@ -315,6 +315,8 @@ def field_check(setup, V, znames, leaf_names, point, chains, joint): if sol is None: raise RouteError("no resting state at the evaluation point") xs = sol["sol"]["val_by"] + if sol.get("cont"): + raise RouteError("the resting states are a curve sample, not a point") base = dict(leaf_val) base.update({k: int(v) % P for k, v in xs.items()}) state_col = {f"{k}|c{mi + 1}" for k in xs} diff --git a/src/symident/detection/observability/analysis.py b/src/symident/detection/observability/analysis.py index ac53640..dc780bc 100644 --- a/src/symident/detection/observability/analysis.py +++ b/src/symident/detection/observability/analysis.py @@ -610,16 +610,14 @@ def _gap_why(self, sc): "failed": f"no kernel past gap order {run.mtot}", }[stop] - def _cert_segments(self, sc, p=None, tries=24): + def _cert_segments(self, sc, bases=None, p=None, tries=24): """The certificate inputs: chains of tapes, a seed per chain, at rest a start per chain, and the points drawn - for the seeds. At rest and a prime `p` the seeds are resting states solved modulo `p` at the first of `tries` - points uniform modulo `p`, random points of the resting variety, and the starts are those of the base - point.""" + for the seeds. At rest the starts are `bases`; with a prime `p` the seeds are resting states solved modulo `p` + at the first of `tries` points uniform modulo `p`, random points of the resting variety.""" run, sys = self.run, self.sys if self.joint: segs = sys.chains if run.has_gaps else [[run.tapes[ci]] for ci in sys.equil_conds] - sols = [sys.solve_cond(sc["point0"], PRIMES[0], ci) for ci in sys.equil_conds] - base = [None if s0 is None else np.asarray(s0["ptc"], dtype=np.int64) % PRIMES[0] for s0 in sols] + base = list(bases) if p is None: return segs, base, None, 1 n = len(sc["point0"]) @@ -757,14 +755,24 @@ def _certificate(self, sc): """The Lie order per block past which the rank provably stays.""" run = self.run P1, q = PRIMES[0], verify_prime() - degs, why = self._cert_degrees(sc) + bases, drawn = None, False + if self.joint: + got = self.sys.cert_bases(sc["point0"], P1) + if isinstance(got, str): + sc["order_bound_why"] = got + session.note("limits", f"Lie order certificate: {got}; the order is not proven") + return + bases, drawn = got + degs, why = (None, None) if drawn else self._cert_degrees(sc) if degs is not None and any(d is None for d in degs): degs = None # at rest the generic ranks are taken at a random resting point modulo q, where the draws are uniform - segs, seeds, starts, rest_draws = self._cert_segments(sc, q if self.joint and degs is not None else None) + segs, seeds, starts, rest_draws = self._cert_segments(sc, bases, q if self.joint and degs is not None else None) if self.joint and degs is not None and any(s is None for s in seeds): - segs, seeds, starts, rest_draws = self._cert_segments(sc) + segs, seeds, starts, rest_draws = self._cert_segments(sc, bases) degs, why = None, "no resting state modulo the verification prime at the points tried" + if drawn: + why = "a continued condition is ranked at a resting point drawn forward, without an error bound" own_threads = not run.has_gaps and not self.joint threads = run.cores if own_threads else 1 mapf = (lambda f, xs: thread_map(f, xs, run.cores)) if threads == 1 and run.cores > 1 else None @@ -1128,8 +1136,19 @@ def grows(r2): return chosen def _direct_kernel(self, ker_dim): - """The kernel at a point where all conditions solve without continuation.""" + """The kernel at a point where all conditions solve without continuation, or in curve mode the series kernel + at eps = 1, the kernel at the parameters of the point.""" sc, sys, nz = self.sc, self.sys, self.nz + if sys.curve_mode(): + try: + rc = self.kcall4(sc["point0"], PRIMES[0], sc["nt_used"], sc.get("mtot_used") or 0) + except Exception as e: + swallow(e, "curve kernel") + rc = {"ok": False} + if not (ok(rc) and nz - rank_of(rc) == ker_dim): + return False + sc.update(ref=rc, rank=rc["rank"], rank_s=rank_of(rc), pivots=rc["pivots"]) + return True chained = sys.chained if chained: sys.unchain() @@ -1230,9 +1249,16 @@ def lift(w): self.N, modulo=(self.free_cols, self.run.nuis_cols) if self.run.nuis_cols else None, shifts={str(r["L"]) for r in self.recast or [] if not r.get("inverted")}, + unknown=self._curve_states(), ) return peel["scaling"], peel["Bmat"] + def _curve_states(self): + """The state columns in curve mode, whose resting values at the kernel point (eps = 1) are not known.""" + if not self.joint or not self.sys.curve: + return () + return [z for z in self.znames if z in self.zsn or "|c" in z] + def _condition_scalings(self, model_lines, obs_lines, keys, keep, known): """Exact scalings whose state weights differ between the resting conditions, each checked on every tape with the state weights of the condition of the tape; those in the span of `known` are left out.""" diff --git a/src/symident/detection/observability/joint.py b/src/symident/detection/observability/joint.py index ac0b2f1..970af63 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 series order of the curve samples is doubled at most this often where a kernel at eps = 1 needs more coefficients +_CURVE_RAISES = 2 + _IDENT = re.compile(r"[A-Za-z._][A-Za-z0-9._]*") @@ -137,6 +140,7 @@ def __init__(self, run): self.fwd_banned = [n for n in strs(multi.get("exp_atoms")) if n in set(self.solve_param_names)] self.fwd_on = not any(r.get("inverted") for r in self.recast) and not state.env("NOFWDSEED") self.cont_t = max(1, int(run.ctrl["gap_order_cap"])) + self.cont_top = self.cont_t << _CURVE_RAISES n_eq = (max(self.equil_conds) + 1) if self.equil_conds else 0 self.cont_off = [False] * n_eq self.cont_seen = [False] * n_eq @@ -148,6 +152,9 @@ def __init__(self, run): self.fwd_sel = list(range(self.kc)) self.warm_off = False self.diag = self.diagonal_start() + self.curve = None + self.curve_seeds = {} + self.curve_bases = {} self.diag_ref = {} self.chained = False if self.diag is not None and not run.has_gaps: @@ -554,9 +561,17 @@ def cond_obs_all(self, scs, p, Nt, Mtot): return [self.cond_obs(self.equil_conds[mi], scs[mi]["ptc"], p, Nt, Mtot) for mi in range(self.kc)] return self.cond_obs_sel(scs, list(range(self.kc)), p, Nt, Mtot) + def curve_order(self, Mtot): + """The gap order of a kernel: in curve mode that of the continuation, the most coefficients for the Pade + form at eps = 1.""" + return max(int(Mtot), self.cont_t) if self.curve and self.run.has_gaps else int(Mtot) + def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): """The wide kernel at a point: every condition solved, rows stacked and reduced.""" run = self.run + if not rank_only: + Mtot = self.curve_order(Mtot) + own = solve_fn is None if solve_fn is None: solve_fn = self.solve_cond if self.kc > 1 and self.solve_cond(point, p, self.equil_conds[0]) is not None: @@ -584,6 +599,11 @@ def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): return {"ok": False} sblocks.append(b["series"]) blocks.append(b["W"]) + if self.curve and run.has_gaps: + out = self.curve_kernel(sblocks, range(self.nz_wide), Mtot + 1, p) + if out.get("short") and own and self.raise_order(): + return self.kcall(point, p, Nt, Mtot) + return run.modulo_nuisance(out, p) rr = _core.sym_rref_mod(np.vstack(blocks).astype(np.float64), p) res = { "ok": True, @@ -596,6 +616,74 @@ def kcall(self, point, p, Nt, Mtot=0, solve_fn=None, rank_only=False): res = series_stack(res, sblocks, self.nz_wide, Mtot + 1, p, run.cores_call) return run.modulo_nuisance(res, p) + def curve_kernel(self, sblocks, cols, N, p): + """The kernel in curve mode on the columns `cols` (wide indices): the state columns eliminated from the series + rows, the parameter part at eps = 1 by Pade, the state columns as unit rows. The parameter part determines a + kernel vector, the resting Jacobian being invertible on the curve.""" + cols = list(cols) + st = [j for j, c in enumerate(cols) if c >= self.n_shared] + th = [j for j, c in enumerate(cols) if c < self.n_shared] + nth = len(th) + live = [np.asarray(b, dtype=np.int64) for b in sblocks if b is not None] + if not live: + return {"ok": False, "why": "no series rows"} + S = np.vstack(live).reshape(-1, len(cols) * int(N)) % p + R_th, piv_th = np.zeros((0, nth), dtype=np.int64), np.zeros(0, dtype=np.int64) + if nth: + sp = _core.sym_series_project(S, len(cols), int(N), p, st, int(self.run.cores_call)) + QS = np.asarray(sp["Q"], dtype=np.int64).reshape(-1, nth * int(N)) + if QS.shape[0]: + sr = _core.sym_series_rank( + QS, + nth, + int(N), + p, + [], + at_one_below=nth + 1, + cores=int(self.run.cores_call), + row_prec=ints(sp["prec"]), + ) + if state.env("CURVEDIAG"): + print( + f"[curvediag] {int(N)} coefficients, rank {int(sr['rank'])} of {nth}, Pade " + + ("found" if sr.get("R") is not None else "none"), + flush=True, + ) + if sr.get("R") is None: + return {"ok": False, "why": "no kernel at eps = 1", "short": True} + piv_th = np.atleast_1d(sr["pivots"]).astype(np.int64) + R_th = np.asarray(sr["R"], dtype=np.int64).reshape(len(piv_th), nth) + rows = [(j, np.eye(1, len(cols), j, dtype=np.int64)[0]) for j in st] + for i, pc in enumerate(piv_th): + r = np.zeros(len(cols), dtype=np.int64) + r[th] = R_th[i] % p + rows.append((th[int(pc)], r)) + rows.sort(key=lambda x: x[0]) + Rm = np.vstack([r for _, r in rows]) if rows else np.zeros((0, len(cols)), dtype=np.int64) + pv = np.array([c for c, _ in rows], dtype=np.int64) + return { + "ok": True, + "R": Rm, + "pivots": pv, + "rank": len(pv), + "rank_s": len(pv), + "dim": len(cols), + "at_one": True, + } + + def raise_order(self): + """The series order of the curve samples doubled for the rest of the analysis; False at the top, with a + limit noted.""" + if self.cont_t < self.cont_top: + self.cont_t *= 2 + return True + session.note( + "limits", + f"curve samples: a kernel at eps = 1 needs more than {self.cont_top + 1} series coefficients; the point is " + "skipped, a larger gap_order_cap raises them", + ) + return False + def kcall_fwd(self, point, p, Nt, solve_rates): """The wide kernel with the forward solve for the turnover rates.""" return self.kcall(point, p, Nt, self.run.mtot, lambda pt, pp, cc: self.solve_cond_fwd(pt, pp, cc, solve_rates)) @@ -687,7 +775,8 @@ def block_profiles(self): def mk(mi): def f(point, p, Nt): sc0 = self.solve_cond(point, p, self.equil_conds[mi]) - if sc0 is None: + # a continued condition rests at eps = 0 only; the orders are scanned on the series instead + if sc0 is None or sc0.get("cont"): return {"ok": False} return _core.sym_obs_chain_rank_profile( run.chain_tapes(run.chain_groups[run.chain_idx[self.equil_conds[mi]]]), @@ -731,6 +820,7 @@ def embed(o): return o n_p = len(point_list) + mt = self.curve_order(run.mtot) per_cond = [None] * n_p seed_rows, ser_rows, ev_chain, ev_prime = [], [], [], [] for i in range(n_p): @@ -760,8 +850,8 @@ def embed(o): run.n_leaves, run.n_states, self.z_slots_local[loc_sel], - run.exact_nt(Nt, run.mtot), - int(run.mtot), + run.exact_nt(Nt, mt), + int(mt), int(min(run.cores, len(ev_chain))), [run.nt_cap[e] for e in ev_chain] if len(run.nt_cap) == self.kc else [], ser_rows if any(s is not None for s in ser_rows) else None, @@ -790,6 +880,16 @@ def embed(o): out[i] = {"ok": False} elif touch: out[i] = {"ok": True, "touch": hit} + elif self.curve: + cl = list(range(self.nz_wide)) if cols is None else list(cols) + Nb = mt + 1 + sk = [c * Nb + j for c in cl for j in range(Nb)] + out[i] = self.curve_kernel( + [None if S is None else np.asarray(S)[:, sk] for S in sblocks], + cl, + Nb, + prime_vec[i], + ) elif cols is not None: cl = list(cols) rr = _core.sym_rref_mod(np.vstack(blocks)[:, cl].astype(np.float64), prime_vec[i]) @@ -825,6 +925,11 @@ def embed(o): prime_vec[i], run.cores, ) + short = [i for i in range(n_p) if out[i].get("short")] + if short and self.raise_order(): + again = self.chunk([point_list[i] for i in short], [prime_vec[i] for i in short], Nt, cols, conds, touch) + for i, o in zip(short, again): + out[i] = o return out hom_kind = "resting states" @@ -839,6 +944,9 @@ def rest_env(self, point, q): solves of the kernel there; None where a condition does not solve.""" run = self.run env = {} + if self.curve: + # a curve sample has the resting states at eps = 0 only; the entries in them are not checked + return env for mi, ci in enumerate(self.equil_conds): sc0 = self.solve_cond(point, q, ci) if sc0 is None: diff --git a/src/symident/detection/observability/proof.py b/src/symident/detection/observability/proof.py index c21da86..d3bb429 100644 --- a/src/symident/detection/observability/proof.py +++ b/src/symident/detection/observability/proof.py @@ -598,12 +598,10 @@ def moved_setup(an, light): for y in Ssym if sol is not None and run.slot(str(y)) is not None } + # a curve sample rests at the seed of the curve: the parameters are those of the seed + at = sol["ptc"] if sol is not None and sol.get("cont") else an.sc["point0"] bc.update( - { - spy.Symbol(n): spy.Integer(int(an.sc["point0"][run.slot(n)])) - for n in map(str, params) - if run.slot(n) is not None - } + {spy.Symbol(n): spy.Integer(int(at[run.slot(n)])) for n in map(str, params) if run.slot(n) is not None} ) A = spy.Matrix([[spy.diff(n, q) for q in par["params"]] for n in par["eqs"]]) if len(bc) < len(Ssym) + len(params) or not _mod(A.det(), bc, PRIMES[0]): diff --git a/src/symident/detection/observability/rest.py b/src/symident/detection/observability/rest.py index 5f5aacb..b2b4a00 100644 --- a/src/symident/detection/observability/rest.py +++ b/src/symident/detection/observability/rest.py @@ -1,5 +1,6 @@ """Resting states over GF(p): backward and forward solves, continuation and warm-up across worker processes.""" +import contextlib import copy import os import time @@ -97,6 +98,41 @@ def solve_raw(self, p, pv, ci): print(f"[sym] solve cond {ci + 1}, pid {os.getpid()}: {time.monotonic() - t0:.1f}s") return out + def curve_mode(self): + """Whether reconstruction and checks take curves of the resting variety (continued conditions, kernels at + eps = 1) instead of points where every condition is solved directly.""" + if self.curve is None: + self.curve = self._curve_needed() + return self.curve + + def direct_caps(self): + """The short caps of msolve for direct solves in curve mode: a point past them is skipped like a pole.""" + from .. import work + + return work.quick_msolve() if self.curve else contextlib.nullcontext() + + def _curve_needed(self): + """Curves where every resting condition can be continued and a direct solve at a random point needs msolve + past the short caps of msolve; the switches RESTCURVE and NORESTCURVE decide first.""" + if state.env("NORESTCURVE") or not self.equil_conds: + return False + if not all(self.cont_eligible(ci) for ci in self.equil_conds): + return False + if state.env("RESTCURVE"): + return True + from .. import work + + p = PRIMES[0] + point = random_point(self.run.n_leaves, seed=session.current().seed("curve probe") % (1 << 31)) + pv = self.joint_pv(point, p) + reps = {self.model_key[ci]: ci for ci in self.equil_conds} + with work.quick_msolve(): + for ci in reps.values(): + sol = self.solve_raw(p, pv, ci) + if sol is not None and not sol.get("ok") and "cap" in str(sol.get("why", "")): + return True + return False + _ROUTE = ("cont_off", "fwd_on", "fwd_rates", "fwd_banned", "fwd_sel") def route_state(self): @@ -157,9 +193,7 @@ def warm_solves(self, pts, primes, conds=None): if len(jobs) < 2: return t0 = time.monotonic() - res = process_map( - lambda j: self.solve_raw(j["p"], j["pv"], j["ci"]), jobs, min(run.cores, len(jobs)), on_error=lambda j: None - ) + res = process_map(lambda j: self._warm_one(j), jobs, min(run.cores, len(jobs)), on_error=lambda j: None) if run.timing: print( f"[sym] warm fill: {len(jobs)} solve(s), fork x{min(run.cores, len(jobs))}, " @@ -169,6 +203,11 @@ def warm_solves(self, pts, primes, conds=None): if r is not None: self.solve_cache[j["key"]] = r if r.get("ok") else {"ok": False} + def _warm_one(self, job): + """One solve of warm_solves(), under the caps of a direct solve.""" + with self.direct_caps(): + return self.solve_raw(job["p"], job["pv"], job["ci"]) + def _seed(self, point, p, sol, ci, rates=None): """The point with the solved resting states (and rates) in the leaves.""" run = self.run @@ -190,7 +229,7 @@ def _seed(self, point, p, sol, ci, rates=None): def solve_cond(self, point, p, ci): """Condition ci solved at the point (continued where that applies), cached.""" - if self.cont_active(ci) and (self.diag is None or self.base_key(point, p) in self.diag_ref): + if self.cont_active(ci) and (self.diag is None or self.curve or self.base_key(point, p) in self.diag_ref): cr = self.cont_cond(point, p, ci) self.cont_trace(ci, cr is not None) if cr is not None: @@ -204,7 +243,7 @@ def solve_direct(self, point, p, ci): key = self.solve_key(p, pv, ci) sol = self.solve_cache.get(key) if sol is None: - with msolve_threads(self.run.cores_call): + with msolve_threads(self.run.cores_call), self.direct_caps(): sol = self.solve_raw(p, pv, ci) self.solve_cache[key] = {"ok": False} if sol is None or not sol.get("ok") else sol if sol is None or not sol.get("ok"): @@ -223,7 +262,12 @@ def at_check_point(self, sol, p, ci): def rest_jacobian_regular(self, ci, point, q, tries=8): """Whether the resting Jacobian of condition `ci` is invertible at a resting point: the base point modulo the - first engine prime, else the first of `tries` points uniform modulo `q` that solve.""" + first engine prime, else the first of `tries` points uniform modulo `q` that solve; in curve mode the seed of + a lift, which the Newton steps need it invertible at.""" + if self.curve: + sc0 = self.solve_cond(point, PRIMES[0], ci) + if sc0 is not None and sc0.get("cont"): + return True sol = self.solve_direct(point, PRIMES[0], ci) p = PRIMES[0] for k in range(tries + 1): @@ -239,6 +283,99 @@ def rest_jacobian_regular(self, ci, point, q, tries=8): M = np.array([[int(x) % p for x in row] for row in jx], dtype=np.int64) return M.shape[0] == M.shape[1] and int(_core.sym_rref_mod(M.astype(np.float64), p)["rank"]) == M.shape[0] + def forward_rest(self, point, p, ci): + """A resting point of condition `ci` drawn forward: states and parameters from `point`, the turnover rates and + the states of the plan solved from the balances; None where the solve is singular or does not apply.""" + run = self.run + if self.recast or self.l_names: + return None + + def rd(nm): + s = run.slot(nm) + return 0 if s is None else int(point[s]) % p + + zero = set(self.zero_of(ci)) | set(run.equil_zero_states) + sv = {nm: 0 if nm in zero else rd(nm) for nm in self.real_state_names} + for h in self.held_names: + sv[h] = rd(self.held_param_of[h]) + try: + sol = solve_forward_modular( + self.models[ci], + list(self.real_state_names), + list(self.solve_param_names), + sv, + {nm: rd(nm) for nm in self.solve_param_names}, + p, + forcings=self.held_of(ci) or None, + held=self.held_names or None, + ) + except SYMPY_FAILS as exc: + sympy_fail(exc) + return None + except Exception as exc: + swallow(exc, "forward resting point") + return None + if state.env("FWDDIAG") and (sol is None or not sol.get("ok")): + print("[fwddiag] forward resting point:", "error" if sol is None else sol.get("why")) + if sol is None or not sol.get("ok") or any(run.slot(r) is None for r in sol["rates"]): + return None + return self._seed(point, p, sol, ci, rates=sol["rates"]) + + def on_forward_component(self, point, p, ci, fwd): + """Whether condition `ci`, continued to `point`, rests on the component the forward solve of `fwd` parametrizes: + the balances are regular in the unknowns of that solve along the continuation, over GF(p)((eps)).""" + sc0 = self.solve_cond(point, p, ci) + if sc0 is None or not sc0.get("cont"): + return False + sol, fs = sc0["sol"], fwd["sol"] + jx, jt, xcols = sol["df_jx"], sol["df_jt"], list(sol["df_state_cols"]) + cols = [] + for u in fs["state_solve"]: + if u not in xcols: + return False + cols.append([r[xcols.index(u)] for r in jx]) + for r in fs["solve_rates"]: + if r not in jt: + return False + cols.append(jt[r]) + n = len(jx) + if n == 0 or len(cols) != n: + return n == 0 and not cols + N = min(len(x) for col in cols for x in col) + S = np.zeros((n, n * N), dtype=np.int64) + for c, col in enumerate(cols): + for i in range(n): + S[i, c * N : (c + 1) * N] = [int(x) % p for x in col[i][:N]] + return int(_core.sym_series_rank(S, n, N, p, [])["rank"]) == n + + def cert_bases(self, point, p, tries=8): + """(bases, drawn): per resting condition the start of the Lie order certificate, the resting point at `point` + where the condition is solved there, else a resting point drawn forward on the component of the continuation + to `point`; `drawn` whether any is drawn. A string says why there is none.""" + out, drawn = [], False + for ci in self.equil_conds: + sc0 = self.solve_cond(point, p, ci) + if sc0 is None: + return "no resting state at the base point" + if sc0.get("cont") and not self.curve_mode(): + sc0 = self.solve_direct(point, p, ci) or sc0 + if not sc0.get("cont"): + out.append(np.asarray(sc0["ptc"], dtype=np.int64) % p) + continue + fwd = None + for k in range(tries): + pt = uniform_point(len(point), p, session.current().seed("forward certificate point", k)) + fwd = self.forward_rest(pt, p, ci) + if fwd is not None: + break + if fwd is None: + return "a continued condition has no resting point drawn forward" + if not self.on_forward_component(point, p, ci, fwd): + return "a continued condition is not shown to rest on the component of the forward draws" + out.append(np.asarray(fwd["ptc"], dtype=np.int64) % p) + drawn = True + return out, drawn + def rest_system(self, ci, pinned=True): """(balances, states, parameters, linear) of the resting solve of condition `ci`: held pivots as parameters, with `pinned` each split balance replaced by the factor the session pinned.""" @@ -430,6 +567,7 @@ def solve(): if diag.pole({**self.joint_pv(point, p)["param_vals"], **{z: 0 for z in diag.Z}, **x0}, p): return None self.diag_ref[self.base_key(point, p)] = x0 + self._register_base(point, p, x0) return point def cont_eligible(self, ci): @@ -464,16 +602,66 @@ def cont_params(self, ci): base = set(self.model_params[self.fwd_cond]) return [n for n in self.model_params[ci] if n not in base] + def curve_base(self, point, p): + """(moved, x0) in curve mode: a forward seed at Z = 0 with resting states x0 and the parameters off Z that the + line to `point` moves, from their values at the seed; the registered seed that moves the fewest, else the + seed of the point itself, whose rates move. None where no seed applies.""" + key = (p, np.asarray(point[: self.run.n_leaves], dtype=np.int64).tobytes()) + if key in self.curve_seeds: + return self.curve_seeds[key] + jp = self.joint_pv(point, p) + tv, th = jp["param_vals"], tuple((jp["held_vals"] or {}).values()) + best = None + for bv, bh, x0 in self.curve_bases.get(p, ()): + if bh != th: + continue + mv = {n: v for n, v in bv.items() if tv.get(n) != v} + if best is None or len(mv) < len(best[0]): + best = (mv, x0) + if best is None or len(best[0]) > len(self.fwd_rates or ()): + seeded = self.fwd_seed(point, p) + if seeded is not None: + z = set(self.diag.Z) + sv = self.joint_pv(seeded, p)["param_vals"] + mv = {n: v for n, v in sv.items() if n not in z and tv.get(n) != v} + x0 = self.diag_ref.get(self.base_key(seeded, p)) + if x0 is not None and (best is None or len(mv) < len(best[0])): + best = (mv, x0) + if len(self.curve_seeds) > 4000: + self.curve_seeds.clear() + self.curve_seeds[key] = best + return best + + def _register_base(self, point, p, x0): + """A forward seed as a base of curves: the first ones kept, then the latest.""" + jp = self.joint_pv(point, p) + z = set(self.diag.Z) + bases = self.curve_bases.setdefault(p, []) + bases.append( + ({n: v for n, v in jp["param_vals"].items() if n not in z}, tuple((jp["held_vals"] or {}).values()), x0) + ) + if len(bases) > 64: + del bases[8] + def cont_cond(self, point, p, ci): - """Condition ci continued along the parameters of ci from the first condition.""" + """Condition ci continued along the parameters of ci from the first condition; in curve mode a point off the + forward seed is reached on a line from a seed, along Z and the parameters where the two differ.""" run = self.run pv = self.joint_pv(point, p) key = ("cont", self.solve_key(p, pv, ci), self.cont_t) sol = self.solve_cache.get(key) + moved, rest = {}, None + if self.diag is not None: + rest = self.diag_ref.get(self.base_key(point, p)) + if rest is None and self.curve: + cb = self.curve_base(point, p) + if cb is None: + return None + moved, rest = cb + if state.env("CURVEDIAG"): + print(f"[curvediag] line moves {len(moved)} parameters", flush=True) if sol is None: - if self.diag is not None: - rest = self.diag_ref.get(self.base_key(point, p)) - else: + if self.diag is None: ref = self.solve_cond(point, p, self.fwd_cond) rest = None if ref is None else ref["sol"]["val_by"] if rest is None: @@ -482,13 +670,16 @@ def cont_cond(self, point, p, ci): pv0 = dict(pv["param_vals"]) for n in priv: pv0[n] = 0 + pv0.update(moved) + dirs = {n: pv["param_vals"][n] for n in priv} + dirs.update({n: (pv["param_vals"][n] - v) % p for n, v in moved.items()}) try: sol = continue_resting_state( self.models[ci], list(self.real_state_names), list(self.solve_param_names), pv0, - {n: pv["param_vals"][n] for n in priv}, + dirs, rest, p, self.cont_t, @@ -522,6 +713,11 @@ def cont_cond(self, point, p, ci): continue ser[sl, 0] = ptc[sl] % p ptc[sl] = 0 + for nm, v in moved.items(): + sl = run.slot(nm) + if sl is not None: + ser[sl, 0] = (ptc[sl] - v) % p + ptc[sl] = v % p for nm in self.zero_of(ci): sl = run.slot(nm) if sl is not None: diff --git a/src/symident/detection/observability/start.py b/src/symident/detection/observability/start.py index 59aa04d..6d3d335 100644 --- a/src/symident/detection/observability/start.py +++ b/src/symident/detection/observability/start.py @@ -37,6 +37,7 @@ def __init__(self, models, reps, fwd, held_of, candidates, keep=(), cap=12): S = self._closure(Z) diff = self._differences(Z, S) if not diff: + Z = self._pruned(Z, S) # without Z the zero set would be a boundary rest of the actual point self.Z, self.S, self.ok = sorted(Z), S, bool(Z) or not S self.dead = self._dead(Z, S) @@ -54,6 +55,15 @@ def __init__(self, models, reps, fwd, held_of, candidates, keep=(), cap=12): return Z = Z + [best[1]] + def _pruned(self, Z, S): + """Z without the parameters the conditions coincide without, at the same S; at zero such a parameter can + remove the only rate of a state in S and make the resting Jacobian singular.""" + for z in sorted(Z): + rest = [x for x in Z if x != z] + if self._closure(rest) == S and not self._differences(rest, S): + Z = rest + return Z + def _denominators(self): """The distinct denominators of every condition, as polynomials.""" out = {} diff --git a/src/symident/options.py b/src/symident/options.py index e797fd3..7e13783 100644 --- a/src/symident/options.py +++ b/src/symident/options.py @@ -57,7 +57,8 @@ def reconst_control( Numerator and denominator degree of the general sparse rational fit. gap_order_cap : int Highest order of the power series in the time between events; reaching it is an - entry in ``info["limits"]``. + entry in ``info["limits"]``. Curve samples of resting conditions start at this + order and double it, up to four times, where a kernel at eps = 1 needs more. minsupport_cand_cap : int Column subsets searched for directions with small support. perprime_cap : int diff --git a/src/symident/state.py b/src/symident/state.py index f8bbb2a..12995b0 100644 --- a/src/symident/state.py +++ b/src/symident/state.py @@ -77,11 +77,14 @@ def switches(**kw): "STATICDIAG": ("diag", "the static subsystem fields"), "REDDIAG": ("diag", "the reduction solve"), "JOINTDIAG": ("diag", "the joint resting-state rows"), + "CURVEDIAG": ("diag", "the lines and kernels at eps = 1 of curve samples"), "NOFIELDS": ("route", "no invariant-field routes (global symmetries, field proof)"), "NOJET": ("route", "no jet route inside the narrow route"), "NOGROUP": ("route", "no translation groups in the narrow route"), "NOFWDSEED": ("route", "no forward seed of the resting states"), "NODIAG": ("route", "no diagonal start: resting conditions continued from the forward one only"), + "RESTCURVE": ("route", "curve samples of the resting conditions also where a direct solve is cheap"), + "NORESTCURVE": ("route", "direct resting solves for reconstruction and checks, never curve samples"), "NOSHARED": ("route", "a tape per condition also where the conditions differ only in the values of symbols"), "NOSELECT": ("route", "every condition analyzed, also where many conditions add nothing to the rank"), "LIEPLATEAU": ("number", "orders the rank stays flat before the saturation ends (3)"), diff --git a/src/symident/sym/restforward.py b/src/symident/sym/restforward.py index 8ea9389..eba94d1 100644 --- a/src/symident/sym/restforward.py +++ b/src/symident/sym/restforward.py @@ -414,6 +414,23 @@ def cvfree(nm): A = [[_eval_terms(c["coef_t"][i][j], rgv, p) for j in range(n_r)] for i in range(n_r)] b = [[(-_eval_terms(c["const_t"][i], rgv, p)) % p] for i in range(n_r)] X = _solve_mod(A, b, p) + if X is None 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) + if plan is not None and list(plan[1]) != list(solve_rates): + return solve_forward_modular( + model, + state_names, + param_names, + state_vals, + param_vals, + prime, + forcings=sorted(forcings), + solve_rates=plan[1], + state_solve=plan[0], + held=sorted(held), + ) if X is None: return {"ok": False, "why": "singular forward system mod p"} rates_dict = {solve_rates[j]: int(X[j][0]) % p for j in range(len(solve_rates))} diff --git a/tests/test_rest_curve.py b/tests/test_rest_curve.py new file mode 100644 index 0000000..b5ae468 --- /dev/null +++ b/tests/test_rest_curve.py @@ -0,0 +1,153 @@ +"""Curve samples of the resting conditions: forced curve mode closes the same directions as direct resting solves, +peels the exact scalings, and solves no resting condition directly.""" + +import traceback + +import pytest +import sympy as spy + +import symident as si +from symident.detection import work +from symident.detection.observability import rest +from symident.sym.msolve import _msolve_binary + + +def _has_msolve(): + try: + _msolve_binary() + except Exception: + return False + return True + + +pytestmark = pytest.mark.skipif(not _has_msolve(), reason="needs msolve") + +EVENTS = [{"var": "L", "time": 0, "value": "dose", "method": "add"}] +CONDS = {"rows": ["c0", "c1", "o1"], "cols": {"dose": [0, 1, 1], "kt": ["kt", "kt", "ktO"]}} + +# a parallel combination of two rates, a translation, and a resting core of three states that only msolve solves +SERIES = dict( + odes={"Rm": "kt - kd*Rm", "x": "kp*Rm*(1 + L) - b*c/(b + c)*x", "L": "-kq*L"}, + observables={"y1": "s*x", "y2": "Rm"}, +) +CORE = dict( + odes={ + "Rm": "kt - kd*Rm", + "A": "ka*Rm + kl*L - k1*A^2*B^2 - (da1 + da2)*A", + "B": "kb - k2*B^2*C^2 - db*B", + "C": "kc - k3*C^2*A^2 - dc*C", + "L": "-kq*L", + }, + observables={"y1": "s1*A", "y2": "s2*B", "y3": "Rm", "y4": "C"}, +) + + +def _canon(gen): + """The generator up to a factor: every entry divided by the first.""" + names = sorted(gen) + e = {k: spy.sympify(str(v).replace("^", "**")) for k, v in gen.items()} + return tuple((k, str(spy.simplify(e[k] / e[names[0]]))) for k in names) + + +def _run(model, monkeypatch, curve, control=None): + monkeypatch.setenv("SYMIDENT_RESTCURVE" if curve else "SYMIDENT_NORESTCURVE", "1") + seen = {"direct": 0, "msolve": 0} + solve_direct, run_msolve = rest.RestingStates.solve_direct, work.run_msolve + + def counted(self, *a): + seen["direct"] += 1 + return solve_direct(self, *a) + + def msolve(cmd, text=True): + seen["msolve"] += any(f.name == "solve_raw" for f in traceback.extract_stack()) + return run_msolve(cmd, text) + + monkeypatch.setattr(rest.RestingStates, "solve_direct", counted) + monkeypatch.setattr(work, "run_msolve", msolve) + m = si.Model(**model, events=EVENTS, conditions=CONDS, inputs=["L"]) + r = si.detect(m, equilibrate=True, reconstruct=True, cores=2, control=control) + return r, seen + + +@pytest.mark.parametrize("model", [SERIES, CORE], ids=["series", "core"]) +def test_curves_close_the_directions_of_direct_solves(model, monkeypatch): + with monkeypatch.context() as mp: + direct, seen_d = _run(model, mp, curve=False) + curve, seen_c = _run(model, monkeypatch, curve=True) + assert {_canon(s.generator) for s in curve.symmetries} == {_canon(s.generator) for s in direct.symmetries} + assert all(s.level == "exact" for s in curve.symmetries) + + def peeled(r): + return {_canon(s.generator) for s in r.symmetries if s.kind == "scaling" and s.route is None} + + assert peeled(direct) and peeled(curve) == peeled(direct) + assert seen_d["direct"] > 0 + assert seen_c == {"direct": 0, "msolve": 0} + + +def test_direct_core_needs_msolve(monkeypatch): + _, seen = _run(CORE, monkeypatch, curve=False) + assert seen["msolve"] > 0 + + +def test_a_rational_direction_of_degree_two(monkeypatch): + r, _ = _run(SERIES, monkeypatch, curve=True) + gens = [_canon(s.generator) for s in r.symmetries] + assert (("b", "1"), ("c", "-c**2/b**2")) in gens + + +def test_a_constant_translation(monkeypatch): + r, _ = _run(CORE, monkeypatch, curve=True) + tr = [s for s in r.symmetries if s.kind == "translation"] + assert [dict(s.generator) for s in tr] == [{"da1": "1", "da2": "-1"}] + + +def test_curve_samples_record_no_route_errors(monkeypatch): + r, _ = _run(SERIES, monkeypatch, curve=True) + assert not r.info.get("errors") + + +def test_rank_profiles_skip_continued_conditions(monkeypatch): + from symident.detection.observability import joint + + profiled = [] + block_profiles = joint.JointSystem.block_profiles + + def watched(self): + fns = block_profiles(self) + if fns is None: + return None + + def wrap(mi, f): + def g(point, p, Nt): + out = f(point, p, Nt) + sol = self.solve_cond(point, p, self.equil_conds[mi]) + profiled.append(bool(out.get("ok")) and bool(sol and sol.get("cont"))) + return out + + return g + + return [wrap(mi, f) for mi, f in enumerate(fns)] + + monkeypatch.setattr(joint.JointSystem, "block_profiles", watched) + _run(SERIES, monkeypatch, curve=True) + assert profiled and not any(profiled) + + +def test_short_curves_raise_their_order(monkeypatch): + with monkeypatch.context() as mp: + direct, _ = _run(SERIES, mp, curve=False) + curve, _ = _run(SERIES, monkeypatch, curve=True, control=si.reconst_control(gap_order_cap=2)) + assert {_canon(s.generator) for s in curve.symmetries} == {_canon(s.generator) for s in direct.symmetries} + assert all(s.level == "exact" for s in curve.symmetries) + + +def test_continued_conditions_certify_the_lie_order(monkeypatch): + with monkeypatch.context() as mp: + direct, _ = _run(CORE, mp, curve=False) + curve, seen = _run(CORE, monkeypatch, curve=True) + for r in (direct, curve): + assert r.info["lie_certified"] is True + assert "drawn forward" in r.info["order_bound_why"] + assert curve.info["lie_block_orders"] == direct.info["lie_block_orders"] == [2, 5, 5] + assert seen == {"direct": 0, "msolve": 0} diff --git a/tests/test_rest_start.py b/tests/test_rest_start.py new file mode 100644 index 0000000..c564213 --- /dev/null +++ b/tests/test_rest_start.py @@ -0,0 +1,76 @@ +"""Starts of the resting states: the forward seed where a sum of balances holds none of the directly picked rates, +and the diagonal start without the private rates of states that rest at zero there.""" + +import random + +import sympy as spy + +from symident.detection.observability.start import DiagonalStart +from symident.sym.restforward import solve_forward_modular + +P = 2147483647 + +# phosphorylated Smad2 pool (pSmad2 + C234 + C234_SnoN) turns over only by k_phos_Smad2 and k_dephos_pSmad2 +SMAD = [ + "Smad2 = -Smad2*k_phos_Smad2 + k_dephos_pSmad2*(pSmad2 + C234 + C234_SnoN)", + "pSmad2 = Smad2*k_phos_Smad2 - k_dephos_pSmad2*pSmad2 - k_form_C234*pSmad2*pSmad3*Smad4" + " + k_dephos_pSmad3*(C234 + C234_SnoN)", + "Smad3 = -Smad3*k_phos_Smad3 + k_dephos_pSmad3*(pSmad3 + C234 + C234_SnoN)", + "pSmad3 = Smad3*k_phos_Smad3 - k_dephos_pSmad3*pSmad3 - k_form_C234*pSmad2*pSmad3*Smad4" + " + k_dephos_pSmad2*(C234 + C234_SnoN)", + "Smad4 = -k_form_C234*pSmad2*pSmad3*Smad4 + (k_dephos_pSmad2 + k_dephos_pSmad3)*(C234 + C234_SnoN)", + "C234 = k_form_C234*pSmad2*pSmad3*Smad4 - (k_dephos_pSmad2 + k_dephos_pSmad3)*C234" + " - k_form_C234_SnoN*C234*SnoN + k_dec_C234_SnoN*C234_SnoN", + "SnoN = k_transl_SnoN - k_dg_SnoN*SnoN - k_form_C234_SnoN*C234*SnoN" + " + (k_dec_C234_SnoN + k_dephos_pSmad2 + k_dephos_pSmad3)*C234_SnoN", + "C234_SnoN = k_form_C234_SnoN*C234*SnoN - (k_dec_C234_SnoN + k_dephos_pSmad2 + k_dephos_pSmad3)*C234_SnoN", +] +SMAD_STATES = ["Smad2", "pSmad2", "Smad3", "pSmad3", "Smad4", "C234", "SnoN", "C234_SnoN"] +SMAD_PARS = [ + "k_phos_Smad2", + "k_phos_Smad3", + "k_dephos_pSmad2", + "k_dephos_pSmad3", + "k_form_C234", + "k_form_C234_SnoN", + "k_dec_C234_SnoN", + "k_transl_SnoN", + "k_dg_SnoN", +] + + +def test_forward_seed_with_a_pool_of_a_total(): + rng = random.Random(1) + sv = {s: rng.randrange(2, P) for s in SMAD_STATES} + pv = {q: rng.randrange(2, P) for q in SMAD_PARS} + r = solve_forward_modular(SMAD, SMAD_STATES, SMAD_PARS, sv, pv, P, held=["Smad2", "Smad3", "Smad4"]) + assert r["ok"], r.get("why") + assert {"k_dephos_pSmad2", "k_phos_Smad2"} & set(r["solve_rates"]) + vals = {spy.Symbol(k): v for k, v in {**pv, **r["rates"], **r["val_by"]}.items()} + for line in SMAD: + 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"] + oe = ["m = ktO - kd*m", "r = kl*m - kdr*r", "s = kb - ks*s"] + pars = ["kt", "ktO", "kd", "kdK", "kl", "kdr", "kb", "ks"] + ds = DiagonalStart([ctrl, knd, oe], [0, 1, 2], 0, lambda ci: [], pars) + assert ds.ok + assert ds.Z == ["kt", "ktO"] + assert ds.S == ["m", "r"] + + +def test_a_face_of_several_states_rests_at_zero(): + from symident.detection.core import _rest_zeros + + f = { + "L": "ka*X*A - kd*L", + "X": "kx*L - dx*X", + "A": "kb - da*A", + "S": "-kp*S + kq*P", + "P": "kp*S - kq*P", + } + assert sorted(_rest_zeros(f, None, [])) == ["L", "X"] + assert _rest_zeros(f, None, [], nonzero=["X"]) == []