Skip to content

表达式、形状与资源 ​

声明出来的信号可以直接参与算术运算或交给 fr.math 算子;形状(shape)决定每个信号的维度,资源(resource)则负责把气动插值表、固定矩阵等常量数据带进模型。

对应示例:packages/fly_ruler/examples/core/expressions.py。完整的运算符与 fr.math 分类速查见信号数学与形状。

最小可运行:插值表与信号索引 ​

py
# 块内声明输入端口与插值资源,再用表达式把两者组合成输出。
@fr.block
def TableLookup() -> None:
    command = fr.input("command", (2,))
    # 二维表按顺序接收两个自变量:V0 采样 [0, 1],V1 采样 [0, 2]。
    # values 的形状 (2, 2) 与网格长度一一对应,缺省按多线性插值求值。
    table = fr.resource.interpolator(
        name="response_table",
        grid_points=[np.array([0.0, 1.0]), np.array([0.0, 2.0])],
        values=np.array([[0.0, 2.0], [2.0, 4.0]]),
    )
    # table(x, y) 的调用顺序必须与 grid_points 一致,即先 V0 后 V1。
    response = table(command[0], command[1])
    # 标量端口显式声明 dim=(1,),避免下游按未知形状推断。
    fr.output("response", response, dim=(1,))
    # 二维范数是 sqrt(u0² + u1²),对命令向量给出整体幅值。
    fr.output("command_norm", fr.math.norm(command), dim=(1,))


@fr.system
def LookupSystem() -> None:
    command = fr.input("command", (2,))
    lookup = TableLookup("lookup")
    command >> lookup.command
    fr.export(response=lookup.response, command_norm=lookup.command_norm)
  • 声明插值器:fr.resource.interpolator(...) 接收各轴网格点 grid_points 与数据数组 values(前导维度须与网格长度一致),返回的可调用对象可直接用 table(command[0], command[1]) 查询。资源名在当前模型内必须唯一。
  • 信号索引与标量形状:command[0] 从 (2,) 向量中取出第 0 个分量,内部 dim 为 []。声明标量输出时可显式写 dim=(1,) 以强调接口契约;表达式形状可推导时也可省略 dim。

常用选项与形状规则 ​

插值器常用配置参数:

参数取值说明
method"linear"(默认)、"cubic"linear 为多线性插值;cubic 为多维 C² not-a-knot 三次样条
n_out整数输出维度;省略时从 values 的尾部维度自动推断

形状规则:fr.input、fr.state、fr.param 声明形状(标量可写 (1,)、1 或 ()),(2,) 与 (1,) 混算时走广播,(2,) 与 (3,) 混算会在编译期报错。fr.math 中的算子在声明期只构造符号节点,因此条件分支请使用 fr.math.where 等条件算子,而非 Python if。

资源如何进入模型与缓存

插值表数据在 Python 侧准备,代码生成阶段按目标后端生成求值实现。固定表属于模型内容身份的一部分,修改表数据后重新编译即可生效;大型数组会随 artifacts.save 自动打包与恢复。C/C++ 目标的数据部署见保存与导出产物。

查表与自动微分 ​

多维 linear 采用多线性插值:每个坐标轴分别做线性插值,再将各轴权重相乘。因此“线性查表”在跨轴方向上存在非零的混合二阶导数(例如二维表在一个胞内表示 F(a,δ)=aδF(a,\delta)=a\delta,则 Fδa=1F_{\delta a}=1),CasADi 与 JAX 均会完整保留这一胞内混合导数。

  • 边界与节点选择:内部节点默认选择右侧插值胞,最外侧节点使用相邻端胞;超出网格范围时沿端胞外推。
  • 有限差分核对:在胞内可用中心差分验证导数;在网格节点处应使用对应胞内的单侧差分。

多维 cubic ​

当需要二阶导数连续(例如轨迹优化或高阶控制律)时,可选 method="cubic"(要求每轴至少 4 个严格递增的有限节点,构造张量积 not-a-knot 三次样条):

py
@fr.block
def CubicTable() -> None:
    coords = fr.input("coords", 2)
    x = np.array([-1.0, -0.2, 0.5, 1.4])
    y = np.array([-0.8, 0.1, 0.7, 1.6])
    xx, yy = np.meshgrid(x, y, indexing="ij")
    table = fr.resource.interpolator(
        "loads", [x, y], xx**3 + xx**2 * yy + xx * yy**2, method="cubic"
    )
    fr.output("value", table(coords[0], coords[1]))
    # 表内仍精确插值 x³;表外沿边界切线延拓,保留非零一阶梯度。
    tail = fr.resource.interpolator(
        "tail", [x], x**3, method="cubic", extrapolation="linear"
    )
    fr.output("tail", tail(coords[0]))


@fr.system
def CubicSystem() -> None:
    coords = fr.input("coords", 2)
    table = CubicTable("table")
    coords >> table.coords
    fr.export(
        value=table.value,
        gain=fr.jacobian(output=table.value, wrt=table.coords),
        tail=table.tail,
    )

默认 extrapolation="polynomial" 会在表外延续端多项式。若希望抑制远场外推增长,可设置 extrapolation="linear",使表外沿边界切线延拓(域内保持 C²,边界处为 C¹):

py
# 表内仍精确插值 x³;表外沿边界切线延拓,保留非零一阶梯度。
tail = fr.resource.interpolator(
    "tail", [x], x**3, method="cubic", extrapolation="linear"
)
fr.output("tail", tail(coords[0]))
py
coords = ca.SX.sym("coords", 2)
empty = ca.SX.zeros(0, 1)
named = model.sx.y.read(
    model.sx.continuous_fn(0.0, empty, empty, coords, empty).y, by="path"
)
gain = named["Root::gain"]
evaluate = ca.Function(
    "evaluate",
    [coords],
    [named["Root::value"], gain, ca.jacobian(ca.vec(gain), coords)],
)

