编排仿真循环
fly_ruler_std.runtime.loop 用于按确定顺序调度输入生成、模型步进、控制器计算与数据记录任务,并统计每个任务的执行耗时。其中 SyncLoop 按仿真时间定步推进,AsyncRealtimeLoop 按真实墙钟时间等待,适合软实时联调。
对应示例:packages/fly_ruler/examples/std/loops.py。
最小可运行示例
首先准备编译好的模型:
py
@fr.block
def IntegratorPlant() -> None:
"""为循环任务提供一个位置状态和速率输入。"""
# 状态方程 position_dot = rate;输入单位 m/s,状态单位 m。
rate = fr.input("rate", (1,), unit="m/s")
position = fr.state("position", (1,), unit="m")
fr.output("position_out", position, unit="m")
fr.dynamics({position: rate})
@fr.system
def IntegratorSystem() -> None:
"""创建供 SyncLoop 逐步推进的公开模型。"""
# 系统根路径为 Root,编译后的输入路径是 Root::rate。
rate = fr.input("rate", (1,), unit="m/s")
plant = IntegratorPlant("plant")
rate >> plant.rate
fr.export(position=plant.position_out)接着创建共享的 SimulationContext(存放状态向量与业务数据),并用 make_discrete_model_task 将模型封装为调度任务:
py
# state 按约定键名存放模型变量:x 连续状态、xd 离散状态、u 输入、p 参数。
sync_context = SimulationContext(dt=model.dt)
sync_context.state["x"] = model.x.build({"Root.plant::position": [0.0]})
sync_context.state["xd"] = model.xd.build()
sync_context.state["u"] = model.u.build({"Root::rate": [0.0]})
sync_context.state["p"] = model.p.default()
# command 任务每周期重写输入:速率从 1.0 起按 0.1 线性增加。
def set_command(ctx: SimulationContext) -> None:
ctx.state["u"] = model.u.build({"Root::rate": [1.0 + 0.1 * ctx.step]})
ctx.data["command_step"] = ctx.step
# LoopTask 用 stage/order 决定排序,wait_for 声明额外依赖。
# BLOCKING 模式同步执行,overrun=BLOCK 表示上一次未完成时等待而非跳过。
command_task = LoopTask(
name="command",
fn=set_command,
rate_hz=100.0,
stage="input",
order=0,
wait_for=(),
mode=TaskMode.BLOCKING,
overrun=OverrunPolicy.BLOCK,
enabled=True,
)
# 该辅助函数把编译模型包装成离散任务:读出 x/xd/u/p,调用 discrete_fn,
# 再把新的 x/xd 与输出 y/effects 写回 ctx.state。
# wait_for=("command",) 保证先刷新输入再积分。
model_task = make_discrete_model_task(
model,
name="integrate",
rate_hz=100.0,
x_key="x",
xd_key="xd",
u_key="u",
p_key="p",
y_key="y",
effects_key="effects",
stage="dynamics",
order=0,
wait_for=("command",),
)最后将任务列表交给 SyncLoop 运行:
py
# 传入顺序故意打乱:SyncLoop 按默认阶段序 input→control→dynamics→sensor→io→record
# 与同阶段 order 重排为 command→integrate→capture。
loop = SyncLoop(sync_context, [capture_task, model_task, command_task])
print(
f"sync order={[task.name for task in loop.tasks]}; tasks={loop.tasks}; "
f"loop context matches={loop.ctx is sync_context}; stats={loop.stats}"
)
# 每个任务的静态合同字段都打印出来,供和 stage 排序规则对照。
for task in loop.tasks:
print(
f"task {task.name}: fn={task.fn}; rate={task.rate_hz}; "
f"stage={task.stage}; order={task.order}; wait_for={task.wait_for}; "
f"mode={task.mode}; overrun={task.overrun}; enabled={task.enabled}"
)
# max_steps=5 表示推进 5 个仿真步,返回 {任务名: LoopStats}。
sync_stats = loop.run(max_steps=5)loop.run(max_steps=5) 会返回每个任务名到 LoopStats 的映射;实际执行顺序由任务的 stage、order 与 wait_for 决定,可通过 loop.tasks 查看排序结果。
任务配置与共享上下文
LoopTask 控制每个任务的执行时机与并发策略:
| 字段 | 说明 |
|---|---|
name | 任务标识,供 wait_for 引用及统计结果索引 |
fn | 回调函数(同步循环用普通函数,异步循环用 async def) |
rate_hz | 任务执行频率;低于循环主频时自动按步跳过 |
stage / order | 调度优先级:先按 stage 升序,同 stage 内按 order 升序 |
wait_for | 同 stage 内必须等待的前置任务名 |
mode | TaskMode.BLOCKING、BACKGROUND、DETACHED |
overrun | 超限策略:ALLOW_OVERLAP、BLOCK、CANCEL_PREVIOUS、QUEUE_LATEST、SKIP |
enabled | 布尔开关,用于临时停用任务 |
SimulationContext 分为两类槽位:ctx.state 存放数组(默认键名 x、xd、u、p、y、effects,与 make_discrete_model_task 自动对接),ctx.data 存放任意自定义业务对象。循环会自动维护 ctx.dt、ctx.step、ctx.time、ctx.wall_time 与 ctx.running,任务内部可通过 ctx.request_stop("原因") 优雅终止循环。
LoopStats 统计字段说明
runs、skipped、cancelled:实际执行次数、按降频跳过的次数、被超限策略取消的次数queued_latest、overlaps、missed_deadlines:排队次数、重叠执行次数、错过的实时截止时间数last_runtime_s、max_runtime_s、max_lag_s:单步耗时、最大耗时与最大滞后last_started_time、last_finished_time:最近一次执行对应的仿真时间
异步软实时循环
将 SyncLoop 替换为 AsyncRealtimeLoop 并把回调写成 async def,即可按真实时间节拍运行:
py
# AsyncRealtimeLoop 接管 asyncio 事件循环,按同一套 stage/order 调度协程任务。
async_loop = AsyncRealtimeLoop(async_context, [async_task])
# asyncio.run 启动事件循环并等待 3 步结束。
async_stats = asyncio.run(async_loop.run(max_steps=3))
print(
f"async ctx: dt={async_context.dt}; step={async_context.step}; "
f"time={async_context.time}; wall_time={async_context.wall_time}; "
f"running={async_context.running}; state={async_context.state}; "
f"data={async_context.data}; stop_reason={async_context.stop_reason}; "
f"tasks={async_loop.tasks}; loop stats={async_loop.stats}; "
f"loop context matches={async_loop.ctx is async_context}"
)
for name, stats in async_stats.items():
show_stats(f"async {name}", stats)
# 手动记录异步循环的停止原因。
async_context.request_stop("async loop complete")如果不需要手动持有循环实例,可以直接使用快捷函数 run_sync(context, tasks, max_steps=...) 或 run_async_realtime(context, tasks, max_steps=...)。
常见报错排查
| 现象 | 排查方向 |
|---|---|
| 任务执行顺序与列表顺序不同 | 循环按 stage 与 order 排序,查看 loop.tasks 确认实际顺序 |
声明 wait_for 时报错 | wait_for 仅支持等待同一 stage 内更早的任务;跨阶段依赖请调整 stage |
| 模型状态没有前进 | 检查 ctx.state 是否已初始化 x/u/p,以及任务列表是否包含 make_discrete_model_task |
| 实时循环频繁超限 | 查看 LoopStats 的 missed_deadlines 与 max_lag_s,适当降低 rate_hz 或调整 overrun 策略 |
| 循环提前退出 | 检查 ctx.stop_reason,确认是否有任务调用了 ctx.request_stop(...) |