Identifying a DC motor from bench data with tune_parameters¶
A brushed DC motor's datasheet gives its torque constant, friction and rotor inertia
to within a few tens of percent; a controller tuned on those numbers inherits the
error. This example identifies the three from what a bench logs, the applied voltage,
the winding current and the shaft speed, with
jaxonomy.optimization.tune_parameters, and then checks the fit where it counts:
on a second run with another voltage profile, held out of the fit.
tune_parameters differentiates the simulation with respect to the parameters, so
the fit is an ordinary least-squares problem over the model the controller will use.
Given a residual_fn, it also returns the parameters' covariance at the optimum
(Gauss–Newton), their standard errors and confidence intervals, and the parameters
the data does not determine.
The bench data here is synthetic: the same model run with known parameters, with
the sensors' noise added, so that the fit can be compared with the truth. With
logged data, train and held below come from the log files instead.
import time
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import jaxonomy as jx
from jaxonomy import library as lib
from jaxonomy import logging
from jaxonomy.optimization import tune_parameters
from jaxonomy.simulation import ResultsMode, ResultsOptions
logging.set_log_level(logging.ERROR)
R, L = 0.5, 2e-3 # winding resistance (Ω) and inductance (H), measured with a meter
DT, T_END = 0.01, 4.0 # the log's sample period and length (s)
SIGMA = {"w": 0.5, "i": 0.05} # encoder speed (rad/s) and current sense (A) noise, std
# Only to synthesize the bench data: K (N·m/A), b (N·m·s/rad), J (kg·m²).
TRUE = {"K": 0.1, "b": 0.005, "J": 0.01}
DATASHEET = {"K": 0.08, "b": 0.0035, "J": 0.013}
The model¶
The winding and the shaft, with the three unknowns as diagram parameters:
$$L\,\frac{di}{dt} = V - R\,i - K\,\omega, \qquad J\,\frac{d\omega}{dt} = K\,i - b\,\omega.$$
The voltage profile is the only difference between the two runs: a staircase of steps for the fit, and two sines on an offset for the held-out check.
def voltage(b, profile):
if profile == "fit": # 6 V, 12 V, 3 V, off
steps = [(0.2, 6.0), (1.2, 6.0), (2.2, -9.0), (3.2, -3.0)]
parts = [b.add(lib.Step(0.0, v, t, name=f"v_step_{k}")) for k, (t, v) in enumerate(steps)]
else: # held out: never seen by the fit
parts = [b.add(lib.Constant(6.0, name="v_offset")),
b.add(lib.Sine(amplitude=4.0, frequency=2 * np.pi * 0.7, name="v_slow")),
b.add(lib.Sine(amplitude=2.0, frequency=2 * np.pi * 2.3, name="v_fast"))]
v = b.add(lib.Adder(len(parts), name="V"))
for k, s in enumerate(parts):
b.connect(s.output_ports[0], v.input_ports[k])
return v
def motor(profile):
p = {k: jx.Parameter(v) for k, v in DATASHEET.items()}
b = jx.DiagramBuilder()
v = voltage(b, profile)
i = b.add(lib.Integrator(0.0, name="i"))
w = b.add(lib.Integrator(0.0, name="w"))
across_l = b.add(lib.Adder(3, operators="+--", name="v_across_L"))
r_i = b.add(lib.Gain(R, name="R_i"))
emf = b.add(lib.Gain(p["K"], name="back_emf"))
di = b.add(lib.Gain(1.0 / L, name="di_dt"))
torque = b.add(lib.Gain(p["K"], name="torque"))
friction = b.add(lib.Gain(p["b"], name="friction"))
net = b.add(lib.Adder(2, operators="+-", name="net_torque"))
dw = b.add(lib.Gain(1.0 / p["J"], name="dw_dt"))
for src, dst in [(v, (across_l, 0)), (i, (r_i, 0)), (r_i, (across_l, 1)), (w, (emf, 0)),
(emf, (across_l, 2)), (across_l, (di, 0)), (di, (i, 0)), (i, (torque, 0)),
(w, (friction, 0)), (torque, (net, 0)), (friction, (net, 1)), (net, (dw, 0)),
(dw, (w, 0))]:
b.connect(src.output_ports[0], dst[0].input_ports[dst[1]])
d = b.build(name=f"motor_{profile}", parameters=p)
return d, {"w": d["w"].output_ports[0], "i": d["i"].output_ports[0]}
def run(profile, params):
d, ports = motor(profile)
res = jx.simulate(d, d.create_context().with_parameters(params), (0.0, T_END),
recorded_signals=ports,
results_options=ResultsOptions(mode=ResultsMode.fixed_interval,
fixed_results_interval=DT))
return np.asarray(res.time), {k: np.asarray(v).ravel() for k, v in res.outputs.items()}
The bench data¶
Each run is logged every 10 ms, the encoder and the current sense each with its own noise.
rng = np.random.default_rng(7)
def bench(profile):
t, clean = run(profile, TRUE)
return t, {k: clean[k] + SIGMA[k] * rng.standard_normal(t.size) for k in clean}
t, train = bench("fit")
_, held = bench("held_out")
print(f"{t.size} samples per signal and run; peak speed {train['w'].max():.0f} rad/s, "
f"peak current {np.abs(train['i']).max():.1f} A")
401 samples per signal and run; peak speed 92 rad/s, peak current 14.8 A
The fit¶
The residual is each sample's model-minus-measurement, divided by its sensor's
noise, so that the speed (in rad/s) and the current (in A) weigh in by how well they
are measured. recorded_signals and record_interval record both on the log's grid,
differentiably; the bounds keep each parameter physical.
fit_diagram, fit_ports = motor("fit")
def residuals(traj):
return jnp.concatenate([(traj.outputs["w"] - train["w"]) / SIGMA["w"],
(traj.outputs["i"] - train["i"]) / SIGMA["i"]])
def identify(guess):
return tune_parameters(
fit_diagram, fit_diagram.create_context(), (0.0, T_END), dict(guess),
set_params=lambda ctx, v: ctx.with_parameters(v),
residual_fn=residuals, recorded_signals=fit_ports, record_interval=DT,
bounds={"K": (0.01, 1.0), "b": (1e-4, 0.1), "J": (1e-3, 0.1)}, verbose=False,
)
t0 = time.perf_counter()
fit = identify(DATASHEET)
print(f"{len(fit.history)} iterations, {time.perf_counter() - t0:.0f} s; "
f"sum of squared residuals {float(fit.objective):.0f} for {fit.n_residuals} residuals, "
f"their variance {float(fit.residual_variance):.2f}\n")
print(f"{'':3} {'datasheet':>10} {'fit':>10} {'std error':>10} {'95 % interval':>24} {'true':>8} {'held':>5}")
for k in TRUE:
lo, hi = fit.confidence_intervals[k]
print(f"{k:3} {DATASHEET[k]:10.4g} {float(fit.params[k]):10.5g} {float(fit.standard_errors[k]):10.2g} "
f" ({lo:.5g}, {hi:.5g}) {TRUE[k]:8.4g} {str(lo <= TRUE[k] <= hi):>5}")
print("parameters the data does not determine:", fit.unidentifiable_params)
14 iterations, 25 s; sum of squared residuals 718 for 802 residuals, their variance 0.90
datasheet fit std error 95 % interval true held
K 0.08 0.10011 5.3e-05 (0.10001, 0.10022) 0.1 False
b 0.0035 0.0049995 6.2e-06 (0.0049874, 0.0050117) 0.005 True
J 0.013 0.010023 1.2e-05 (0.0099999, 0.010046) 0.01 True
parameters the data does not determine: []
fitted = {k: float(v) for k, v in fit.params.items()}
assert fit.unidentifiable_params == []
assert 0.8 < float(fit.residual_variance) < 1.2
for k in TRUE:
assert abs(fitted[k] - TRUE[k]) < 0.01 * TRUE[k], k
Each interval is the range that holds the true value in 95 % of noise draws; in any one draw a parameter's interval can miss it, which the last column says. The residuals' variance comes out near 1, as it should for residuals divided by their noise: the model explains the data down to the sensors.
The held-out check¶
A fit is judged on data it did not see. The second run's voltage, two sines on an offset, drives the model with the datasheet's parameters and with the fitted ones; each prediction is compared with that run's log.
def held_out_rms(params):
_, pred = run("held_out", params)
return {k: float(np.sqrt(np.mean((pred[k] - held[k]) ** 2))) for k in pred}, pred
rms_sheet, pred_sheet = held_out_rms(DATASHEET)
rms_fit, pred_fit = held_out_rms(fitted)
print(f"{'held-out rms':14} {'speed (rad/s)':>14} {'current (A)':>12}")
print(f"{'sensor noise':14} {SIGMA['w']:14.3f} {SIGMA['i']:12.3f}")
for name, rms in (("datasheet", rms_sheet), ("fit", rms_fit)):
print(f"{name:14} {rms['w']:14.3f} {rms['i']:12.3f}")
held-out rms speed (rad/s) current (A) sensor noise 0.500 0.050 datasheet 8.907 1.801 fit 0.542 0.049
for k in SIGMA:
assert rms_fit[k] < 1.2 * SIGMA[k], k # down to the sensor noise
assert rms_sheet[k] > 5 * SIGMA[k], k # the datasheet's model is not
fig, axes = plt.subplots(2, 1, figsize=(9, 6), sharex=True)
for ax, k, unit in zip(axes, ("w", "i"), ("rad/s", "A")):
ax.plot(t, held[k], ".", ms=2, color="0.6", label="held-out log")
ax.plot(t, pred_sheet[k], color="tab:orange", lw=1, label="datasheet")
ax.plot(t, pred_fit[k], color="tab:blue", lw=1.2, label="fit")
ax.set_ylabel(f"{'speed' if k == 'w' else 'current'} ({unit})")
ax.legend(loc="upper right")
axes[-1].set_xlabel("time (s)")
fig.tight_layout()
A guess too far¶
The fit is a local search. Started from half the datasheet's torque constant and twice its friction and inertia, it settles in another basin, with a residual far above the noise, and says it converged. The held-out run gives it away.
far = identify({"K": 0.05, "b": 0.01, "J": 0.02})
rms_far, _ = held_out_rms({k: float(v) for k, v in far.params.items()})
print(f"converged: {far.success}; sum of squared residuals {float(far.objective):.3g} "
f"(the close guess: {float(fit.objective):.3g})")
print(f"held-out rms: speed {rms_far['w']:.2f} rad/s, current {rms_far['i']:.3f} A")
assert float(far.objective) > 100 * float(fit.objective)
assert rms_far["w"] > 10 * SIGMA["w"]
converged: True; sum of squared residuals 1.38e+06 (the close guess: 718) held-out rms: speed 23.76 rad/s, current 1.418 A
What to take from it¶
tune_parameterswith aresidual_fnfits a diagram's parameters to logged signals and says how well the data determines each: standard errors, confidence intervals, andunidentifiable_params.- Divide each residual by its sensor's noise: signals in different units then weigh in by how well they are measured, and a residual variance near 1 says the model explains the data down to the noise.
- Keep a run out of the fit and judge the fit on it. A held-out error at the sensor noise is the evidence; a converged optimizer is not, since a guess far from the truth converges to a worse basin.