Skip to content

封装环境接口 ​

fly_ruler_std.runtime.env 将编译后的 FlyRuler 模型包装为标准的 reset / step 环境接口,方便接入强化学习训练、策略评估或外部控制框架。环境包装器专注状态步进与向量化,不绑定特定 RL 算法或 Gym 注册表。

对应示例:packages/fly_ruler/examples/std/env.py。

NumPy 单环境与基本用法 ​

将编译后的 NumPy RuntimeInstance 传给 NumpyEnv,即可使用 reset() 与 step(state, u) 推进仿真:

py
@fr.block
def FlightPlant() -> None:
    """一个连续位置状态、离散采样计数和单一控制输入。"""
    position = fr.state("position", (1,), default=[2.0], unit="m")
    samples = fr.dstate("samples", (1,), default=[4.0])
    command = fr.input("command", (1,), unit="m/s")

    # 使用 Euler 步进;position 前的系数是 1 s⁻¹,command 与位置导数同为 m/s。
    # 两项都在 Signal 方程里计算,不由 Python 分支控制模型行为。
    fr.dynamics({position: -position + command})
    fr.next_step({samples: samples + 1.0})
    fr.output("position_out", position, unit="m")
    fr.output("samples_out", samples)


@fr.system
def FlightSystem() -> None:
    """连接控制输入并公开两个输出。"""
    command = fr.input("command", (1,), unit="m/s")
    plant = FlightPlant("plant")
    command >> plant.command
    fr.export(position=plant.position_out, samples=plant.samples_out)

重置初值与附加数据 ​

调用 reset() 时,连续/离散状态默认取模型 x.build() / xd.build(),参数取 p.default(),输入默认全零。你也可以显式覆盖初值或参数,并通过 custom_data 携带模型外的自定义状态(会在后续 step 中原样传递):

