lawsynth/docs/guide/examples/gen_forced_oscillator.py
caelum0x fab9a4a45a feat: reach + performance + docs — Python analysis client, parallel eval, sensitivity, guide
Batch 7 of expansion-v2. Extends the product across surfaces and adds an
analysis primitive. Deterministic/offline/std-only (Rust) or graceful-absence
(Python).

python/lawsynth analysis.py (new): Python client for the engine's stability,
control, and domains analyses — shells out to the lawsynth CLI (--json) and
parses to typed dataclasses. No numerics re-implemented in Python; the Rust
engine is the single source of truth. Locates the binary like the benchmarks,
raises MissingBinaryError/CliError honestly, and is fully parse-testable
offline. 20 tests; full SDK suite 114 passed.

crates/lawsynth-features: opt-in std::thread-parallel feature-library
evaluation, bit-identical to serial for ALL thread counts (row-chunked via
thread::scope, ordered assembly, no parallel float reduction). Verified via
f64::to_bits across {1,2,3,4,7,8} threads x 10 library variants x uneven row
counts. Measured 3.6x at 8 threads; honestly sublinear (allocation-bound,
~few-thousand-row crossover). 28 tests + benchmark.

crates/lawsynth-sensitivity (new): forward sensitivity analysis. Integrates the
variational equations Ṡ_j = J_x·S_j + f_θj (J_x from the analytic Jacobian, f_θ
by symbolic differentiation) on the augmented system with fixed-step RK4.
Analytic check to <1e-6; finite-difference cross-check at 1e-6 for every
parameter on logistic + Lotka-Volterra. 22 tests.

docs/guide (new): verified end-to-end guide — getting-started, workflow
(discover→simplify→stability→control→export→validate→uncertainty), and a
determinism demo. All 17 documented commands run exit-0 via run_all.sh; honest
about real behaviors (already-minimal law simplifies to 0 nodes saved, CLI
bootstrap doesn't surface per-coef intervals, center points are inconclusive).
README links the guide.

specs/{parallel-evaluation,sensitivity-analysis}: boundary specs.
2026-08-18 16:14:46 +03:00

70 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Generate a deterministic *forced* (controlled) dataset for `lawsynth control`.
The system is a driven damped harmonic oscillator with one exogenous control
input `u(t)`:
dx/dt = v
dv/dt = -x - 0.3*v + u, with u(t) = sin(0.7*t)
The trajectory is integrated with classical fourth-order Runge-Kutta at a fixed
step. There is no random number generator and no wall-clock read anywhere in
this file, so the emitted `forced-oscillator.csv` is byte-for-byte reproducible
on any machine with a standard Python 3 interpreter (only the `math` module is
used). Re-running this script overwrites the CSV with identical bytes.
Usage:
python3 gen_forced_oscillator.py # writes forced-oscillator.csv
"""
from __future__ import annotations
import math
from pathlib import Path
DT = 0.02
STEPS = 600
DAMPING = 0.3
def control(t: float) -> float:
"""The exogenous, measured control signal u(t)."""
return math.sin(0.7 * t)
def field(state: tuple[float, float], u: float) -> tuple[float, float]:
"""Right-hand side dx/dt = v, dv/dt = -x - 0.3*v + u."""
x, v = state
return (v, -x - DAMPING * v + u)
def rk4_step(state: tuple[float, float], t: float) -> tuple[float, float]:
"""One fixed-step RK4 update. The control is sampled inside the step."""
x, v = state
k1 = field((x, v), control(t))
k2 = field((x + 0.5 * DT * k1[0], v + 0.5 * DT * k1[1]), control(t + 0.5 * DT))
k3 = field((x + 0.5 * DT * k2[0], v + 0.5 * DT * k2[1]), control(t + 0.5 * DT))
k4 = field((x + DT * k3[0], v + DT * k3[1]), control(t + DT))
return (
x + DT * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]) / 6.0,
v + DT * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]) / 6.0,
)
def main() -> None:
state = (1.0, 0.0)
lines = ["time,x,v,u"]
t = 0.0
for _ in range(STEPS + 1):
x, v = state
lines.append(f"{t:.12e},{x:.12e},{v:.12e},{control(t):.12e}")
state = rk4_step(state, t)
t += DT
out = Path(__file__).with_name("forced-oscillator.csv")
out.write_text("\n".join(lines) + "\n")
print(f"wrote {out.name} ({STEPS + 1} rows, step {DT}, columns time,x,v,u)")
if __name__ == "__main__":
main()