caelum0x 220552d530 feat: SDE discovery + discrete-time control + Python/TS reach
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.
2026-08-18 17:21:57 +03:00

113 lines
3.8 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Integration tests for the discrete Luenberger observer (dual pole placement).
mod common;
use common::{assert_poles_match, matrix, norm, spectral_radius, step_input};
use lawsynth_discrete::{
Complex, DiscreteError, Matrix, ObserverMethod, discrete_observer_from_poles,
};
/// A stable, observable single-output plant.
fn plant() -> (Matrix, Matrix, Matrix) {
let a = matrix(vec![vec![0.9, 0.1], vec![0.0, 0.8]]);
let b = matrix(vec![vec![0.0], vec![1.0]]);
let c = matrix(vec![vec![1.0, 0.0]]);
(a, b, c)
}
#[test]
fn places_error_poles_in_the_z_plane() {
let (a, _b, c) = plant();
let desired = [Complex::real(0.2), Complex::real(0.3)];
let observer = discrete_observer_from_poles(&a, &c, &desired).unwrap();
assert_eq!(observer.method, ObserverMethod::PolePlacement);
assert!(observer.p.is_none());
assert_poles_match(&observer.error_poles, &desired, 1e-9);
assert!(observer.is_convergent(1e-6));
assert!(spectral_radius(&observer.error_poles) < 1.0);
}
#[test]
fn places_complex_conjugate_error_poles() {
let (a, _b, c) = plant();
let desired = [Complex::new(0.3, 0.2), Complex::new(0.3, -0.2)];
let observer = discrete_observer_from_poles(&a, &c, &desired).unwrap();
assert_poles_match(&observer.error_poles, &desired, 1e-8);
assert_eq!((observer.l.rows(), observer.l.cols()), (2, 1));
}
#[test]
fn placement_observer_reconstructs_state() {
let (a, b, c) = plant();
let desired = [Complex::real(0.2), Complex::real(0.25)];
let observer = discrete_observer_from_poles(&a, &c, &desired).unwrap();
let l = &observer.l;
let mut x = vec![1.0, -1.0];
let mut x_hat = vec![0.0, 0.0];
let u = vec![1.0];
for _ in 0..200 {
let y = mat_vec(&c, &x);
let y_hat = mat_vec(&c, &x_hat);
let innovation: Vec<f64> = y.iter().zip(&y_hat).map(|(p, q)| p - q).collect();
let l_innov = mat_vec(l, &innovation);
let x_next = step_input(&a, &b, &x, &u);
let mut x_hat_next = step_input(&a, &b, &x_hat, &u);
for i in 0..x_hat_next.len() {
x_hat_next[i] += l_innov[i];
}
x = x_next;
x_hat = x_hat_next;
}
let error: Vec<f64> = x.iter().zip(&x_hat).map(|(p, q)| p - q).collect();
assert!(norm(&error) < 1e-6, "estimate did not converge: ‖x − x̂‖ = {}", norm(&error));
}
#[test]
fn rejects_multi_output_placement() {
let a = matrix(vec![vec![0.9, 0.1], vec![0.0, 0.8]]);
let c = matrix(vec![vec![1.0, 0.0], vec![0.0, 1.0]]); // 2×2, two outputs
let desired = [Complex::real(0.2), Complex::real(0.3)];
assert_eq!(
discrete_observer_from_poles(&a, &c, &desired).unwrap_err(),
DiscreteError::MultiOutput
);
}
#[test]
fn rejects_unobservable_pair() {
// C measures only state 0; with a diagonal A the second state is invisible.
let a = matrix(vec![vec![0.9, 0.0], vec![0.0, 0.8]]);
let c = matrix(vec![vec![1.0, 0.0]]);
let desired = [Complex::real(0.2), Complex::real(0.3)];
assert_eq!(
discrete_observer_from_poles(&a, &c, &desired).unwrap_err(),
DiscreteError::Unobservable
);
}
#[test]
fn rejects_lone_complex_pole() {
let (a, _b, c) = plant();
let desired = [Complex::new(0.3, 0.2), Complex::real(0.4)]; // not conjugate-closed
assert_eq!(
discrete_observer_from_poles(&a, &c, &desired).unwrap_err(),
DiscreteError::NonRealDesignPoles
);
}
#[test]
fn rejects_wrong_pole_count() {
let (a, _b, c) = plant();
let desired = [Complex::real(0.2)]; // only one pole for a 2-state system
assert_eq!(
discrete_observer_from_poles(&a, &c, &desired).unwrap_err(),
DiscreteError::PoleCountMismatch
);
}
/// `A x` for a general matrix and vector.
fn mat_vec(a: &Matrix, x: &[f64]) -> Vec<f64> {
(0..a.rows()).map(|i| (0..a.cols()).map(|j| a.get(i, j) * x[j]).sum()).collect()
}