配平、线性化与后端对比
同一个模型声明可以降到不同后端上执行,也可以被配平与线性化工具直接调用。这一章给出悬停配平的完整流程、线性化结果的形状与含义、三个后端的一致性对比,以及用来核对产物的检查手段。
对应示例:models/fr_quad/examples/trim_linearize.py、models/fr_quad/examples/backend_compare.py、models/fr_quad/examples/inspect_model.py。
悬停配平
配平与线性化要求 CasADi 后端。先把指令算到一个接近悬停的初值:单个旋翼的目标推力是 mg/4,用 rpm_to_thrust 表反查转速,再用 pwm_to_rpm 表反查 PWM,最后仿射回归一化指令:
py
# 悬停时四个旋翼均分重量,先从参数取重力加速度再算单旋翼所需推力。
g0 = float(np.asarray(params["Root.gravity::g0"]).reshape(-1)[0])
hover_thrust = cfg.mass * g0 / 4.0
# 用推力到转速的表格反查所需转速;断点按升序存储,np.interp 按单调插值处理。
hover_rpm = float(
np.interp(
hover_thrust,
cfg.rpm_to_thrust_table,
cfg.rpm_to_thrust_breakpoints,
)
)
# 再用转速到 PWM 的表格反查 PWM,并仿射归一化到 [-1, 1] 的指令区间。
hover_pwm = float(
np.interp(hover_rpm, cfg.pwm_to_rpm_table, cfg.pwm_to_rpm_breakpoints)
)
hover_command = (hover_pwm - cfg.pwm_min) / (cfg.pwm_max - cfg.pwm_min) * 2.0 - 1.0初值、约束与求解选项都写在 TrimSpec 里;被配平的导数约束用完整路径给出(这里只要求四个转子转速的导数为零):
py
# param_value、state_value、input_value 把这三类量钉在给定值;state_derivative
# 只要求旋翼转速导数为零,因此这是部分配平,刚体状态仍由给定值固定。
# initial_guess 给出完整初值,objective_weights 抑制输入与导数项的附加代价。
trim = TrimSolver(
model,
TrimSpec(
param_value=params,
state_value=state,
input_value=inputs,
state_derivative={"Root.rotor::motor_rpms": np.zeros(4)},
initial_guess={
"Root.rb::pos_ned": flight_position,
"Root.rb::vel_body": np.zeros(3),
"Root.rb::quat": np.array([1.0, 0.0, 0.0, 0.0]),
"Root.rb::omega_body": np.zeros(3),
"Root.rotor::motor_rpms": np.full(4, hover_rpm),
"Root::motor_cmds": np.full(4, hover_command),
"Root::wind_ned": np.zeros(3),
"Root::sensor_noise": np.zeros(19),
},
objective_weights={"u": 1e-8, "x_dot": 1e-4},
solver_opts={
"ipopt.max_iter": 1000,
"ipopt.tol": 1e-7,
"ipopt.constr_viol_tol": 1e-7,
},
),
).solve(verbose=False)solve() 返回的 TrimResult 给出 success、stats、x_opt、u_opt 与 x_dot_opt,用 model.x.read(..., by="path")、model.u.read(..., by="path") 读回路径化的结果:
python
x_by_path = model.x.read(trim.x_opt, by="path")
u_by_path = model.u.read(trim.u_opt, by="path")
motor_xdot = model.xdot.read(trim.x_dot_opt, by="path")["Root.rotor::motor_rpms"]model.xdot 给出的是状态导数空间,因此 motor_xdot 就是转速导数;配平成功的直接判据是它的最大绝对值接近零。
线性化
把配平解当作工作点,选择要保留的状态、输入与输出,就能得到线性模型:
py
# 工作点直接取自配平结果;x_keys、u_keys、y_keys 选取关注的子集,
# 四元数等 SO3 通道在输出中会展开为切空间分量。
linear = LinearizationSolver(
model,
LinearizationSpec(
x_op={
path: np.asarray(value, dtype=float).reshape(-1).tolist()
for path, value in x_by_path.items()
},
u_op={
path: np.asarray(value, dtype=float).reshape(-1).tolist()
for path, value in u_by_path.items()
},
x_keys=[
"Root.rb::vel_body",
"Root.rb::omega_body",
"Root.rotor::motor_rpms",
],
u_keys=["Root::motor_cmds"],
y_keys=["Root::vel_body", "Root::omega_body", "Root::rpm"],
),
).solve()
print(f"A={linear.A.shape}, B={linear.B.shape}")
print(f"C={linear.C.shape}, D={linear.D.shape}")LinearizationResult 给出 A、B、C、D 四个矩阵,以及 x_op、u_op、y_op、x_dot_op 与 dimensions。x_keys、u_keys、y_keys 是可选的子集:不写就取全部通道,写上就只保留指定的完整路径。滚转、俯仰、偏航回路通常只关心 Root.rb::vel_body、Root.rb::omega_body、Root.rotor::motor_rpms 与 Root::motor_cmds。
后端对比
三个后端共享同一份声明,编译耗时与一次求值的数值可以逐项对比:
py
# 每个后端独立编译一次并计时,compile/ms 包含构建 IR 与生成后端代码的总耗时。
results: dict[str, tuple[float, np.ndarray, np.ndarray]] = {}
for name in names:
started = perf_counter()
compiler_settings = ModelSettings(integrator="rk4", dt=0.01)
compiler_context = OperationContext(store=ROOT / "build" / "flyruler")
builder = QuadSystem.build("Root", cfg)
program = compiler.prepare(
builder, settings=compiler_settings, context=compiler_context
)
# 走到最后的分支时 name 只能是 jax,因为清单由上面的可用性检查生成。
if name == "numpy":
xdot, y = _evaluate(
runtime.bind(
compiler.compile(
program,
target=targets.numpy,
context=compiler_context,
)
),
cfg,
)
elif name == "casadi":
xdot, y = _evaluate(
runtime.bind(
compiler.compile(
program,
target=targets.casadi,
context=compiler_context,
)
),
cfg,
)
else:
xdot, y = _evaluate(
runtime.bind(
compiler.compile(
program,
target=targets.jax,
context=compiler_context,
)
),
cfg,
)
compile_ms = (perf_counter() - started) * 1000.0
results[name] = (
compile_ms,
xdot,
y,
)
# 以 NumPy 后端的结果作为参考,偏差用逐分量最大绝对值表示。
_, xdot_ref, y_ref = results["numpy"]
print(f"{'backend':>8} {'compile/ms':>10} {'max|xdot|':>12} {'max|y|':>12}")
for name, (compile_ms, xdot, y) in results.items():
print(
f"{name:>8} {compile_ms:10.1f} "
f"{np.max(np.abs(xdot - xdot_ref)):12.3e} "
f"{np.max(np.abs(y - y_ref)):12.3e}"
)以 NumPy 的结果为参考,打印每个后端的编译耗时与 xdot、y 的最大偏差。JAX 未安装时脚本会跳过它;启用 JAX 时,此比较脚本显式配置 CPU x64,以符合其参考精度要求。普通 JAX 仿真默认使用 float32,FlyRuler 不会自动切换到 x64。
产物与缓存
给出 OperationContext.store 之后产物会落盘,inspect_model.py 把产物路径、缓存命中情况与各变量向量的完整路径清单打印出来:
py
# Store 是显式可复用缓存;保存目录是可独立恢复的交付产物。
context = OperationContext(store=root / "build" / "store")
program = compiler.prepare(
builder, settings=ModelSettings(integrator="rk4", dt=0.01), context=context
)
target = compiler.compile(program, target=targets.casadi, context=context)
saved = artifacts.save(target, output_dir=root / "build" / "model", overwrite=True)
model = runtime.bind(target)
print(f"artifact: {saved}")
print(f"description: {artifacts.open(saved).describe()}")
print(
f"sizes: x={model.n_x}, xdot={model.n_xdot}, "
f"xd={model.n_xd}, u={model.n_u}, p={model.n_p}, y={model.n_y}"
)
# keys 给出每个向量空间的顶层完整路径;状态、输入与输出的地址都以此为准。
for space, paths in (("x", model.x.keys), ("u", model.u.keys), ("y", model.y.keys)):
print(f"\n{space} paths:")
for path in paths:
print(f" {path}")model.artifact.file(ArtifactFile.SYSTEM_IR) 等接口给出各产物的实际文件,model.n_x、model.n_xdot、model.n_xd、model.n_u、model.n_p、model.n_y 给出向量长度(本模型默认配置为 n_x=17、n_xdot=17、n_u=26、n_p=20、n_y=103)。需要跨进程复用时用 artifacts.save(model.target_program, output_dir=...) 落盘、runtime.bind(path) 装载,细节见编译产物。
边界与坑
| 现象 | 原因 |
|---|---|
| 配平跑不起来 | TrimSolver 与 LinearizationSolver 需要 CasADi 后端编译出的模型 |
| 配平不收敛 | 初值离解太远;用标定表反查悬停转速,并把 motor_rpms 的导数约束与初值放在同一量级 |
| A、B 形状与预期不符 | x_keys、u_keys 没写就是全通道;本模型的状态含四元数,姿态通道会展开 |
| JAX 与 NumPy 偏差超出预期 | JAX 默认使用 float32;初值、输入或 dt 不一致也会改变结果。先统一比较条件;严格参考需要 float64 时,在首次导入前显式配置 CPU x64 |
| 改了标定表后旧产物还在用 | artifact.cache_hit 为真表示命中缓存;换 OperationContext.store 或改 OperationContext.cache 重编 |
| 配平成功但仿真仍然漂移 | 线性化的工作点与仿真的初值不是同一个点;用 LinearizationResult.x_op、u_op 做对比 |
这一章用到的 API
- quad 配置:标定表字段与不确定度上界
- std 配平:
TrimSolver、TrimSpec、TrimResult - std 线性化:
LinearizationSolver、LinearizationSpec、LinearizationResult - core 编译产物:
artifact.path、artifact.file(...)、_save、load - core 后端与目标:
targets.numpy、targets.casadi、targets.jax