r"""System identification
Recovers an unknown drag coefficient from position observations of a
drag-perturbed LEO trajectory, by gradient descent through the dynamics.
The "observations" are generated by the same simulator with the true value
(`--true-cd`, 2.2), and the estimate starts from `--guess-cd` (1.4).
- reads vehicle-parameter gradients from `rollout.vehicle_configs.grad`
- sums the squared position errors over the per-step history
(`rollout.states[t]`) at 10 observation times
- updates the parameter on the simulator and re-reads it with
`rollout.reset()` before the next taped rollout
- a light, high-drag spacecraft on a circular orbit at about 400 km; the
rollout is 500 steps of 2 s, symplectic integrator, gravity with J2 and drag
```bash
python examples/12_system_identification.py
python examples/12_system_identification.py --guess-cd 3.0 --device cpu
```
Options: `--num-steps`, `--dt`, `--iters`, `--obs-every`, `--true-cd`,
`--guess-cd`, `--tol`, `--device`, `--no-show`.

**What to look for:** the error contracts by a factor of about 5 per
iteration, from 36 % to about $10^{-11}$ in 15 iterations (convergence is
reported against `--tol`, $10^{-9}$ by default). The step size is set once
from the first gradient, assuming a quadratic loss; the steady contraction
shows that holds here.
"""
import argparse
import os
import math
import time
import numpy as np
import warp as wp
import matplotlib.pyplot as plt
from cosmic_warp.core.pipeline import SpacecraftSimulator
from cosmic_warp.core.state import State
from cosmic_warp.physics.gravity import MU_EARTH
@wp.kernel
def position_loss_kernel(
states: wp.array(dtype=State),
target: wp.vec3d,
loss: wp.array(dtype=wp.float64),
):
"""Squared distance of the position to one observation."""
tid = wp.tid()
d = states[tid].pos - target
wp.atomic_add(loss, 0, wp.dot(d, d))
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="System identification of a drag coefficient")
parser.add_argument("--num-steps", type=int, default=500, help="Rollout steps")
parser.add_argument("--dt", type=float, default=2.0, help="Time step [s]")
parser.add_argument("--iters", type=int, default=15, help="Gradient descent iterations")
parser.add_argument("--obs-every", type=int, default=50,
help="Observe the position every N steps")
parser.add_argument("--true-cd", type=float, default=2.2,
help="Drag coefficient used to generate the observations")
parser.add_argument("--guess-cd", type=float, default=1.4,
help="Initial drag-coefficient guess")
parser.add_argument("--tol", type=float, default=1e-9,
help="Relative cd error counted as converged")
parser.add_argument("--device", default="cuda", help="Warp device (e.g. 'cuda' or 'cpu')")
parser.add_argument("--no-show", action="store_true",
help="Skip interactive plot windows (plots are still saved to disk)")
return parser.parse_args()
def main():
args = _parse_args()
wp.init()
print("=" * 60)
print("COSMIC WARP - System Identification (drag coefficient)")
print("=" * 60)
r_orbit = 6.778e6 # ~400 km altitude: strong drag
v_circ = math.sqrt(MU_EARTH / r_orbit)
sim = SpacecraftSimulator(
num_envs=1,
integrator="symplectic",
dt=args.dt,
device=args.device,
check_bounds=False,
drag=True,
differentiable=True,
)
# Light, high-drag spacecraft so the observations carry a clear cd signal
sim.vehicle.set_config(mass_dry=0.5, area_drag=5.0, cd=args.true_cd)
sim.reset_to_conditions(
positions=wp.array([[r_orbit, 0.0, 0.0]], dtype=wp.vec3d, device=args.device),
momenta=wp.array([[0.0, v_circ, 0.0]], dtype=wp.vec3d, device=args.device), # 1 kg
)
rollout = sim.differentiable_rollout(args.num_steps)
obs_steps = list(range(args.obs_every, args.num_steps + 1, args.obs_every))
# "Observed" positions from the true drag coefficient
rollout.forward()
observations = {t: wp.vec3d(*rollout.states[t].numpy()["pos"][0]) for t in obs_steps}
print(f"Rollout: {args.num_steps} steps x {args.dt} s = {args.num_steps * args.dt:.0f} s")
print(f"Observations: {len(obs_steps)} positions (every {args.obs_every} steps)")
print(f"True cd = {args.true_cd}, initial guess = {args.guess_cd}\n")
sim.vehicle.set_config(cd=args.guess_cd) # the other fields are kept
cds, losses = [args.guess_cd], []
lr = None
t_start = time.time()
for it in range(args.iters):
rollout.reset() # re-reads state AND parameters
loss = wp.zeros(1, dtype=wp.float64, device=args.device, requires_grad=True)
with rollout.tape:
rollout.forward()
for t in obs_steps:
wp.launch(position_loss_kernel, dim=sim.num_entities,
inputs=[rollout.states[t], observations[t], loss],
device=args.device)
rollout.tape.backward(loss)
loss_val = float(loss.numpy()[0])
g = float(rollout.vehicle_configs.grad.numpy()["cd"][0])
if lr is None:
# For the quadratic residual loss = S*dcd^2 the gradient gives
# S = g^2 / (4*loss); lr = 0.4/S contracts the error 5x per step
lr = 0.4 * 4.0 * loss_val / g**2
cd = cds[-1] - lr * g
sim.vehicle.set_config(cd=cd)
cds.append(cd)
losses.append(loss_val)
print(f" iter {it:3d} cd = {cd:.9f} |error| = {abs(cd - args.true_cd):.3e}")
elapsed = time.time() - t_start
rel_err = abs(cds[-1] - args.true_cd) / abs(args.true_cd)
status = "Converged" if rel_err <= args.tol else "Not converged"
print(f"\n{status} (relative cd error {rel_err:.1e}, tolerance {args.tol:g}) after "
f"{args.iters} forward+backward rollouts of {args.num_steps} steps "
f"in {elapsed:.2f} s")
print(f"Recovered cd = {cds[-1]:.9f} (true {args.true_cd})")
# --- Plots ---
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
ax1.plot(cds, marker="o")
ax1.axhline(args.true_cd, color="r", linestyle="--", label=f"true cd = {args.true_cd}")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Drag coefficient")
ax1.set_title("Parameter estimate")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.semilogy(np.abs(np.array(cds) - args.true_cd))
ax2.set_xlabel("Iteration")
ax2.set_ylabel("|cd error|")
ax2.set_title("Identification error")
ax2.grid(True, alpha=0.3)
plt.tight_layout()
out = os.path.join(os.getcwd(), "system_identification.png")
plt.savefig(out, dpi=150)
print(f"\nPlot saved to {out}")
if not args.no_show:
plt.show()
if __name__ == "__main__":
main()