循环与调度
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 里,模型本身被包成一个任务:
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(context, tasks) 按任务的 stage、order 与 wait_for 排出执行顺序——传入顺序不等于执行顺序:
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 的映射;loop.tasks 是排序后的任务列表,loop.ctx 就是传进去的那个上下文对象。
任务字段
LoopTask 的字段决定「什么时候跑、能不能并行、超限怎么办」:
| 字段 | 说明 |
|---|---|
name | 任务名,wait_for 与统计结果都用它引用 |
fn | 回调,同步循环用普通函数,异步循环用 async def |
rate_hz | 任务自身的执行频率,低于循环频率时按步跳过 |
stage / order | 排序依据:先按 stage,同 stage 内按 order |
wait_for | 必须等待的同一步任务名(只能等更早的任务,否则声明即报错) |
mode | TaskMode.BLOCKING、BACKGROUND、DETACHED |
overrun | OverrunPolicy.ALLOW_OVERLAP、BLOCK、CANCEL_PREVIOUS、QUEUE_LATEST、SKIP |
enabled | 临时停用任务而不改列表 |
make_discrete_model_task(model, ...) 是给模型准备的任务工厂:它从 ctx.state 里读 x_key、xd_key、u_key、p_key 指定的数组,调用 discrete_fn 推进,并把结果写回 y_key 与 effects_key;默认键名就是 x/xd/u/p/y/effects。
上下文与统计
SimulationContext 里有两类槽位:ctx.state 放数组(x、xd、u、p、y、effects),ctx.data 放任意业务数据。ctx.dt、ctx.step、ctx.time、ctx.wall_time、ctx.running、ctx.stop_reason 由循环维护;调 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")asyncio.run(async_loop.run(max_steps=3)) 的返回值结构与同步循环相同。不想自己建循环对象时,用 run_sync(context, tasks, max_steps=...) 与 run_async_realtime(context, tasks, max_steps=...) 这两个快捷入口。
边界与常见坑
| 现象 | 先查什么 |
|---|---|
| 执行顺序和传入顺序不一致 | 任务按 stage / order 排序,loop.tasks 才是真实顺序 |
声明 wait_for 直接报错 | 只能等待同一 stage 内更早的任务;跨 stage 的依赖要用 stage 顺序表达 |
| 模型不前进 | 上下文里缺 x/u/p 等键,或任务没启用 make_discrete_model_task |
| 实时循环追不上 | 看 missed_deadlines 与 max_lag_s,再决定放宽 rate_hz 或调整 overrun 策略 |
| 任务被跳过 | rate_hz 低于循环频率时按步跳过是正常行为,看 skipped |
| 循环退出原因不明 | 读 ctx.stop_reason;request_stop 传的原因会保留下来 |
| 两种循环混用 | 同步循环的回调应是普通函数,异步回调放在 AsyncRealtimeLoop 里 |