Skip to content

配平、线性化与后端对比 ​

fr_gtm.trim 按飞行条件求三轴局部定常配平,并将结果映射回调用模型的后端与布局;线性化使用 CasADi。这一章说明目标、残差与工作点的用法。

配平 ​

trim(model, cfg, altitude=1000.0, tas=100.0) 求完整力/力矩及内部状态平衡,不是只求作动器零导数。cfg 必须与编译模型一致:

py
point = trim(model, cfg, altitude=1000.0, tas=100.0, gamma=0.0, psi=0.0, phi=0.0)
if not point.success:
    raise RuntimeError(
        f"trim failed: {point.solver.stats}; residuals={point.residuals}"
    )
参数含义
altitude、tas必填,高度 m、真空速 m/s;TAS 必须为正
gammaNED 航迹角,deg,默认 0
psi机头偏航角,deg,默认 0;不是地速航向 chi
phi滚转角,deg,默认 0
p固定运行时参数向量,省略用模型默认参数;可设置风和不确定度
guess可选 (x, xd, u) 初猜
paths目标模型实例的 GTMPaths,默认根实例

gamma/psi/phi=None 分别释放该条件,侧滑角始终不额外固定。位置固定为 (0,0,-altitude),角速率固定零,机体速度、角速率、舵面、发动机和 Dryden 状态导数为零;位置导数允许前进和爬升。舵面/指令边界来自配置,d/n 固定零。非零 gamma 是给定高度处的局部爬升条件,非零 phi 不自动建立协调转弯。

实现只在外层加标量条件观测包装,内部复用生产 GTMSystem 和 std TrimSolver;求解使用 CasADi,但返回的 x/xd/u/p 保留传入模型的后端类型。默认初猜由 init 构造,也可以复用上一次结果。

result.success 同时要求求解器成功和每项物理/内部状态/目标残差不超过 1e-6。result.residuals 使用对应物理单位(m、m/s、deg、m/s²、rad/s² 或内部状态每秒变化率);result.solver 保留 std 统计,不掩盖求解失败:

py
print(f"body acceleration: {point.residuals[paths.x.vel_body]:.3e} m/s²")
print(f"angular acceleration: {point.residuals[paths.x.omega_body]:.3e} rad/s²")
output = model.continuous_fn(0.0, point.x, point.xd, point.u, point.p)
observation = read_observation(model, output.y)
print(
    f"alpha={observation.alpha_deg:.3f} deg, "
    f"throttle={observation.throttle_percent:.3f}%"
)

线性化 ​

线性化的操作点直接取自配平结果,x_op 与 u_op 是路径到值的字典,x_keys、u_keys、y_keys 决定 A、B、C、D 的行列顺序:

py
linear = LinearizationSolver(
    model,
    LinearizationSpec(
        x_op={
            key: model.to_numpy(value).reshape(-1).tolist()
            for key, value in model.x.read(point.x, by="path").items()
        },
        u_op={
            key: model.to_numpy(value).reshape(-1).tolist()
            for key, value in model.u.read(point.u, by="path").items()
        },
        p_op={
            key: model.to_numpy(value).reshape(-1).tolist()
            for key, value in model.p.read(point.p, by="path").items()
        },
        x_keys=[
            paths.x.vel_body,
            paths.x.omega_body,
            paths.x.actuator_position,
            paths.x.engine_lag,
        ],
        u_keys=[paths.u.command],
        y_keys=[paths.y.clean],
    ),
).solve()
print(f"A shape: {linear.A.shape}, B shape: {linear.B.shape}")
print(f"C shape: {linear.C.shape}, D shape: {linear.D.shape}")

示例只取速度、角速度、三个舵面与发动机滞后状态这四个状态路径,加一个输入路径,y_keys 用 Root::clean_y 保持 17 通道布局。返回结果的 A、B、C、D 形状由键的数量与观测布局决定。

后端对比 ​

四种后端共享同一段声明,差异来自 lowering 与浮点求和顺序。backend_compare.py 用同一次求值对比 NumPy、CasADi 与可选的 JAX,打印编译耗时以及相对 NumPy 的 max|xdot| 与 max|y|:

py
# 每个后端独立编译一次并计时;最后统一以 NumPy 的 xdot、y 作为偏差参考。
results: dict[str, tuple[float, np.ndarray, np.ndarray]] = {}
for name in names:
    started = perf_counter()
    compiler_settings = ModelSettings(integrator="euler", dt=0.01)
    compiler_context = OperationContext(store=ROOT / "build" / "flyruler")
    cfg = GTMConfig.fullscale()
    builder = GTMSystem.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}"
    )

backend_compare.py 为高精度后端比较显式配置 CPU 与 float64:

py
# 先按实际安装情况确定后端清单;JAX 需先配置运行时策略才能启用 CPU 与 64 位。
if find_spec("jax") is not None:
    configure_jax_runtime(
        JaxRuntimePolicy(
            platforms=("cpu",),
            preallocate=False,
            enable_x64=True,
        )
    )
    names.append("jax")
else:
    print("JAX is not installed; skipping it.")

native 后端在另外两个示例里出现:ground_operations.py 用 compiler.compile(symbolic.program, target=targets.NativeTarget()) 从相同模型程序生成 C++ 扩展,benchmark_jax_compile.py 单独度量 JAX 的跟踪、lower 与编译耗时,结果写进 build/jax_compile_benchmark.json。

产物检查用 inspect_model.py:artifacts.save(target, output_dir=...) 保存可恢复产物,artifacts.open(path).describe() 直接读取步长、目标类型与变量布局,Graph 也从保存目录读取拓扑,无需绑定运行实例;缓存位置由独立的 OperationContext(store=...) 指定。

产物与示例 ​

命令产物或输出
just example-trim飞行配平的物理残差与 A、B、C、D 形状
just example-backends三个后端的编译耗时与相对 NumPy 的偏差
just example-ground --scenario takeoff --backend nativeC++/pybind11 扩展缓存与地面场景记录
just benchmark-jax-compilemodels/fr_gtm/build/jax_compile_benchmark.json
just example-inspect产物路径、描述、完整路径清单与 Graph WebUI

这一章用到的 API ​

边界与常见坑 ​

边界说明
线性化使用 CasADiGTM trim 内部编译 CasADi 包装,结果返回原后端;LinearizationSolver 仍要求 CasADi 模型
路径写错抛 KeyErrorTrimSpec、LinearizationSpec 里的路径先经 model.x.keys 与 model.u.keys 核对
初始猜测影响收敛八个 Dryden 状态、三个舵面位置与发动机滞后状态要一起猜,离工作点太远会不收敛
键的顺序决定矩阵布局x_keys、u_keys、y_keys 的顺序与 A、B、C、D 的行列一一对应
后端偏差超出预期对比时用同一初值与 dt;JAX 默认 float32,若参考要求 float64 则在首次导入前显式启用 x64
native 首次编译慢首次生成 C++ 扩展,显式配置 Store 后可跨运行复用缓存

相关页面 ​