JAX 单精度下的 cubic 精度

在 JAX 默认 float32 下,cubic 张量收缩显式使用 HIGHEST dot 精度;若对一阶/二阶导数精度有严格要求,建议按选择数值后端开启 JAX x64。

大表与稀疏矩阵 ​

对于含大量零元素的固定矩阵或矩阵插值表,可以通过 sparse=True 启用紧凑存储与乘法,写法与普通矩阵一致:

python
A = fr.math.matrix([[2.0, 0.0, 3.0], [0.0, 4.0, 0.0]], sparse=True)
y = A @ x                    # x:(3,) → y:(2,)
Y = fr.math.matmul(A, X)      # X:(3,r) → Y:(2,r)
z = A.T @ w                  # w:(2,) → z:(3,)

fr.resource.matrix_table(name, grid_points, values, *, method="linear", sparse=False) 与 interpolator 共用 linear/cubic 数学,区别在于查询结果保留 (m, n) 矩阵形状;设置 sparse=True 后,仅当所有网格节点在某位置均严格为零时才会压缩该位置。

py
@fr.block
def MatrixTableBlock() -> None:
    query = fr.input("query", 1)
    x = fr.input("x", 3)
    # 普通节点矩阵即可声明:所有节点均为零的位置才从内部存储删除。
    # 一维 linear 直接读取原节点;CasADi 所需通道排列由编译器在查询前准备。
    table = fr.resource.matrix_table(
        "A",
        [[0.0, 1.0]],
        [[[1.0, 0.0, 2.0], [0.0, 3.0, 4.0]], [[2.0, 0.0, 3.0], [0.0, 4.0, 5.0]]],
        sparse=True,
    )
    A = table(query)  # 逻辑形状始终是 (2, 3),不是 nnz 向量。
    fr.output("value", A @ x)


@fr.system
def MatrixTableSystem() -> None:
    query = fr.input("query", 1)
    x = fr.input("x", 3)
    matrix = MatrixTableBlock("matrix")
    query >> matrix.query
    x >> matrix.x
    fr.export(value=matrix.value)

多轴查询的传参方式

interpolator 与 matrix_table 要求每轴传入一个标量坐标,多轴查询应写为 table(q[0], q[1]);直接传入向量 table(q) 会触发形状错误。批量求值请使用后端 vmap 或 BatchModel。

矩阵表乘法 y=A(q)xy = A(q)x 在 CasADi 与 JAX 中完整保留对向量 xx 和查询坐标 qq 的链式导数(包括非线性查询 q=s2q=s^2 的二阶导数):

py
# 使用公开变量布局构造方向,避免依赖 u 中端口的排序。
z = ca.MX.sym("u", model.n_u)
symbolic_y = model.mx.continuous_fn(
    0.0, model.mx.x.build(), model.mx.xd.build(), z, model.mx.p.default()
).y
direction = model.u.build({"Root::query": [1.0], "Root::x": [0.0, 0.0, 0.0]})
jvp = ca.Function("query_jvp", [z], [ca.jtimes(symbolic_y, z, direction)])
derivative = model.to_numpy(jvp(u)).reshape(-1)
np.testing.assert_allclose(derivative, [1.0, 2.0])
py
# 即使 A 对 query 分段线性,query=s**2 仍会产生非零二阶链式项。
s = ca.MX.sym("s")
scheduled_inputs = model.mx.u.build(
    {"Root::query": s**2, "Root::x": [2.0, 3.0, -1.0]}
)
scheduled_y = model.mx.continuous_fn(
    0.0,
    model.mx.x.build(),
    model.mx.xd.build(),
    scheduled_inputs,
    model.mx.p.default(),
).y
second = ca.Function(
    "scheduled_hessian", [s], [ca.jacobian(ca.jacobian(scheduled_y, s), s)]
)
hessian = model.to_numpy(second(0.5)).reshape(-1)
np.testing.assert_allclose(hessian, [2.0, 4.0])
进阶:资产打包阈值、稀疏限制与 native 融合
  • 资产阈值:在声明作用域内,超过 1024 个元素的数组默认写入压缩的 assets.npz,可通过 build_options(BuildOptions(...)) 调整阈值。
  • 稀疏作用域:sparse=True 仅适用于固定数值矩阵与 matrix_table(支持左乘向量、二维多右端项及转置);运行期可调参数的 fr.param 不支持稀疏压缩,solve 等运算请使用普通稠密矩阵。
  • native 融合:C++/native/PX4 导出会对一维 linear 的 table(q) @ x 自动按行融合计算,避免先生成整张临时矩阵。

常见报错排查 ​

现象排查方向
Unsupported interpolator methodmethod 仅支持 "linear" 或 "cubic"
Linear grids must be finite and strictly increasing网格必须为一维、有限且严格递增(linear 每轴至少 2 点,cubic 至少 4 点)
coordinate … must be scalar每轴传一个标量,多轴查询写 table(q[0], q[1])
Interpolator values leading dimensions must match grid lengths检查 values.shape 前几维是否与各轴网格长度一致
does not match values output size显式指定的 n_out 与 values 尾部维度不一致
形状不匹配或推导失败(1,) 与 1 会归一化为标量;检查索引、reshape 与广播,必要时在 fr.output 显式写 dim

下一步 ​