同步、批量与异步记录
在 FlyRuler 工作区根目录运行:
bash
uv run python packages/fly_ruler/examples/std/record.py --output results/records先检查同步记录的 5 个采样,再比较两个各 4 步的 batch,最后确认异步队列的样本在关闭前已落盘。脚本用 Loader 逐项校验;你可以在输出目录打开 Parquet 和同名元数据。要查时间戳、变量布局和列选择,见记录与回读。
最小可运行
py
@fr.block
def Oscillator() -> None:
"""带参数的一维振子,提供 x/y/u/p/effect 记录样本。"""
# 状态为 [位移, 速度];阻尼系数是参数,能量作为 effect 便于观察衰减。
command = fr.input("command", (1,), unit="N")
state = fr.state("state", (2,), unit="mixed", description="位移与速度")
damping = fr.param("damping", default=0.15, unit="1/s")
fr.output("position", state[0], unit="m")
fr.effect("energy", state[0] ** 2 + state[1] ** 2, description="状态平方和诊断")
# 状态方程 state_dot = [v, F - c*v];状态含位移与速度,故单位标注 mixed。
fr.dynamics({state: fr.math.stack([state[1], command[0] - damping * state[1]])})
@fr.system
def OscillatorSystem() -> None:
# 系统只暴露位置输出,阻尼参数由调用者通过 p 传入。
command = fr.input("command", (1,), unit="N")
plant = Oscillator("plant")
command >> plant.command
fr.export(position=plant.position)
def build_model(output: Path) -> CasadiModel:
"""用 rk4、0.02 s 步长编译 CasADi 模型,缓存目录放在 output/cache。"""
compiler_settings = fr.ModelSettings(integrator="rk4", dt=0.02)
compiler_context = fr.OperationContext(store=output / "cache")
model_program = compilation.prepare(
OscillatorSystem.build("Root"),
settings=compiler_settings,
context=compiler_context,
)
model_target = compilation.compile(
model_program, target=fr.targets.casadi, context=compiler_context
)
return fr.runtime.bind(model_target)Recorder(model, output_dir=...) 绑定模型与目录;每推进一步记一次:
py
# 同步记录:先写一条 step=999、time=-1.0 的样本,再用 clear() 验证清空行为。
sync_dir = output / "sync"
recorder = Recorder(model, output_dir=sync_dir)
recorder.record(
step=999,
time=-1.0,
x=model.to_numpy(x),
y=model.to_numpy(initial_result.y),
u=model.to_numpy(u),
p=model.to_numpy(p),
effect=model.to_numpy(initial_result.effects),
)
# RecordSample 是落盘前的最小样本单元,values 按变量全路径分类存放。
first_sample: RecordSample = recorder.samples[0]
print(
f"pre-clear sample={first_sample}; batch={first_sample.batch_idx}; "
f"step={first_sample.step}; time={first_sample.time}; "
f"values={first_sample.values}; metadata={recorder.metadata}; "
f"output_dir={recorder.output_dir}; model={recorder.model}"
)
recorder.clear()
# 推进 5 步并逐样本记录;x 记录的是每个周期开始时的状态。
for step in range(5):
time = step * model.dt
result = model.discrete_fn(time, x, xd, u, p)
recorder.record(
step=step,
time=time,
x=model.to_numpy(x),
xd=model.to_numpy(xd),
y=model.to_numpy(result.y),
u=model.to_numpy(u),
p=model.to_numpy(p),
effect=model.to_numpy(result.effects),
)
x, xd = result.x_next, result.xd_next
# 清空后只剩这 5 条样本,batch_idx 均为 0。
sample: RecordSample = recorder.samples[0]
print(
f"sync sample={sample}; batch={sample.batch_idx}; step={sample.step}; "
f"time={sample.time}; values={sample.values}; count={len(recorder.samples)}"
)
recorder.save("sync_data")recorder.samples 是内存里的样本列表,recorder.clear() 清空,recorder.save("sync_data") 落盘(.parquet 加同名的元数据文件)。CasADi DM、JAX 设备数组都可以直接记录,Recorder 按模型后端自行转换,不需要先手工 to_numpy。
批量与异步
批量记录一次写入多组轨迹,record_batch(times=..., x=..., y=..., u=..., p=..., effect=...) 的数组形状是 (batch, steps, dim):
py
# 批量记录:数组形状为 (batch, step, dim),这里造两条各 4 步的轨迹。
batch_dir = output / "batch"
batch_recorder = Recorder(model, output_dir=batch_dir)
times = np.arange(4, dtype=float) * model.dt
batch_x = np.zeros((2, 4, 2), dtype=float)
batch_y = np.zeros((2, 4, 1), dtype=float)
batch_u = np.full((2, 4, 1), 0.25, dtype=float)
batch_p = np.tile(np.asarray(model.p.default(), dtype=float).reshape(1, -1), (2, 1))
batch_effect = np.zeros((2, 4, 1), dtype=float)
# 两条轨迹的状态分别从 0 与 1 附近出发,y 取状态本身,effect 取状态平方。
for batch_idx in range(2):
batch_x[batch_idx, :, 0] = batch_idx + times
batch_y[batch_idx, :, 0] = batch_x[batch_idx, :, 0]
batch_effect[batch_idx, :, 0] = batch_x[batch_idx, :, 0] ** 2
batch_recorder.record_batch(
times=times,
x=batch_x,
y=batch_y,
u=batch_u,
p=batch_p,
effect=batch_effect,
)
# 若使用 native BatchModel,也直接绑定它;记录数组仍是 (batch, steps, dim)。
# 不要用同布局标量模型替代,否则 metadata 的 target/artifact 会指向错误产物。
batch_recorder.save("batch_data")
# Loader 用完整路径取回,batch_id=1 时返回第二条轨迹的状态。
batch_loader = Loader(batch_dir, filename="batch_data", model=model)
print(
f"batch loader batches={batch_loader.batches}; "
f"records={batch_loader.total_records}; "
f"batch 1 states={batch_loader.get_x('Root.plant::state', batch_id=1)}"
)Recorder、AsyncRecorder 与 Loader 都可以直接绑定 BatchModel,无需额外编译同布局的标量模型。元数据保留批量模型自身的 target="native_batch"、artifact_key 与 batch_size。native batch 的一次运行返回 (B,D),必须先按时间堆叠为 (B,T,D) 才能交给 record_batch;也可以逐轨迹调用 record:
python
# batch_model 是 NativeBatchTarget 编译得到的模型;result 为一次 batch 运行的结果。
recorder = Recorder(batch_model, output_dir="results/batch")
for batch_idx in range(batch_model.batch_size):
recorder.record(
step=1,
time=batch_model.dt,
x=result.x_next[batch_idx],
y=result.y[batch_idx],
batch_idx=batch_idx,
)
recorder.save("batch_data")
loader = Loader("results/batch", filename="batch_data", model=batch_model)record 的路径映射也描述单条轨迹,例如 x={"Root.plant::state": [1.0, 0.0]},不会自动广播到整个 batch。未提供的状态和参数取该模型的单实例默认值。
异步记录将采样入队,由后台协程转入底层记录器的内存。record_nowait(...) 立即尝试入队:默认策略在队列满时抛 asyncio.QueueFull,drop_newest 丢弃当前样本并返回 False,drop_oldest 替换最旧样本并返回 True;await record(...) 则等待队列空位。pending 给出队列中待处理数量:
py
# 异步记录:队列容量 8,写满即抛错,用 async with 管理后台写盘任务。
async def record_asynchronously() -> None:
async with AsyncRecorder(
model,
output_dir=async_dir,
max_queue_size=8,
drop_policy="raise",
) as async_recorder:
print(
f"async recorder: queue_policy={async_recorder.drop_policy}; "
f"inner output={async_recorder.recorder.output_dir}; "
f"inner model={async_recorder.recorder.model}"
)
# record_nowait 入队成功返回 True;drop_newest 策略下队列满返回 False,
# 此时退回 await record 等待队列腾出空间(本例用 raise,属防御分支)。
for step in range(5):
now = async_recorder.record_nowait(
step=step,
time=step * model.dt,
x=model.to_numpy(x),
y=model.to_numpy(initial_result.y),
u=model.to_numpy(u),
p=model.to_numpy(p),
effect=model.to_numpy(initial_result.effects),
)
if not now:落盘使用 await async_recorder.save(stem),它先等待队列处理完再写文件;用完调用 await async_recorder.close()。flush() 只排空队列,默认的 close() 也不保存文件。
回读
Loader(output_dir, filename=...) 读回一份记录,按类别与完整路径取列:
py
# 回读同步文件:变量名必须写完整路径,例如 Root.plant::state。
loader = Loader(sync_dir, filename="sync_data", model=model)
# time_range 按 [start, end] 过滤,batch_id 选择第几条轨迹。
x_rows = loader.get_x("Root.plant::state", time_range=(0.0, 0.04))
y_rows = loader.get_y("Root::position", batch_id=0)
u_rows = loader.get_u("Root::command")
p_rows = loader.get_p("Root.plant::damping")
effect_rows = loader.get_effect("Root.plant::energy")
xd_rows = loader.get_xd(batch_id=0)
print(
f"loader: batches={loader.batches}; range={loader.time_range}; "
f"records={loader.total_records}; columns={loader.columns}; "
f"timestamp={loader.timestamp}; saved={loader.save_timestamp}; "
f"compiled_model={loader.compiled_model_info}; metadata={loader.metadata}; "
f"model={loader.model}"
)
print(
f"dataframe={loader.dataframe}; "
f"batch_frame={loader.get_dataframe(batch_id=0)}; "
f"x={x_rows}; xd={xd_rows}; y={y_rows}; u={u_rows}; p={p_rows}; "
f"effect={effect_rows}"
)可取的内容包括 batches、total_records、time_range、columns、timestamp、save_timestamp、compiled_model_info、metadata,以及 dataframe 与 get_dataframe(batch_id=...)。列名是 类别:布局名称[分量],例如 x:plant.state[0],布局名称可能是模型路径的简写——同一个模型里重复的局部名靠完整路径区分,这些显示名与完整路径的对应关系保存在 spaces 中;旧记录缺少 spaces 时,路径解析仍需显式提供匹配的 model。
读取诊断说明不需要恢复执行环境:
python
loader = Loader(sync_dir, filename="sync_data")
info = loader.info("effect", "Root.plant::energy")
print(info.unit, info.description, info.dim, info.dtype)info 返回记录保存的 VariableInfo,path 使用完整公开路径;缺少元数据时抛 KeyError。get_effect(path) 等数值接口仍返回 (N, D),矩阵也保持行优先展平;原始矩阵形状从 info.dim 读取。逻辑 Bool 标签不会改变 Parquet 数值列的浮点存储。
把数据交给 Plot
Plot 通过 Python 使用 Loader 或内存 Recorder:按完整列名选择变量和 batch 后调用 panel.record_line(...),无需在浏览器扫描目录,也无需重新加载模型。一般数组计算结果可直接使用 panel.line(x=..., y=...)。
Plot 的安装与用法见 Plot;模型拓扑查看见 Graph;记录目录的通用约定见记录与回读。需要直接分析或集成文件时,参阅开发者手册的记录器与 Parquet 布局,其中详细说明行列结构、batch、矩阵分量和 JSON 元数据。
边界与常见坑
| 现象 | 先查什么 |
|---|---|
| 列名对不上 | 列名可能是布局简写,回读使用匹配模型与完整路径,例如 Root.plant::state |
Loader 取到空数据 | 检查 filename 是否与 save(...) 的名字一致,以及 time_range / batch_id 过滤是否过窄 |
| 数组类型不对 | 传入的值应来自同一模型的后端;DM、JAX 数组本身都可直接记录 |
| 异步记录丢尾部 | 退出前 await save(stem) 再 await close() |
| 队列满或丢样本 | 用 await record(...) 等待空位,或调整容量与 drop_policy |
| 批量数据形状不合 | 批量数组是 (batch, steps, dim);times 可共享 (steps,) 时间戳,也可使用 (batch, steps) |
| 想直接画图却打不开数据 | 记录目录里要有 .parquet 与元数据文件,用 Loader 按文件名读取,再调用 record_line |