Batch 10 of expansion-v2. Extends discovery into stochastic dynamics, adds
discrete-time control, and completes the Python/TS reach for the analysis
commands. Deterministic/offline/std-only (Rust) or typed/tested (Python/TS).
crates/lawsynth-sde (new): stochastic law discovery via Kramers-Moyal
conditional moments. Drift a(x)=E[ΔX|x]/Δt and diffusion b²(x)=E[ΔX²|x]/Δt
estimated by binning, occupancy-gated, then sparse-fit to a polynomial library.
Recovers OU (linear drift, constant diffusion), GBM (state-dependent quadratic
diffusion), and double-well (cubic drift) from seeded Euler-Maruyama paths.
Reports raw binned table + fitted laws; honest that it's a statistical
estimator (accuracy scales with path length / bin occupancy). Closes the loop
with the existing SDE simulator. 29 tests.
crates/lawsynth-discrete (new): discrete-time DLQR + Kalman/observer. DARE by
deterministic value iteration (reused on the dual for the filter); discrete
stability = spectral radius < 1, verified via koopman::eigen. DARE residuals
1e-12..5e-14, stabilizes an open-loop-unstable plant, matches the analytic
scalar P=2+√5 case. 34 tests.
python/lawsynth analysis.py: bifurcation/sensitivity/estimate/reduce client
methods over the CLI --json (single source of truth). test_analysis 36 passed;
full SDK suite 130 passed. Honest engine constraints surfaced (pole placement
needs observability; reduce needs a diagonalizable Hurwitz linearization).
packages/world-schema + api-client: typed models + parsers for the four new
analysis-command JSON shapes, verbatim-CLI fixtures, token strings confirmed
against source. api-client 24 tests.
specs/{sde-discovery,discrete-time-control}: boundary specs with honest limits.
Discrete-time-control boundary (v2-A)
This directory specifies deterministic discrete-time control and estimation —
given a sampled-data linear(ized) system, computing a feedback gain K, a filter
gain L, or a Luenberger observer gain that drive the closed-loop / error
dynamics inside the unit circle, implemented in crates/lawsynth-discrete. It is
a boundary specification in the house style: it states what a conforming
implementation MUST do, and — crucially — what a designed gain is and is not
allowed to claim.
Motivation
A discovered dynamical law sampled at a fixed step Δt — or a Koopman/DMD
operator, which is natively discrete (x' ≈ A x + B u) — advances the state one
step at a time:
x_{k+1} = A x_k + B u_k, y_k = C x_k.
This is the discrete-time counterpart of the continuous pair ẋ = A x + B u that
crates/lawsynth-feedback controls and crates/lawsynth-estimate observes. The
engineering questions are the same — choose u = −K x so the loop behaves, and
reconstruct x from partial y — but the stability notion changes. A
continuous system is stable when every eigenvalue lies in the open left
half-plane (Re λ < 0); a discrete system is stable when every eigenvalue lies
strictly inside the unit circle (|λ| < 1, i.e. spectral radius < 1). The
governing equations are therefore the discrete algebraic Riccati equations, not
the continuous ones — they are genuinely different and are solved here directly,
not by mapping to the continuous crate.
- Discrete LQR (DLQR) minimizes
Σ_k (xₖᵀQxₖ + uₖᵀRuₖ). The optimal gain isK = (R + BᵀPB)⁻¹BᵀPA, wherePsolves the discrete algebraic Riccati equation (DARE)P = AᵀPA − AᵀPB(R + BᵀPB)⁻¹BᵀPA + Q. - Discrete Kalman filter chooses the estimator gain optimally given process
covariance
Qand measurement covarianceR. The steady-state predictor gain isL = APCᵀ(R + CPCᵀ)⁻¹, wherePsolves the dual (filter) DAREP = APAᵀ − APCᵀ(R + CPCᵀ)⁻¹CPAᵀ + Q. - Discrete Luenberger observer places the error poles
A − LCexactly at chosen z-plane locations by the dual of Ackermann's formula.
Duality
The filter DARE for (A, C) is exactly the control DARE for the transposed pair
(Aᵀ, Cᵀ). The implementation exploits this directly: discrete_kalman reuses
the same DARE value iteration on (Aᵀ, Cᵀ) and reads the predictor gain
L = APCᵀ(R + CPCᵀ)⁻¹ off the solution — one audited Riccati routine serves both
control and estimation.
LawSynth is deterministic and offline. This stage reuses the deterministic
eigensolver of crates/lawsynth-koopman (Householder–Hessenberg + Wilkinson
complex QR) to report the achieved closed-loop / error spectrum; the only other
numerics are local Gaussian elimination and matrix polynomials. Identical inputs
MUST yield bit-identical output.
What a designed gain IS
A gain is a property of the supplied linear system and the design weights, not of any data or of the underlying nonlinear field. The contract is:
- A gain for the linearization, not the nonlinear law.
KstabilizesA − BK;Lshapes the error dynamicsA − LC. On the true nonlinear system the guarantee is valid only in the neighbourhood of the fixed point whereAis a faithful one-step linearization; the crate makes no basin-of-attraction or global claim. - Discrete stability, honestly verified. Every design returns its achieved
spectrum as
eigen(A − BK)/eigen(A − LC), so a caller reads the actually realized eigenvalues — and confirms the discrete condition|λ| < 1directly — rather than trusting the requested spectrum. - The Riccati solution is checkable. DLQR and the Kalman filter return the
solved
P; plugging it back into the relevant DARE gives a residual a caller can measure. The optimality claim is exactly "this(K, P)/(L, P)is a stabilizing solution of the stated DARE", no more. - A property of the expression, not of any fit. The design carries no discovery confidence or fit residual. Those are separate, upstream concerns.
Requirements
-
DLQR solves the DARE by a deterministic value iteration. From
P₀ = Q, an implementation MUST iterateP ← AᵀPA − AᵀPB(R + BᵀPB)⁻¹BᵀPA + Qto a fixed relative convergence tolerance, bounded by a maximum iteration count. Each iterate MUST be symmetrized ((P + Pᵀ)/2), exact in infinite precision. The inner solve of(R + BᵀPB)⁻¹MUST use local deterministic Gaussian elimination. The gain is thenK = (R + BᵀPB)⁻¹BᵀPAfor the control lawu = −K x. -
The Kalman filter solves the dual filter DARE. For covariances
Q ⪰ 0(process) andR ≻ 0(measurement), an implementation MUST computePfrom the same DARE iteration applied to(Aᵀ, Cᵀ)and return the predictor gainL = APCᵀ(R + CPCᵀ)⁻¹, whose error dynamics areA − LC. The Kalman path admits multiple outputs (p ≥ 1), since the dual control problem is multi-input. -
Discrete observer placement is single-output and exact (dual Ackermann). For an observable pair
(A, C)withCof shape1 × nandndesired z-plane error poles, an implementation MUST computeL = p(A) O⁻¹ eₙ, whereO = [C; CA; …; CAⁿ⁻¹]is the observability matrix,eₙ = [0 … 0 1]ᵀ, andpis the monic desired characteristic polynomial∏(z − λᵢ).O⁻¹andp(A)MUST be formed with local deterministic Gaussian elimination and matrix multiplication. A tallerC(p > 1) MUST be rejected with a distinctMultiOutputerror. -
Real gains only. The desired observer poles MUST be closed under complex conjugation, so
phas real coefficients andLis real. A lone complex pole MUST be rejected (NonRealDesignPoles) rather than returning a complex gain. -
Observability / stabilizability is required, not assumed. If the observability matrix is singular the pair is unobservable and MUST return a distinct
Unobservableerror. If the DARE iteration fails to converge — a diverging iterate or an exhausted budget, as happens for an unstabilizable / undetectable unstable mode — the implementation MUST return a distinctNotConvergenterror, never a fabricated or least-squares gain. -
Weights are validated at the boundary.
QMUST be symmetric and positive semidefinite;RMUST be symmetric and positive definite (hence invertible). Symmetry is checked directly; definiteness is checked from the shared eigensolver's eigenvalues. A violated precondition MUST surface as a distinct typed error (NotSymmetric,NotPositiveSemidefinite,NotPositiveDefinite), never a silently repaired weight. -
Reuse the deterministic eigensolver. The achieved closed-loop / error poles MUST come from the
lawsynth-koopmaneigensolver applied toA − BK/A − LC, in that solver's canonical order, so the whole pipeline shares one audited decomposition. Discrete stability is then read off as spectral radius< 1. -
Determinism. The DARE value iteration, the polynomial expansion, observability, Gaussian elimination (largest-magnitude pivot, lowest index on a tie), and the eigen-verification MUST all be deterministic — fixed loop order, no RNG, no clock. Identical inputs MUST produce a bit-identical result: identical
K/L/P(tof64bit patterns) and an identical achieved spectrum in identical order.
Public API
dlqr(&Matrix /*A*/, &Matrix /*B*/, &Matrix /*Q*/, &Matrix /*R*/)
-> Result<DiscreteGain, DiscreteError>
discrete_kalman(&Matrix /*A*/, &Matrix /*C, p×n*/, &Matrix /*Q, n×n*/, &Matrix /*R, p×p*/)
-> Result<DiscreteObserver, DiscreteError>
discrete_observer_from_poles(&Matrix /*A*/, &Matrix /*C, 1×n*/, &[Complex] /*z-plane poles*/)
-> Result<DiscreteObserver, DiscreteError>
DiscreteGain { k: Matrix, achieved_poles: Vec<Complex>, p: Matrix }
DiscreteGain::spectral_radius() -> f64
DiscreteGain::is_stable(margin) -> bool // all |λ| < 1 − margin
DiscreteObserver { l: Matrix, error_poles: Vec<Complex>, p: Option<Matrix>, method: ObserverMethod }
DiscreteObserver::spectral_radius() -> f64
DiscreteObserver::is_convergent(margin) -> bool // all |λ| < 1 − margin
Matrix and Complex are re-exported from lawsynth-koopman so a caller builds
(A, B, C) and reads achieved spectra without a separate dependency. DLQR always
returns P; the Kalman filter returns Some(P) (the error covariance); observer
placement returns None (it forms no covariance). This crate delivers the
discrete design library only; wiring it into a controller, a discovery report,
or a simulation loop is downstream and out of scope here.
Honest scope & limits
- Discrete stability means the unit circle. The whole crate's stability notion
is
|λ| < 1(spectral radius below one), not the continuousRe λ < 0. The DARE, the DLQR/Kalman gains, andis_stable/is_convergentare all discrete-time; do not confuse them with the continuous CARE ofcrates/lawsynth-feedback. - DARE convergence requires stabilizability / detectability. The value
iteration converges to the stabilizing solution only for a stabilizable
(A, B)(detectable(A, C)for the filter). A genuinely unstabilizable unstable mode has no stabilizing DARE solution: the iterate diverges and is reported asNotConvergentrather than returned as a fabricated gain. - Value iteration converges linearly — slow near marginal stability. The
fixed-point map contracts at a rate governed by the closed-loop spectral radius
squared, so convergence is fast for well-damped systems but slows sharply as
poles approach the unit circle. The iteration is bounded by a maximum count; a
near-marginal problem may hit that bound and report
NotConvergent. (A quadratically convergent doubling scheme is a possible future refinement, out of scope here.) R ≻ 0is assumed.Rmust be positive definite forR + BᵀPB(resp.R + CPCᵀ) to be invertible; a semidefinite or indefiniteRis rejected.- The gain is only as local as the linearization.
Ais a one-step linearization at a point; the closed-loop / error guarantee is local. Nothing here certifies a region of attraction or behaviour away from the fixed point. - Observer placement is single-output only. Dual Ackermann applies to one
measured output (
Cof height 1); a tallerCis rejected rather than silently reduced. The Kalman filter does handle multiple outputs, via the multi-input dual DARE. - Numerical conditioning degrades near the unit circle. For large
n, a near-uncontrollable / near-unobservable pair, or a fast desired spectrum, the DARE, the observability matrix, and the matrix polynomial become ill-conditioned; the achieved spectrum then drifts from the requested one, which is precisely why the achieved spectrum is reported rather than assumed. A DARE residual is likewise a modelling check, not a proof of optimality to machine precision. - Optimality is asymptotic and (for Kalman) Gaussian. The Kalman gain is the
steady-state constant gain, optimal only under linear-Gaussian assumptions at
steady state;
Pis the steady-state error covariance.
Non-goals
- No continuous-time design (that is
crates/lawsynth-feedback/crates/lawsynth-estimate); no mapping between the two here. - No multi-output / robust observer placement, no reduced-order observer, no unknown-input or disturbance observer.
- No finite-horizon / time-varying DARE, no LQG / separation-principle controller
synthesis, no deadbeat or
H∞design. - No time-varying or extended/unscented filtering for nonlinear models; the estimate is linear and local to the linearization.
- No region-of-attraction estimate or any nonlinear / global guarantee for the underlying field.