DiffusionControl / nonlinear /experiments /x31_trace_diag.py
matCercola18's picture
X31 write-up and swing-up trace diagnostic
d98652f verified
Raw History Blame Contribute Delete
2.73 kB
"""X31 diagnostic (PREREG addendum 2): plant 0, |u| <= 0.6 m g l, its July-output spline, one start just off hanging (theta0 = -pi + 1e-3, omega0 = 0).
Prints the wrapped state once per second under the held-input RK4 model (dt 0.02 and 0.0025 s, float64 CPU and float32 GPU) and under a
float64 continuous-time integration (scipy RK45, input re-evaluated continuously). Not a pre-registered measure.
Run: PYTHONPATH=. python -m nonlinear.experiments.x31_trace_diag"""
import json, numpy as np, torch
from scipy.integrate import solve_ivp
from nonlinear.experiments import x31_pend_screen as S
P = S.plants(); G = S.G
r = json.load(open("results/icml_r3/X31/plants/p00_r6.json")); s = r["spl_july"]
V, c, Y, um = np.array(s["V"]), s["c"], s["Y"], r["umax"]; l, m, b = r["l"], r["m"], r["b"]
def phi(y):
i = np.clip(np.floor((y / Y + 1) * 5), 0, 9).astype(int); w = (y / Y + 1) * 5 - i
return V[i] + w * (V[i + 1] - V[i])
def rhs(t, x):
tw = np.arctan2(np.sin(x[0]), np.cos(x[0])); u = np.clip(-phi(tw + c * x[1]), -um, um)
return [x[1], G / l * np.sin(x[0]) - b / (m * l * l) * x[1] + u / (m * l * l)]
x0 = [-np.pi + 1e-3, 0.0]
sol = solve_ivp(rhs, (0, 10), x0, method="RK45", rtol=1e-9, atol=1e-11, max_step=0.005, dense_output=True)
for dev, dtype in (("cpu", torch.float64), ("cuda", torch.float32)):
for dt in (0.02, 0.0025):
S.DT = dt
par = tuple(torch.tensor(float(x), dtype=dtype, device=dev) for x in P[0])
ctrl = S.spl(torch.tensor(V[None], dtype=dtype, device=dev), torch.tensor([c], dtype=dtype, device=dev), torch.tensor([Y], dtype=dtype, device=dev))
th, om = torch.tensor([x0[0]], dtype=dtype, device=dev), torch.tensor([x0[1]], dtype=dtype, device=dev)
rows = []
n = int(round(10 / dt)); every = int(round(1 / dt))
for k in range(n):
u = torch.clamp(ctrl(S.wrap(th), om), -um, um)
k1t, k1o = S.pendulum_deriv(th, om, u, *par); k2t, k2o = S.pendulum_deriv(th + .5 * dt * k1t, om + .5 * dt * k1o, u, *par)
k3t, k3o = S.pendulum_deriv(th + .5 * dt * k2t, om + .5 * dt * k2o, u, *par); k4t, k4o = S.pendulum_deriv(th + dt * k3t, om + dt * k3o, u, *par)
th = th + dt / 6 * (k1t + 2 * k2t + 2 * k3t + k4t); om = om + dt / 6 * (k1o + 2 * k2o + 2 * k3o + k4o)
if (k + 1) % every == 0:
rows.append((float(S.wrap(th)[0]), float(om[0])))
print(f"{dev} {dtype} dt {dt}: " + " ".join(f"t{i + 1}:({a:+.2f},{w:+.2f})" for i, (a, w) in enumerate(rows)), flush=True)
z = sol.sol(np.arange(1, 11))
print("RK45 float64: " + " ".join(f"t{i + 1}:({np.arctan2(np.sin(z[0, i]), np.cos(z[0, i])):+.2f},{z[1, i]:+.2f})" for i in range(10)), "| nfev", sol.nfev, "status", sol.status)