py
# reset 未传 x/xd 时读取模型中声明的非零初值;u 仍按变量空间零初始化。
initial = env.reset(custom_data={"episode_id": np.asarray([7.0])})
np.testing.assert_allclose(initial.x, [2.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(initial.xd, [4.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(initial.u, [0.0], atol=NUMPY_TOLERANCE, rtol=0.0)
assert initial.step_count.item() == 0
assert initial.t.item() == 0.0
assert initial.custom_data is not None
assert initial.custom_data["episode_id"].item() == 7.0
_check_state_pytree(initial)

# 第二次 reset 显式覆盖 x、xd 和输入,custom_data 由环境原样带入状态。
state = env.reset(
    x=np.asarray([1.0]),
    xd=np.asarray([10.0]),
    u=np.asarray([2.0]),
    custom_data={"episode_id": np.asarray([8.0])},
)
np.testing.assert_allclose(state.x, [1.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(state.xd, [10.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(state.p, [], atol=NUMPY_TOLERANCE, rtol=0.0)
assert state.custom_data is not None
assert state.custom_data["episode_id"].item() == 8.0

推进一步 ​

step(state, u) 接收当前 State 与控制输入 u,返回一个全新的冻结 State 对象与 info 字典(info["effects"] 包含本步派生量):

py
# Env 本身不保存 episode 状态;step 返回新 State,由调用方接续下一步。
command = np.asarray([0.5])
next_state, info = env.step(state, command)
np.testing.assert_allclose(next_state.x, [0.95], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(next_state.xd, [11.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(
    next_state.y, [0.95, 10.0], atol=NUMPY_TOLERANCE, rtol=0.0
)
assert next_state.step_count.item() == 1
assert next_state.t.item() == DT
assert next_state.custom_data is state.custom_data
assert info["effects"] is next_state.effects

continued, _ = env.step(next_state, np.asarray([-0.5]))
np.testing.assert_allclose(continued.x, [0.805], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(continued.xd, [12.0], atol=NUMPY_TOLERANCE, rtol=0.0)
np.testing.assert_allclose(
    continued.y, [0.805, 11.0], atol=NUMPY_TOLERANCE, rtol=0.0
)
assert continued.step_count.item() == 2
print(
    "numpy:默认初态 (2, 4),显式覆盖后两步 "
    f"x={continued.x[0]:.3f}, xd={continued.xd[0]:.0f}"
)

State 的不可变性与 custom_data

State 是冻结的 dataclass,每次 step 都会返回新实例,因此循环中务必接住返回值。若 custom_data 中包含可变容器,环境会沿用同一引用,由调用方负责其读写管理。

JAX 加速与批量向量化环境 ​

将 JAX 模型包装为 JaxEnv 后,可直接配合 jax.jit 使用;需要并行推进多个相同模型时,使用 JaxVectorizedEnv(固定批大小 B,状态与输入形状为 (B, n),即使 B=1 也保留批次轴):

py
# JaxVectorizedEnv 用 vmap 并行执行独立环境;B=1 与 B=4 保持前导批轴。
for num_envs in (1, 4):
    vectorized: JaxVectorizedEnv = JaxVectorizedEnv(model, num_envs=num_envs)
    assert vectorized.array_type is jax.Array
    batch_state = vectorized.reset(
        custom_data={"row": jnp.arange(num_envs, dtype=jnp.float32)}
    )
    batch_leaves, batch_tree = jax.tree_util.tree_flatten(batch_state)
    restored_batch_state = jax.tree_util.tree_unflatten(batch_tree, batch_leaves)
    np.testing.assert_array_equal(
        np.asarray(restored_batch_state.custom_data["row"]), np.arange(num_envs)
    )
    commands = jnp.full((num_envs, 1), 0.5, dtype=jnp.float32)
    batch_step = jax.jit(vectorized.step)
    batch_next, batch_info = batch_step(batch_state, commands)
    assert batch_next.x.shape == (num_envs, 1)
    assert batch_next.xd.shape == (num_envs, 1)
    assert batch_next.custom_data is not None
    np.testing.assert_allclose(
        np.asarray(batch_next.x),
        np.full((num_envs, 1), 1.85),
        atol=tolerance,
        rtol=0.0,
    )
    np.testing.assert_allclose(
        np.asarray(batch_next.xd),
        np.full((num_envs, 1), 5.0),
        atol=tolerance,
        rtol=0.0,
    )
    np.testing.assert_array_equal(
        np.asarray(batch_next.custom_data["row"]), np.arange(num_envs)
    )
    np.testing.assert_array_equal(
        np.asarray(batch_info["effects"]), np.asarray(batch_next.effects)
    )
    print(f"jax vmap B={num_envs}:x={np.asarray(batch_next.x).ravel()}")

精度提醒

JAX 环境默认沿用 JAX 的 float32 精度;需要 float64 时请在构建模型与环境前按选择数值后端显式开启 x64。

CasADi 转 Native 执行 ​

如果你持有 CasADi 模型并希望以原生 C++/NumPy 速度执行(包括多轨迹并行),可使用 CasADiEnv 或 CasADiVectorizedEnv(批量版依赖本机 C++ 工具链):

py
for num_envs in (1, 4):
    vectorized: CasADiVectorizedEnv = CasADiVectorizedEnv(
        batch_model, num_envs=num_envs, context=batch_context
    )
    assert vectorized.array_type is np.ndarray
    batch_state = vectorized.reset()
    batch_next, batch_info = vectorized.step(
        batch_state, np.full((num_envs, 1), 0.5)
    )
    assert batch_next.x.shape == (num_envs, 1)
    np.testing.assert_allclose(
        batch_next.x,
        np.full((num_envs, 1), 1.85),
        atol=NUMPY_TOLERANCE,
        rtol=0.0,
    )
    np.testing.assert_allclose(
        batch_next.xd,
        np.full((num_envs, 1), 5.0),
        atol=NUMPY_TOLERANCE,
        rtol=0.0,
    )
    np.testing.assert_array_equal(
        np.asarray(batch_info["effects"]), np.asarray(batch_next.effects)
    )
    print(f"casadi native batch B={num_envs}:x={batch_next.x.ravel()}")

如何选择合适的环境包装器 ​

使用场景推荐环境运行前提
本地调试与控制逻辑验证NumpyEnv无额外依赖,返回 NumPy 数组
jax.jit 加速或与 JAX 训练流集成JaxEnv需安装 fly-ruler[jax]
大批量并行 rolloutJaxVectorizedEnv / CasADiVectorizedEnv固定批大小 B,t 与 step_count 为标量
CasADi 模型高性能原生步进CasADiEnv / CasADiVectorizedEnv批量执行需本机 C++ 工具链

下一步 ​