Spaces:
Running
Running
stouchinglhh commited on
Commit ·
1758ba6
1
Parent(s): af470e1
collector: 更新采集工程至 v1.3.1(力矩阵落盘规格 5 档可选默认 ×100、倍率改按段记录 meta 第 11 列 force_matrix_specs;触觉热力图量程改下限固定+慢速自适应;SLAM 停落 slam_pose 列,位姿由 slam_trajectory 唯一承载;任务进度上报 404 冷却重探)
Browse files- collector/README.md +38 -4
- collector/config/__init__.py +1 -1
- collector/config/settings.py +53 -1
- collector/core/egodata_writer.py +102 -27
- collector/core/gripper/bridge.py +1 -1
- collector/core/gripper/tactile_process_worker.py +84 -2
- collector/core/helpers.py +2 -1
- collector/core/pipeline.py +25 -10
- collector/core/task_service.py +19 -2
- collector/docs/core.md +9 -2
- collector/docs/file_format.html +17 -2
- collector/docs/file_format.md +40 -2
- collector/scripts/repair_force_matrix_scale.py +291 -0
- collector/tools/demos/gripper_force_matrix_demo/gripper_force_matrix_demo.py +312 -33
- collector/tools/tests/test_gripper_force_matrix_demo.py +298 -12
- collector/tools/tests/test_gripper_matrix_encoding.py +92 -2
- collector/tools/tests/test_gripper_matrix_writer.py +325 -0
- collector/tools/tests/test_gripper_slam_columns.py +208 -0
- collector/tools/tests/test_repair_force_matrix_scale.py +206 -0
- collector/tools/tests/test_task_progress_retry.py +139 -0
- collector/ui/main_window.py +139 -16
collector/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
|
| 2 |
|
| 3 |
-

|
| 5 |

|
| 6 |
|
|
@@ -361,6 +361,20 @@ are documented in [docs/index.md](docs/index.md#开发约定).
|
|
| 361 |
|
| 362 |
### Changelog
|
| 363 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
- **v1.3.0** — UMI gripper support (Fays S80M stereo SLAM pose/trajectory
|
| 365 |
+ Sightac left/right tactile force with 250×250 force matrix + DECXIN
|
| 366 |
RGB; gripper group in the device panel, hidden when native resources
|
|
@@ -376,7 +390,13 @@ are documented in [docs/index.md](docs/index.md#开发约定).
|
|
| 376 |
committed), Sightac SDK shipped pyarmor-encrypted,
|
| 377 |
`tools/import_gripper_calibration.py` imports per-serial calibration
|
| 378 |
for a new gripper. Multiple S80M cameras distinguished by serial /
|
| 379 |
-
USB topology path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
- **v1.2.1** — large-file upload no longer killed by the 10 s timeout
|
| 381 |
(the send-body phase used the connect timeout; now uses a read-timeout
|
| 382 |
window); closing the upload dialog lets the task finish in the
|
|
@@ -539,7 +559,7 @@ data/recordings/<任务>/
|
|
| 539 |
├── info.json # 任务级头部;format="pooled_episodes_v1" 为判别键
|
| 540 |
├── stats.json # 全任务统计累加器(每列 count/mean/std/min/max)
|
| 541 |
├── tasks.jsonl # 任务描述(单行 JSONL 是格式契约)
|
| 542 |
-
└── episodes/chunk-NNN/episode-NNN.parquet # 每段一行元数据(
|
| 543 |
```
|
| 544 |
|
| 545 |
- **编号规则**:episode 全局从 N=1 递增,`chunk = (N-1) // 1000`、
|
|
@@ -720,6 +740,16 @@ i18n 文案经 `tr()` 翻译、PyQt5 信号参数用 `object` 封送大整数、
|
|
| 720 |
|
| 721 |
### 更新记录
|
| 722 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
- **v1.3.0** — 新增 UMI 夹爪全链接入(Fays S80M 双目 SLAM 位姿/轨迹 +
|
| 724 |
Sightac 左右触觉力与 250×250 力矩阵 + DECXIN RGB;设备面板夹爪分组,
|
| 725 |
原生资源缺失时自动隐藏),支持双臂双夹爪同录(rig1 旧槽位/数据列契约
|
|
@@ -730,7 +760,11 @@ i18n 文案经 `tr()` 翻译、PyQt5 信号参数用 `object` 封送大整数、
|
|
| 730 |
不再落 txt 侧车。夹爪脱离 `online/` 自持:原生资源镜像到
|
| 731 |
`core/gripper/native/`(不入库),Sightac SDK pyarmor 加密随包,
|
| 732 |
新增 `tools/import_gripper_calibration.py` 搬入新夹爪 per-serial 标定。
|
| 733 |
-
多台 S80M 按序列号 / USB 拓扑路径区分
|
|
|
|
|
|
|
|
|
|
|
|
|
| 734 |
- **v1.2.1** — 修复大文件上传被 10 秒误杀(发送阶段 socket 超时错用连接
|
| 735 |
超时,现改用读超时窗口);上传对话框关闭后任务在后台继续完成(手动上传
|
| 736 |
并入主窗口共享队列,重复提交自动跳过)
|
|
|
|
| 1 |
# collector — Multimodal Data Acquisition SDK · 多模态数据采集 SDK
|
| 2 |
|
| 3 |
+

|
| 4 |

|
| 5 |

|
| 6 |
|
|
|
|
| 361 |
|
| 362 |
### Changelog
|
| 363 |
|
| 364 |
+
- **v1.3.1** — force-matrix storage spec is now a five-way choice
|
| 365 |
+
(int16 / int16×10 / ×100 / ×1000 / float32) switchable from the
|
| 366 |
+
toolbar, defaulting to ×100 — quantisation error down to 0.9 % of the
|
| 367 |
+
sensor's own noise floor while staying at 38 % of float32 size; the
|
| 368 |
+
scale is recorded per episode in the `meta/episodes` row. Tactile
|
| 369 |
+
heat-map display range is now floor-anchored with slow adaptation
|
| 370 |
+
(τ≈8 s), so pressing harder actually changes the colour instead of
|
| 371 |
+
only the contact area. Task-progress reporting retries after a 404 on
|
| 372 |
+
a 10-minute cooldown, recovering without a restart once the backend
|
| 373 |
+
implements the endpoint. The `slam_pose` column is no longer written:
|
| 374 |
+
a fixed 7-value per-frame column cannot be filled by the 20/20/60 ms
|
| 375 |
+
pose burst, and 26.5 % of rows were landing as `[0]*7`, which
|
| 376 |
+
downstream reads as real poses — `slam_trajectory` is now the only
|
| 377 |
+
SLAM pose on disk
|
| 378 |
- **v1.3.0** — UMI gripper support (Fays S80M stereo SLAM pose/trajectory
|
| 379 |
+ Sightac left/right tactile force with 250×250 force matrix + DECXIN
|
| 380 |
RGB; gripper group in the device panel, hidden when native resources
|
|
|
|
| 390 |
committed), Sightac SDK shipped pyarmor-encrypted,
|
| 391 |
`tools/import_gripper_calibration.py` imports per-serial calibration
|
| 392 |
for a new gripper. Multiple S80M cameras distinguished by serial /
|
| 393 |
+
USB topology path. Force-matrix scale (int16×10/×100/×1000 / float32)
|
| 394 |
+
is now recorded **per episode** in the `meta/episodes` row
|
| 395 |
+
(`force_matrix_specs`); previously it lived only in the task-level
|
| 396 |
+
`meta/info.json`, where the next recording overwrote it and made
|
| 397 |
+
replay/training read ×10/×100/×1000 values at face value.
|
| 398 |
+
`scripts/repair_force_matrix_scale.py` back-fills the scale of
|
| 399 |
+
already-recorded episodes (meta rows only, data bytes untouched)
|
| 400 |
- **v1.2.1** — large-file upload no longer killed by the 10 s timeout
|
| 401 |
(the send-body phase used the connect timeout; now uses a read-timeout
|
| 402 |
window); closing the upload dialog lets the task finish in the
|
|
|
|
| 559 |
├── info.json # 任务级头部;format="pooled_episodes_v1" 为判别键
|
| 560 |
├── stats.json # 全任务统计累加器(每列 count/mean/std/min/max)
|
| 561 |
├── tasks.jsonl # 任务描述(单行 JSONL 是格式契约)
|
| 562 |
+
└── episodes/chunk-NNN/episode-NNN.parquet # 每段一行元数据(11 列)
|
| 563 |
```
|
| 564 |
|
| 565 |
- **编号规则**:episode 全局从 N=1 递增,`chunk = (N-1) // 1000`、
|
|
|
|
| 740 |
|
| 741 |
### 更新记录
|
| 742 |
|
| 743 |
+
- **v1.3.1** — 力矩阵落盘规格改为 5 档可选(int16 / int16×10 / ×100 /
|
| 744 |
+
×1000 / float32),工具栏「🎚 力矩阵精度」可切、默认 ×100——量化误差降到
|
| 745 |
+
传感器自身噪声的 0.9%,体积仍是 float32 的 38%;倍率记在每段一份的
|
| 746 |
+
`meta/episodes` 行。触觉热力图显示量程改「下限固定 + 慢速自适应」
|
| 747 |
+
(τ≈8s):此前固定量程下量化把梯度压平,用力大小只剩接触面积在变、
|
| 748 |
+
颜色几乎不动。任务进度上报 404 后带 10 分钟冷却期重探,服务端补上端点后
|
| 749 |
+
无需重启自动恢复。不再落 `slam_pose` 列——定长 7 值列填不满 20/20/60ms
|
| 750 |
+
的位姿突发,实测 26.5% 的行被填成 `[0]*7` 且会被下游当真实位姿读;
|
| 751 |
+
`slam_trajectory` 成为位姿唯一落盘形态,新增
|
| 752 |
+
`tools/tests/test_gripper_slam_columns.py` 守住该契约
|
| 753 |
- **v1.3.0** — 新增 UMI 夹爪全链接入(Fays S80M 双目 SLAM 位姿/轨迹 +
|
| 754 |
Sightac 左右触觉力与 250×250 力矩阵 + DECXIN RGB;设备面板夹爪分组,
|
| 755 |
原生资源缺失时自动隐藏),支持双臂双夹爪同录(rig1 旧槽位/数据列契约
|
|
|
|
| 760 |
不再落 txt 侧车。夹爪脱离 `online/` 自持:原生资源镜像到
|
| 761 |
`core/gripper/native/`(不入库),Sightac SDK pyarmor 加密随包,
|
| 762 |
新增 `tools/import_gripper_calibration.py` 搬入新夹爪 per-serial 标定。
|
| 763 |
+
多台 S80M 按序列号 / USB 拓扑路径区分。力矩阵倍率(int16×10/×100/×1000 /
|
| 764 |
+
float32)改记在**每段一份**的 `meta/episodes` 行(`force_matrix_specs`)——
|
| 765 |
+
此前只写在任务级 `meta/info.json`,会被同任务后一段录制覆盖,回放与训练
|
| 766 |
+
按面值读放大 10/100/1000 倍的数;`scripts/repair_force_matrix_scale.py`
|
| 767 |
+
可按实测比值给已录段补写倍率(只补 meta 行,不碰 data 字节)
|
| 768 |
- **v1.2.1** — 修复大文件上传被 10 秒误杀(发送阶段 socket 超时错用连接
|
| 769 |
超时,现改用读超时窗口);上传对话框关闭后任务在后台继续完成(手动上传
|
| 770 |
并入主窗口共享队列,重复提交自动跳过)
|
collector/config/__init__.py
CHANGED
|
@@ -3,4 +3,4 @@
|
|
| 3 |
版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
__version__ = "1.3.
|
|
|
|
| 3 |
版本号集中定义于此:settings.APP_VERSION 及其他模块均从这里取值。
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
__version__ = "1.3.1" # 力矩阵落盘规格改为 5 档可选(int16 / int16×10 / ×100 / ×1000 / float32,工具栏「🎚 力矩阵精度」可切,默认 ×100 —— 误差降到传感器自身噪声的 0.9% 而体积仍是 float32 的 38%),倍率改记在**每段一份**的 meta/episodes 行(新增第 11 列 force_matrix_specs,修「同任务换档时前一段被后一段顶掉、回放与训练按面值读放大 10/100/1000 倍的数」的静默错),并新增 scripts/repair_force_matrix_scale.py 按实测比值给已录段补写倍率(只补 meta 行、不碰 data 字节);触觉热力图显示量程改「下限固定 + 慢速自适应」(τ≈8s),修固定量程下量化把梯度压平、用力大小只剩接触面积在变;任务进度上报 404 后带 10 分钟冷却期重探,服务端补上端点后采集端无需重启自动恢复;SLAM 停落 slam_pose 列(定长 7 值列填不满 20/20/60ms 的位姿突发,实测 26.5% 的行被填成 [0]*7 会被下游当真实位姿读),slam_trajectory 成为位姿唯一落盘形态。承接 v1.3.0 的 UMI 夹爪全链接入(Fays S80M 双目 SLAM 位姿/轨迹 + Sightac 左右触觉力与 250×250 力矩阵 + DECXIN RGB;面板夹爪分组、资源缺失自动隐藏),支持双臂双夹爪同录(rig1 旧槽位/数据列契约不变,rig2 加 gripper_2_ 前缀;两 rig 独立 CPU 亲和分区零共享物理核 + raw 流专用核 + 30fps 空桶看门狗);SLAM 位姿坐标约定按新 ORB 核修正(X=右/Y=正对/Z=上,原点后姿态相对化,起始不跳变);左目显示稳 15fps(奇偶抽帧)且 raw 流断线自动重连;轨迹并入 episode parquet 列不再落 txt 侧车;夹爪脱离 online/ 自持(原生资源镜像 core/gripper/native/ 不入库、Sightac SDK pyarmor 加密随包、新增 tools/import_gripper_calibration.py 接入新夹爪标定);多台 S80M 按序列号/USB 拓扑路径区分(--device-serial/--device-path)。
|
collector/config/settings.py
CHANGED
|
@@ -285,6 +285,22 @@ def save_upload_delete_after(on: bool):
|
|
| 285 |
"""持久化"上传成功后自动删除本地文件"开关。"""
|
| 286 |
_save_server_config({"upload_delete_after": bool(on)})
|
| 287 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
def load_upload_project_id() -> str:
|
| 289 |
"""读取上传目标项目 ID(server_config.json)。
|
| 290 |
|
|
@@ -493,5 +509,41 @@ GRIPPER_SLOT_FORCE_L = "gripper_force_left" # Sightac 左(热力图+力曲
|
|
| 493 |
GRIPPER_SLOT_FORCE_R = "gripper_force_right" # Sightac 右(热力图+力曲线)
|
| 494 |
GRIPPER_STEREO_DISPLAY_FPS = 15.0 # 左目显示节流(SLAM 取帧在桥接进程内保持 30fps)
|
| 495 |
GRIPPER_SLAM_READY_TIMEOUT_S = 45.0 # wait_sdk_ready 上限(SDK 运行时重读标定)
|
| 496 |
-
GRIPPER_FORCE_MATRIX_DIM = 250 # 触觉力矩阵边长(250×250×3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
GRIPPER_TACTILE_MATRIX_MATERIALIZE = False # 矩阵逐帧拷回主进程开关(默认子进程直写)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
"""持久化"上传成功后自动删除本地文件"开关。"""
|
| 286 |
_save_server_config({"upload_delete_after": bool(on)})
|
| 287 |
|
| 288 |
+
def load_gripper_force_matrix_spec() -> str:
|
| 289 |
+
"""读取力矩阵落盘规格(server_config.json,默认 "int16x100")。
|
| 290 |
+
|
| 291 |
+
取值见 GRIPPER_FORCE_MATRIX_SPECS;非法值/缺失一律回默认档。
|
| 292 |
+
"""
|
| 293 |
+
raw = _load_server_config().get("gripper_force_matrix_spec")
|
| 294 |
+
if isinstance(raw, str) and raw in GRIPPER_FORCE_MATRIX_SPECS:
|
| 295 |
+
return raw
|
| 296 |
+
return GRIPPER_FORCE_MATRIX_SPEC_DEFAULT
|
| 297 |
+
|
| 298 |
+
def save_gripper_force_matrix_spec(spec: str):
|
| 299 |
+
"""持久化力矩阵落盘规格(非法值直接拒绝,不写坏配置)。"""
|
| 300 |
+
if spec not in GRIPPER_FORCE_MATRIX_SPECS:
|
| 301 |
+
raise ValueError(f"未知力矩阵规格 {spec!r},可选 {GRIPPER_FORCE_MATRIX_SPECS}")
|
| 302 |
+
_save_server_config({"gripper_force_matrix_spec": str(spec)})
|
| 303 |
+
|
| 304 |
def load_upload_project_id() -> str:
|
| 305 |
"""读取上传目标项目 ID(server_config.json)。
|
| 306 |
|
|
|
|
| 509 |
GRIPPER_SLOT_FORCE_R = "gripper_force_right" # Sightac 右(热力图+力曲线)
|
| 510 |
GRIPPER_STEREO_DISPLAY_FPS = 15.0 # 左目显示节流(SLAM 取帧在桥接进程内保持 30fps)
|
| 511 |
GRIPPER_SLAM_READY_TIMEOUT_S = 45.0 # wait_sdk_ready 上限(SDK 运行时重读标定)
|
| 512 |
+
GRIPPER_FORCE_MATRIX_DIM = 250 # 触觉力矩阵边长(250×250×3)
|
| 513 |
+
# 力矩阵落盘规格(工具栏可切换,持久化到 server_config.json)。
|
| 514 |
+
# 与实时显示无关:显示一直走 float32 原值,本档位只决定落盘规格。
|
| 515 |
+
# 录制开始时锁定,避免同一列出现两种类型(parquet 一列只有一种类型)。
|
| 516 |
+
#
|
| 517 |
+
# 命名:int16xN = 先乘 N 再取整存 int16,解码后除以 N 还原,分辨率 1/N mN。
|
| 518 |
+
# 落盘类型只有 int16 / float32 两种,倍率记在 info.json features.scale,
|
| 519 |
+
# 所以读取端(writer 定型、demo 反解)必须看 scale,不能只看列类型。
|
| 520 |
+
#
|
| 521 |
+
# 实测代价(episode-016 左列 611 帧,单列 ZSTD;右列同量级、倍数更高):
|
| 522 |
+
# int16 0.77MB 0.007 B/点 1 mN —— 既有契约,向零截断
|
| 523 |
+
# int16x10 13.95MB 0.122 B/点 0.1 mN —— 量程 ±3276.7 mN,重压场景用这个
|
| 524 |
+
# int16x100 34.78MB 0.304 B/点 0.01 mN —— 默认档
|
| 525 |
+
# int16x1000 53.84MB 0.470 B/点 0.001 mN —— 再往上不如直接 float32
|
| 526 |
+
# float32 91.26MB 0.797 B/点 原值
|
| 527 |
+
# 注:int16x1000 与 int32x1000 体积逐字节相同(差分后 delta 很小,int32
|
| 528 |
+
# 多出的 2 个零字节被 ZSTD 免费吃掉),但 int32 无精度收益,故不提供。
|
| 529 |
+
# 默认档为什么是 x100(2026-09-10 实测定档,样本=016/021 两段 float32 原值):
|
| 530 |
+
# 逐点误差约为传感器自身时间噪声(0.28 mN)的 0.9%,已在显示端(一级灰
|
| 531 |
+
# 0.0058 mN)之下;再降档没有物理收益,而体积是 float32 的 38%。代价是
|
| 532 |
+
# 量程只有 ±327.67 mN(SDK 力曲线量程 ±3000 mN),真按到几百 mN 会削平。
|
| 533 |
+
GRIPPER_FORCE_MATRIX_SPECS = ("int16", "int16x10", "int16x100",
|
| 534 |
+
"int16x1000", "float32")
|
| 535 |
+
GRIPPER_FORCE_MATRIX_SPEC_DEFAULT = "int16x100"
|
| 536 |
+
# 倍率表;float32 不在表内(无定标,编码器按此判定走原值分支)
|
| 537 |
+
GRIPPER_FORCE_MATRIX_SCALES = {"int16": 1, "int16x10": 10,
|
| 538 |
+
"int16x100": 100, "int16x1000": 1000}
|
| 539 |
+
GRIPPER_FORCE_MATRIX_SPEC = load_gripper_force_matrix_spec()
|
| 540 |
GRIPPER_TACTILE_MATRIX_MATERIALIZE = False # 矩阵逐帧拷回主进程开关(默认子进程直写)
|
| 541 |
+
# 触觉热力图显示量程(只影响显示,落盘力矩阵不受影响)
|
| 542 |
+
# True = 下限固定 + 慢速自适应:满量程取 REF 下限,非零像素 p99 明显更高时
|
| 543 |
+
# 才慢速抬高(换 SDK/硬件量级变化不会整片糊红)
|
| 544 |
+
# False = 用 0902 固定量程(bevel ×50 / curved ×200),与 online 上位机一致
|
| 545 |
+
GRIPPER_TACTILE_HEATMAP_AUTO = True
|
| 546 |
+
# 满量程参考值(矩阵单位,越小越灵敏)。bevel 3.0 → ×85:实测非零像素多为
|
| 547 |
+
# 1~3,正好铺满 JET 的青→橙→红;嫌不灵敏就调小,嫌噪点太亮就调大。
|
| 548 |
+
GRIPPER_TACTILE_HEATMAP_REF = {"bevel": 3.0, "curved": 12.0}
|
| 549 |
+
GRIPPER_TACTILE_HEATMAP_REF_MAX = {"bevel": 20.0, "curved": 80.0} # 自适应上限
|
collector/core/egodata_writer.py
CHANGED
|
@@ -86,6 +86,12 @@ _EPISODE_COLUMNS = [
|
|
| 86 |
("drop_stats", pa.string(), "{}"),
|
| 87 |
("video_codec", pa.string(), "{}"),
|
| 88 |
("calibration", pa.string(), "{}"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
]
|
| 90 |
_EPISODE_SCHEMA = pa.schema([(n, t) for n, t, _d in _EPISODE_COLUMNS])
|
| 91 |
|
|
@@ -158,7 +164,15 @@ class EgoDataWriter(QObject):
|
|
| 158 |
self._present_sensors: set = set()
|
| 159 |
self._present_imu: bool = False
|
| 160 |
self._present_glove_imu: set = set() # USB 手套 IMU 稀疏列(按传感器名)
|
| 161 |
-
self._present_gripper: set = set() # UMI 夹爪稀疏列(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
# 深度多槽位(D435 第 n 台 = d435_depth[_n];S80M 传统路径兜底
|
| 163 |
# settings.CAMERA_DEPTH):槽位键 → depth image_key
|
| 164 |
self._depth_slots: Dict[str, str] = {}
|
|
@@ -351,6 +365,8 @@ class EgoDataWriter(QObject):
|
|
| 351 |
self._present_imu = False
|
| 352 |
self._present_glove_imu = set()
|
| 353 |
self._present_gripper = set()
|
|
|
|
|
|
|
| 354 |
self._reset_stats()
|
| 355 |
self._last_task = task_name
|
| 356 |
|
|
@@ -542,6 +558,60 @@ class EgoDataWriter(QObject):
|
|
| 542 |
|
| 543 |
# ── 数据行写入 (LeRobot v3 兼容 Parquet) ────────────
|
| 544 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
def write_frame_row(self, frame_index: int, timestamp_s: float,
|
| 546 |
sensors: Optional[Dict[str, np.ndarray]] = None,
|
| 547 |
connection_status: Optional[Dict[str, str]] = None,
|
|
@@ -569,11 +639,19 @@ class EgoDataWriter(QObject):
|
|
| 569 |
USB 手套骨架快照,回填恒写的
|
| 570 |
observation.{left,right}_hand_pose 占位列
|
| 571 |
gripper: UMI 夹爪稀疏快照(P3/P4),键值:
|
| 572 |
-
|
| 573 |
gripper_state [open_pct, gripped, fz_mn]
|
| 574 |
gripper_{left,right}_force [fx,fy,fz] mN
|
| 575 |
-
gripper_{left,right}_force_matrix
|
| 576 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
"""
|
| 578 |
sensors = sensors or {}
|
| 579 |
row = {
|
|
@@ -639,24 +717,21 @@ class EgoDataWriter(QObject):
|
|
| 639 |
float(v) for v in k]
|
| 640 |
|
| 641 |
# UMI 夹爪稀疏列(P3/P4):本 episode 出现过的列才建列。
|
| 642 |
-
# 键按后缀定类型(
|
| 643 |
# _force_matrix=int16 行差分变长,P4 泵线程预编码后原样落盘);
|
| 644 |
-
# 双夹爪 rig2 带 "gripper_2_" 前缀,rig1 旧键(
|
| 645 |
-
#
|
|
|
|
| 646 |
for key, value in (gripper or {}).items():
|
| 647 |
if value is None:
|
| 648 |
continue
|
| 649 |
if key.endswith("_force_matrix"):
|
| 650 |
row[f"observation.{key}"] = value
|
|
|
|
| 651 |
elif key.endswith("slam_trajectory"):
|
| 652 |
# 本帧窗口内全部轨迹点的扁平 8 值列表
|
| 653 |
# [t,x,y,z,qx,qy,qz,qw]×N(float64 原样落盘)
|
| 654 |
row[f"observation.{key}"] = value
|
| 655 |
-
elif key.endswith("slam_pose"):
|
| 656 |
-
# 后缀不带下划线:rig1 旧键是裸 "slam_pose"(无前缀),
|
| 657 |
-
# rig2 为 "gripper_2_slam_pose"
|
| 658 |
-
row[f"observation.{key}"] = [
|
| 659 |
-
float(v) for v in value[:7]]
|
| 660 |
elif key.endswith("_state") or key.endswith("_force"):
|
| 661 |
row[f"observation.{key}"] = [
|
| 662 |
float(v) for v in value[:3]]
|
|
@@ -830,19 +905,18 @@ class EgoDataWriter(QObject):
|
|
| 830 |
cols[name_v] = pa.array(
|
| 831 |
[r.get(name_v, [0.0] * 16) for r in rows],
|
| 832 |
pa.list_(pa.float32(), 16))
|
| 833 |
-
# 稀疏 UMI 夹爪列(
|
|
|
|
| 834 |
for key in sorted(self._present_gripper):
|
| 835 |
name = f"observation.{key}"
|
| 836 |
if key.endswith("_force_matrix"):
|
|
|
|
|
|
|
| 837 |
cols[name] = pa.array(
|
| 838 |
-
[r.get(name, []) for r in rows], pa.list_(
|
| 839 |
elif key.endswith("slam_trajectory"):
|
| 840 |
cols[name] = pa.array(
|
| 841 |
[r.get(name, []) for r in rows], pa.list_(pa.float64()))
|
| 842 |
-
elif key.endswith("slam_pose"):
|
| 843 |
-
cols[name] = pa.array(
|
| 844 |
-
[r.get(name, [0.0] * 7) for r in rows],
|
| 845 |
-
pa.list_(pa.float32(), 7))
|
| 846 |
else: # _state / _force
|
| 847 |
cols[name] = pa.array(
|
| 848 |
[r.get(name, [0.0] * 3) for r in rows],
|
|
@@ -870,6 +944,8 @@ class EgoDataWriter(QObject):
|
|
| 870 |
与 data/videos 同编号(episode-000 = episode 1):每采一条新任务
|
| 871 |
就多一个 episode 文件。重录同 episode_index = 覆盖该文件。旧分片
|
| 872 |
(每 chunk 一个多行文件)里的同号行一并删除,避免双份。
|
|
|
|
|
|
|
| 873 |
跨进程安全:fcntl.flock 锁 meta/episodes/.lock(Windows 无
|
| 874 |
fcntl 退化为无锁,多机共享须 POSIX);写入走临时文件 +
|
| 875 |
os.replace 原子替换。
|
|
@@ -889,6 +965,8 @@ class EgoDataWriter(QObject):
|
|
| 889 |
"video_codec": json.dumps(self._video_codec_meta(),
|
| 890 |
ensure_ascii=False),
|
| 891 |
"calibration": json.dumps(self._calib_dict, ensure_ascii=False),
|
|
|
|
|
|
|
| 892 |
}
|
| 893 |
with self._task_lock():
|
| 894 |
_atomic_write_parquet(_episode_rows_table([row]), path)
|
|
@@ -958,21 +1036,18 @@ class EgoDataWriter(QObject):
|
|
| 958 |
"dtype": "float32", "shape": [16, 4]}
|
| 959 |
features[f"observation.{sn}_imu_valid"] = {
|
| 960 |
"dtype": "float32", "shape": [16]}
|
| 961 |
-
# UMI 夹爪(P3/P4):定长 f32 列 + 变长
|
|
|
|
|
|
|
|
|
|
| 962 |
for key in sorted(self._present_gripper):
|
| 963 |
if key.endswith("_force_matrix"):
|
| 964 |
-
features[f"observation.{key}"] =
|
| 965 |
-
"
|
| 966 |
-
"shape": [settings.GRIPPER_FORCE_MATRIX_DIM] * 2 + [3],
|
| 967 |
-
"encoding": "row_diff_quantized",
|
| 968 |
-
}
|
| 969 |
elif key.endswith("slam_trajectory"):
|
| 970 |
features[f"observation.{key}"] = {
|
| 971 |
"dtype": "float64", "shape": [8],
|
| 972 |
"encoding": "flat_points_8_txyz_qxyzw"}
|
| 973 |
-
elif key.endswith("slam_pose"):
|
| 974 |
-
features[f"observation.{key}"] = {
|
| 975 |
-
"dtype": "float32", "shape": [7]}
|
| 976 |
else: # _state / _force
|
| 977 |
features[f"observation.{key}"] = {
|
| 978 |
"dtype": "float32", "shape": [3]}
|
|
|
|
| 86 |
("drop_stats", pa.string(), "{}"),
|
| 87 |
("video_codec", pa.string(), "{}"),
|
| 88 |
("calibration", pa.string(), "{}"),
|
| 89 |
+
# v1.3.x 新增:本段力矩阵列的规格(列名 → dtype/shape/encoding/scale)。
|
| 90 |
+
# 必须每段一份 —— 倍率是「每段录制」的事实,而 info.json 是任务级、
|
| 91 |
+
# 值以最新 episode 为准,同任务里换了档位会把上一段的覆盖掉(实测
|
| 92 |
+
# ×10/×100/×1000 三段连录后 scale 全被最后一段顶成 1)。读取端应以
|
| 93 |
+
# 本列为准,info.json 只作回退。
|
| 94 |
+
("force_matrix_specs", pa.string(), "{}"),
|
| 95 |
]
|
| 96 |
_EPISODE_SCHEMA = pa.schema([(n, t) for n, t, _d in _EPISODE_COLUMNS])
|
| 97 |
|
|
|
|
| 164 |
self._present_sensors: set = set()
|
| 165 |
self._present_imu: bool = False
|
| 166 |
self._present_glove_imu: set = set() # USB 手套 IMU 稀疏列(按传感器名)
|
| 167 |
+
self._present_gripper: set = set() # UMI 夹爪稀疏列(state/force/matrix/trajectory)
|
| 168 |
+
# 力矩阵键 → 落盘家族("int16" 行差分量化 / "float32" 原值)。
|
| 169 |
+
# 由首帧实际元素类型判定(见 _note_matrix_dtype),不用全局开关推断——
|
| 170 |
+
# 历史 episode 与录制中改开关都不会串型。
|
| 171 |
+
self._matrix_dtype: Dict[str, str] = {}
|
| 172 |
+
# 力矩阵键 → 定标倍率(1/10/100/1000),录制开始时由采集侧登记
|
| 173 |
+
# (set_force_matrix_spec)。**落盘类型看不出倍率**:×10 与 ×1000
|
| 174 |
+
# 都是 list<int16>,只能靠 info.json features.scale 区分,缺省 1。
|
| 175 |
+
self._matrix_scale: Dict[str, int] = {}
|
| 176 |
# 深度多槽位(D435 第 n 台 = d435_depth[_n];S80M 传统路径兜底
|
| 177 |
# settings.CAMERA_DEPTH):槽位键 → depth image_key
|
| 178 |
self._depth_slots: Dict[str, str] = {}
|
|
|
|
| 365 |
self._present_imu = False
|
| 366 |
self._present_glove_imu = set()
|
| 367 |
self._present_gripper = set()
|
| 368 |
+
self._matrix_dtype = {}
|
| 369 |
+
self._matrix_scale = {} # 倍率由采集侧重新登记;防上一段残留
|
| 370 |
self._reset_stats()
|
| 371 |
self._last_task = task_name
|
| 372 |
|
|
|
|
| 558 |
|
| 559 |
# ── 数据行写入 (LeRobot v3 兼容 Parquet) ────────────
|
| 560 |
|
| 561 |
+
def set_force_matrix_spec(self, key: str, spec: str) -> None:
|
| 562 |
+
"""登记某力矩阵列的落盘规格(录制开始时由采集侧调一次)。
|
| 563 |
+
|
| 564 |
+
倍率只影响 info.json features.scale 与读取端还原,**不影响 parquet
|
| 565 |
+
列类型**——列类型仍由首帧元素类型定型(见 _note_matrix_dtype),
|
| 566 |
+
所以不登记也只是丢失倍率信息、默认按 1 还原,历史 episode 行为不变。
|
| 567 |
+
"""
|
| 568 |
+
scale = settings.GRIPPER_FORCE_MATRIX_SCALES.get(spec)
|
| 569 |
+
self._matrix_scale[key] = int(scale) if scale else 1
|
| 570 |
+
|
| 571 |
+
def _force_matrix_features(self) -> Dict[str, dict]:
|
| 572 |
+
"""本 episode 各力矩阵列的规格描述:列名 → dtype/shape/encoding/scale。
|
| 573 |
+
|
| 574 |
+
**scale 是读取端的必需信息**:×10 与 ×1000 的列类型都是
|
| 575 |
+
list<int16>、元素也都是 int,从数据上分辨不出倍率,只有 scale 能
|
| 576 |
+
决定该 ÷10 还是 ÷1000。float32 恒为 1(无定标,÷1 是恒等)。
|
| 577 |
+
|
| 578 |
+
单一来源:info.json 的 features 与 meta/episodes 行的
|
| 579 |
+
force_matrix_specs 都取这份,避免两处各写一份而后漂移。
|
| 580 |
+
"""
|
| 581 |
+
features = {}
|
| 582 |
+
for key in sorted(self._present_gripper):
|
| 583 |
+
if not key.endswith("_force_matrix"):
|
| 584 |
+
continue
|
| 585 |
+
float32 = self._matrix_dtype.get(key) == "float32"
|
| 586 |
+
features[f"observation.{key}"] = {
|
| 587 |
+
"dtype": "float32" if float32 else "int16",
|
| 588 |
+
"shape": [settings.GRIPPER_FORCE_MATRIX_DIM] * 2 + [3],
|
| 589 |
+
"encoding": ("row_flat_raw" if float32
|
| 590 |
+
else "row_diff_quantized"),
|
| 591 |
+
"scale": 1 if float32 else self._matrix_scale.get(key, 1),
|
| 592 |
+
}
|
| 593 |
+
return features
|
| 594 |
+
|
| 595 |
+
def _note_matrix_dtype(self, key: str, value) -> None:
|
| 596 |
+
"""按首帧实际元素类型锁定该力矩阵列的落盘规格。
|
| 597 |
+
|
| 598 |
+
int16 行差分编码走 np.int16.tolist() → Python int;
|
| 599 |
+
float32 原值走 np.float32.tolist() → Python float。
|
| 600 |
+
首帧空样本时不定型(后续有样本再定);定型后若类型变了说明
|
| 601 |
+
录制中切了开关——parquet 一列只能一种类型,这里显式报错而不是
|
| 602 |
+
让 pyarrow 抛难懂的转换异常。
|
| 603 |
+
"""
|
| 604 |
+
if not value:
|
| 605 |
+
return # 空样本:不定型
|
| 606 |
+
dtype = "float32" if isinstance(value[0], float) else "int16"
|
| 607 |
+
prev = self._matrix_dtype.get(key)
|
| 608 |
+
if prev is None:
|
| 609 |
+
self._matrix_dtype[key] = dtype
|
| 610 |
+
elif prev != dtype:
|
| 611 |
+
raise ValueError(
|
| 612 |
+
f"力矩阵列 {key} 在录制中改变了规格({prev} → {dtype});"
|
| 613 |
+
f"parquet 一列只能一种类型,请一段录制只用一种规格")
|
| 614 |
+
|
| 615 |
def write_frame_row(self, frame_index: int, timestamp_s: float,
|
| 616 |
sensors: Optional[Dict[str, np.ndarray]] = None,
|
| 617 |
connection_status: Optional[Dict[str, str]] = None,
|
|
|
|
| 639 |
USB 手套骨架快照,回填恒写的
|
| 640 |
observation.{left,right}_hand_pose 占位列
|
| 641 |
gripper: UMI 夹爪稀疏快照(P3/P4),键值:
|
| 642 |
+
slam_trajectory [t,x,y,z,qx,qy,qz,qw]×N 变长
|
| 643 |
gripper_state [open_pct, gripped, fz_mn]
|
| 644 |
gripper_{left,right}_force [fx,fy,fz] mN
|
| 645 |
+
gripper_{left,right}_force_matrix 力矩阵变长
|
| 646 |
+
列表(P4 泵线程预编码,无新样本不写键)。元素
|
| 647 |
+
类型只能区分「家族」,**倍率要另看 info.json
|
| 648 |
+
features.scale**:
|
| 649 |
+
int = int16 行差分量化(250×750 展平,cumsum
|
| 650 |
+
反解,再 ÷scale 还原 mN)。scale=1 是
|
| 651 |
+
向零截断的既有契约;scale=10/100/1000
|
| 652 |
+
为定标档(分辨率 1/scale mN)
|
| 653 |
+
float = float32 原值直存(250×750 展平,
|
| 654 |
+
reshape 反解;精度完整,scale 恒 1)
|
| 655 |
"""
|
| 656 |
sensors = sensors or {}
|
| 657 |
row = {
|
|
|
|
| 717 |
float(v) for v in k]
|
| 718 |
|
| 719 |
# UMI 夹爪稀疏列(P3/P4):本 episode 出现过的列才建列。
|
| 720 |
+
# 键按后缀定类型(_slam_trajectory=变长 f64 / _state/_force=3f32 /
|
| 721 |
# _force_matrix=int16 行差分变长,P4 泵线程预编码后原样落盘);
|
| 722 |
+
# 双夹爪 rig2 带 "gripper_2_" 前缀,rig1 旧键(gripper_state /
|
| 723 |
+
# gripper_left_force…)契约不变。无新样本不写键。
|
| 724 |
+
# 不认识的键(含 2026-09-10 起停落的 slam_pose)落到 else 静默忽略。
|
| 725 |
for key, value in (gripper or {}).items():
|
| 726 |
if value is None:
|
| 727 |
continue
|
| 728 |
if key.endswith("_force_matrix"):
|
| 729 |
row[f"observation.{key}"] = value
|
| 730 |
+
self._note_matrix_dtype(key, value)
|
| 731 |
elif key.endswith("slam_trajectory"):
|
| 732 |
# 本帧窗口内全部轨迹点的扁平 8 值列表
|
| 733 |
# [t,x,y,z,qx,qy,qz,qw]×N(float64 原样落盘)
|
| 734 |
row[f"observation.{key}"] = value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 735 |
elif key.endswith("_state") or key.endswith("_force"):
|
| 736 |
row[f"observation.{key}"] = [
|
| 737 |
float(v) for v in value[:3]]
|
|
|
|
| 905 |
cols[name_v] = pa.array(
|
| 906 |
[r.get(name_v, [0.0] * 16) for r in rows],
|
| 907 |
pa.list_(pa.float32(), 16))
|
| 908 |
+
# 稀疏 UMI 夹爪列(state/force 定长;slam_trajectory 与 matrix 变长,
|
| 909 |
+
# 后者类型按本 episode 实际规格:int16 行差分 / float32 原值)
|
| 910 |
for key in sorted(self._present_gripper):
|
| 911 |
name = f"observation.{key}"
|
| 912 |
if key.endswith("_force_matrix"):
|
| 913 |
+
item = (pa.float32() if self._matrix_dtype.get(key) == "float32"
|
| 914 |
+
else pa.int16())
|
| 915 |
cols[name] = pa.array(
|
| 916 |
+
[r.get(name, []) for r in rows], pa.list_(item))
|
| 917 |
elif key.endswith("slam_trajectory"):
|
| 918 |
cols[name] = pa.array(
|
| 919 |
[r.get(name, []) for r in rows], pa.list_(pa.float64()))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 920 |
else: # _state / _force
|
| 921 |
cols[name] = pa.array(
|
| 922 |
[r.get(name, [0.0] * 3) for r in rows],
|
|
|
|
| 944 |
与 data/videos 同编号(episode-000 = episode 1):每采一条新任务
|
| 945 |
就多一个 episode 文件。重录同 episode_index = 覆盖该文件。旧分片
|
| 946 |
(每 chunk 一个多行文件)里的同号行一并删除,避免双份。
|
| 947 |
+
本行的 force_matrix_specs 是该段力矩阵规格的**唯一权威**来源
|
| 948 |
+
(info.json 同名信息是任务级的,会被后一段录制覆盖)。
|
| 949 |
跨进程安全:fcntl.flock 锁 meta/episodes/.lock(Windows 无
|
| 950 |
fcntl 退化为无锁,多机共享须 POSIX);写入走临时文件 +
|
| 951 |
os.replace 原子替换。
|
|
|
|
| 965 |
"video_codec": json.dumps(self._video_codec_meta(),
|
| 966 |
ensure_ascii=False),
|
| 967 |
"calibration": json.dumps(self._calib_dict, ensure_ascii=False),
|
| 968 |
+
"force_matrix_specs": json.dumps(self._force_matrix_features(),
|
| 969 |
+
ensure_ascii=False),
|
| 970 |
}
|
| 971 |
with self._task_lock():
|
| 972 |
_atomic_write_parquet(_episode_rows_table([row]), path)
|
|
|
|
| 1036 |
"dtype": "float32", "shape": [16, 4]}
|
| 1037 |
features[f"observation.{sn}_imu_valid"] = {
|
| 1038 |
"dtype": "float32", "shape": [16]}
|
| 1039 |
+
# UMI 夹爪(P3/P4):定长 f32 列 + 变长轨迹/力矩阵(力矩阵规格见
|
| 1040 |
+
# _force_matrix_features —— 同一份描述也进 meta/episodes 行,
|
| 1041 |
+
# 这里不重写一遍以免两处漂移)
|
| 1042 |
+
matrix_features = self._force_matrix_features()
|
| 1043 |
for key in sorted(self._present_gripper):
|
| 1044 |
if key.endswith("_force_matrix"):
|
| 1045 |
+
features[f"observation.{key}"] = matrix_features[
|
| 1046 |
+
f"observation.{key}"]
|
|
|
|
|
|
|
|
|
|
| 1047 |
elif key.endswith("slam_trajectory"):
|
| 1048 |
features[f"observation.{key}"] = {
|
| 1049 |
"dtype": "float64", "shape": [8],
|
| 1050 |
"encoding": "flat_points_8_txyz_qxyzw"}
|
|
|
|
|
|
|
|
|
|
| 1051 |
else: # _state / _force
|
| 1052 |
features[f"observation.{key}"] = {
|
| 1053 |
"dtype": "float32", "shape": [3]}
|
collector/core/gripper/bridge.py
CHANGED
|
@@ -701,7 +701,7 @@ class GripperBridge(QObject):
|
|
| 701 |
"""录制开始清空 GUI 轨迹滚动窗口(只显示本段录制的点)。
|
| 702 |
|
| 703 |
parquet 的 slam_trajectory 列由 writer 在录制期独立累积
|
| 704 |
-
(见 pipeline.
|
| 705 |
显示侧。UI 侧配合 pose_view.reset() 同步清空渲染缓存。
|
| 706 |
"""
|
| 707 |
self._trajectory_points = []
|
|
|
|
| 701 |
"""录制开始清空 GUI 轨迹滚动窗口(只显示本段录制的点)。
|
| 702 |
|
| 703 |
parquet 的 slam_trajectory 列由 writer 在录制期独立累积
|
| 704 |
+
(见 pipeline.write_slam_trajectory),不受此窗口影响;这里只管
|
| 705 |
显示侧。UI 侧配合 pose_view.reset() 同步清空渲染缓存。
|
| 706 |
"""
|
| 707 |
self._trajectory_points = []
|
collector/core/gripper/tactile_process_worker.py
CHANGED
|
@@ -229,8 +229,89 @@ def clear_frame_queue(frame_queue, free_slots=None):
|
|
| 229 |
return
|
| 230 |
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
def pressure_to_heatmap(pressure_matrix, device_type="bevel", scale=None):
|
| 233 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
if pressure_matrix is None:
|
| 235 |
return None
|
| 236 |
if scale is None:
|
|
@@ -308,7 +389,8 @@ def process_tactile_frame(sensor, raw_frame, captured_at):
|
|
| 308 |
).astype(np.float32, copy=False)
|
| 309 |
heatmap_started = time.perf_counter()
|
| 310 |
heatmap = pressure_to_heatmap(
|
| 311 |
-
fz_matrix, getattr(sensor, "device_type", "bevel")
|
|
|
|
| 312 |
heatmap_ms = (time.perf_counter() - heatmap_started) * 1000.0
|
| 313 |
if heatmap is None:
|
| 314 |
return {"kind": "skip"}
|
|
|
|
| 229 |
return
|
| 230 |
|
| 231 |
|
| 232 |
+
# ── 热力图显示量程 ──────────────────────────────────────────────────
|
| 233 |
+
# 0902 的固定量程(bevel ×50 / curved ×200)是按已标定 mN 矩阵定的,而实测
|
| 234 |
+
# 逐点值比它小一到两个数量级(录制实证:非零像素多为 1~3、峰值 7),固定
|
| 235 |
+
# 量程下整幅图停在深蓝区,用力大小只剩接触面积在变、颜色几乎不动。改为
|
| 236 |
+
# 「下限固定 + 慢速自适应」:满量程参考值默认取 FLOOR(bevel 3.0 → ×85,
|
| 237 |
+
# 正好把 1~3 铺成青→橙→红),只有非零像素 p99 明显更高时才慢速抬高参考值
|
| 238 |
+
# (τ≈8s)——换 SDK/换硬件后量级变大也不会整片糊成红。无接触时回落到下限。
|
| 239 |
+
HEATMAP_REF_FLOOR = {"bevel": 3.0, "curved": 12.0}
|
| 240 |
+
HEATMAP_REF_CEILING = {"bevel": 20.0, "curved": 80.0}
|
| 241 |
+
HEATMAP_REF_ALPHA = 0.004 # 参考值跟随速度(30fps 下 τ≈8s)
|
| 242 |
+
HEATMAP_REF_MIN_PIXELS = 64 # 非零像素少于该值按无接触处理(噪声)
|
| 243 |
+
_HEATMAP_AUTO_CACHE = {}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _heatmap_tuning():
|
| 247 |
+
"""显示量程标定表(config.settings 可覆盖,缺失时用模块内默认)。"""
|
| 248 |
+
try:
|
| 249 |
+
from config import settings
|
| 250 |
+
floor = getattr(settings, "GRIPPER_TACTILE_HEATMAP_REF", None)
|
| 251 |
+
ceiling = getattr(settings, "GRIPPER_TACTILE_HEATMAP_REF_MAX", None)
|
| 252 |
+
if isinstance(floor, dict) and isinstance(ceiling, dict):
|
| 253 |
+
return floor, ceiling
|
| 254 |
+
except Exception:
|
| 255 |
+
pass
|
| 256 |
+
return HEATMAP_REF_FLOOR, HEATMAP_REF_CEILING
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def heatmap_auto_enabled():
|
| 260 |
+
"""显示量程是否自适应(config.settings.GRIPPER_TACTILE_HEATMAP_AUTO)。"""
|
| 261 |
+
if "value" not in _HEATMAP_AUTO_CACHE:
|
| 262 |
+
try:
|
| 263 |
+
from config import settings
|
| 264 |
+
value = bool(getattr(
|
| 265 |
+
settings, "GRIPPER_TACTILE_HEATMAP_AUTO", True))
|
| 266 |
+
except Exception:
|
| 267 |
+
value = True
|
| 268 |
+
_HEATMAP_AUTO_CACHE["value"] = value
|
| 269 |
+
return _HEATMAP_AUTO_CACHE["value"]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class HeatmapScaleTracker:
|
| 273 |
+
"""每侧热力图的显示量程(子进程内每个传感器一个,逐帧更新)。"""
|
| 274 |
+
|
| 275 |
+
def __init__(self, device_type="bevel", floor=None, ceiling=None):
|
| 276 |
+
self.device_type = str(device_type)
|
| 277 |
+
floor_table, ceiling_table = _heatmap_tuning()
|
| 278 |
+
self.floor = float(floor if floor is not None
|
| 279 |
+
else floor_table.get(self.device_type, 3.0))
|
| 280 |
+
self.ceiling = float(ceiling if ceiling is not None
|
| 281 |
+
else ceiling_table.get(self.device_type, 20.0))
|
| 282 |
+
self.ref = self.floor
|
| 283 |
+
|
| 284 |
+
def scale(self, pressure_matrix):
|
| 285 |
+
"""返回本帧显示增益(255/满量程参考值)。"""
|
| 286 |
+
plane = np.asarray(pressure_matrix, dtype=np.float32)
|
| 287 |
+
nonzero = plane[plane > 0]
|
| 288 |
+
target = self.floor
|
| 289 |
+
if nonzero.size >= HEATMAP_REF_MIN_PIXELS:
|
| 290 |
+
target = min(max(float(np.percentile(nonzero, 99)),
|
| 291 |
+
self.floor), self.ceiling)
|
| 292 |
+
self.ref += HEATMAP_REF_ALPHA * (target - self.ref)
|
| 293 |
+
return 255.0 / max(self.ref, 1e-6)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def heatmap_scale_for(sensor, pressure_matrix):
|
| 297 |
+
"""本帧显示增益:自适应开启时按传感器跟踪,关闭时回固定量程(None)。"""
|
| 298 |
+
if not heatmap_auto_enabled():
|
| 299 |
+
return None
|
| 300 |
+
tracker = getattr(sensor, "_ksq_heatmap_scale", None)
|
| 301 |
+
if tracker is None:
|
| 302 |
+
tracker = HeatmapScaleTracker(
|
| 303 |
+
getattr(sensor, "device_type", "bevel"))
|
| 304 |
+
# _ksq_ 前缀:snapshot_sensor_state 不跨进程搬运该状态
|
| 305 |
+
sensor._ksq_heatmap_scale = tracker
|
| 306 |
+
return tracker.scale(pressure_matrix)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
def pressure_to_heatmap(pressure_matrix, device_type="bevel", scale=None):
|
| 310 |
+
"""压力平面 → 320×240 RGB 热力图(JET)。
|
| 311 |
+
|
| 312 |
+
scale=None 用固定量程(curved 200 / bevel 50);实时链路传入
|
| 313 |
+
heatmap_scale_for() 给出的自适应增益(见上方量程说明)。
|
| 314 |
+
"""
|
| 315 |
if pressure_matrix is None:
|
| 316 |
return None
|
| 317 |
if scale is None:
|
|
|
|
| 389 |
).astype(np.float32, copy=False)
|
| 390 |
heatmap_started = time.perf_counter()
|
| 391 |
heatmap = pressure_to_heatmap(
|
| 392 |
+
fz_matrix, getattr(sensor, "device_type", "bevel"),
|
| 393 |
+
scale=heatmap_scale_for(sensor, fz_matrix))
|
| 394 |
heatmap_ms = (time.perf_counter() - heatmap_started) * 1000.0
|
| 395 |
if heatmap is None:
|
| 396 |
return {"kind": "skip"}
|
collector/core/helpers.py
CHANGED
|
@@ -458,7 +458,8 @@ def pooled_data_parquet_path(task_dir: str, episode_index: int) -> str:
|
|
| 458 |
|
| 459 |
def pooled_episodes_path(task_dir: str, episode_index: int) -> str:
|
| 460 |
"""meta/episodes/chunk-NNN/episode-NNN.parquet(每 episode 一个文件,
|
| 461 |
-
与 data/videos 同编号:episode-000 = episode 1;单行
|
|
|
|
| 462 |
c, f = episode_chunk_file(episode_index)
|
| 463 |
return os.path.join(task_dir, "meta", "episodes", chunk_dir(c),
|
| 464 |
pooled_file_stem(f, ".parquet"))
|
|
|
|
| 458 |
|
| 459 |
def pooled_episodes_path(task_dir: str, episode_index: int) -> str:
|
| 460 |
"""meta/episodes/chunk-NNN/episode-NNN.parquet(每 episode 一个文件,
|
| 461 |
+
与 data/videos 同编号:episode-000 = episode 1;单行 11 列,末列
|
| 462 |
+
force_matrix_specs 为该段力矩阵规格的权威来源)。"""
|
| 463 |
c, f = episode_chunk_file(episode_index)
|
| 464 |
return os.path.join(task_dir, "meta", "episodes", chunk_dir(c),
|
| 465 |
pooled_file_stem(f, ".parquet"))
|
collector/core/pipeline.py
CHANGED
|
@@ -157,8 +157,9 @@ class CameraPipeline(QObject):
|
|
| 157 |
self._glove_kpts: Dict[str, np.ndarray] = {}
|
| 158 |
self._glove_kpts_lock = threading.Lock()
|
| 159 |
# UMI 夹爪稀疏列快照(P3/P4):latest-wins,写入线程每帧取走清空
|
| 160 |
-
# 键:
|
| 161 |
# gripper_{left,right}_force_matrix(P4 泵线程预编码 int16 列表)
|
|
|
|
| 162 |
# 双夹爪 rig2 加 "gripper_2_" 前缀(rig1 旧键不变,见 write_*)
|
| 163 |
self._gripper_snapshots: Dict[str, object] = {}
|
| 164 |
self._gripper_snapshots_lock = threading.Lock()
|
|
@@ -815,22 +816,23 @@ class CameraPipeline(QObject):
|
|
| 815 |
with self._gripper_snapshots_lock:
|
| 816 |
self._gripper_snapshots[key] = value
|
| 817 |
|
| 818 |
-
def
|
| 819 |
-
"""SLAM
|
| 820 |
|
| 821 |
-
prefix 为双夹爪命名空间:rig1 空串(旧键
|
| 822 |
-
rig2 "gripper_2_" →
|
| 823 |
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
|
|
|
|
|
|
| 827 |
"""
|
| 828 |
if pose7 is None:
|
| 829 |
return
|
| 830 |
values = [float(value) for value in pose7[:7]]
|
| 831 |
if len(values) != 7 or not all(np.isfinite(values)):
|
| 832 |
return
|
| 833 |
-
self._put_gripper_snapshot(f"{prefix}slam_pose", values)
|
| 834 |
if timestamp is not None:
|
| 835 |
try:
|
| 836 |
t = float(timestamp)
|
|
@@ -865,12 +867,25 @@ class CameraPipeline(QObject):
|
|
| 865 |
|
| 866 |
def write_tactile_force_matrix(self, side: str, encoded,
|
| 867 |
prefix: str = ""):
|
| 868 |
-
"""触觉力矩阵快照(P4 泵线程预编码的
|
| 869 |
if encoded is None or side not in ("left", "right"):
|
| 870 |
return
|
| 871 |
self._put_gripper_snapshot(
|
| 872 |
f"{prefix}gripper_{side}_force_matrix", encoded)
|
| 873 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
def _pop_gripper_snapshots(self) -> Dict[str, object]:
|
| 875 |
"""取走并清空本帧窗口内的夹爪快照(写入线程调用)。
|
| 876 |
|
|
|
|
| 157 |
self._glove_kpts: Dict[str, np.ndarray] = {}
|
| 158 |
self._glove_kpts_lock = threading.Lock()
|
| 159 |
# UMI 夹爪稀疏列快照(P3/P4):latest-wins,写入线程每帧取走清空
|
| 160 |
+
# 键:gripper_state / gripper_{left,right}_force /
|
| 161 |
# gripper_{left,right}_force_matrix(P4 泵线程预编码 int16 列表)
|
| 162 |
+
# (slam_pose 已于 2026-09-10 停止落盘,位姿只走 _gripper_traj)
|
| 163 |
# 双夹爪 rig2 加 "gripper_2_" 前缀(rig1 旧键不变,见 write_*)
|
| 164 |
self._gripper_snapshots: Dict[str, object] = {}
|
| 165 |
self._gripper_snapshots_lock = threading.Lock()
|
|
|
|
| 816 |
with self._gripper_snapshots_lock:
|
| 817 |
self._gripper_snapshots[key] = value
|
| 818 |
|
| 819 |
+
def write_slam_trajectory(self, pose7, prefix: str = "", timestamp=None):
|
| 820 |
+
"""SLAM 轨迹点 [t,x,y,z,qx,qy,qz,qw] 累积(P3;桥接 pose_ready 回调)。
|
| 821 |
|
| 822 |
+
prefix 为双夹爪命名空间:rig1 空串(旧键 slam_trajectory 不变),
|
| 823 |
+
rig2 "gripper_2_" → gripper_2_slam_trajectory。
|
| 824 |
|
| 825 |
+
只累积轨迹、不再落 slam_pose 快照列(2026-09-10 定案):位姿流是
|
| 826 |
+
20/20/60ms 突发而 parquet 行是 1/30s 均匀网格,定长 7 值列填不满,
|
| 827 |
+
缺位姿的行会被填成 [0]*7 被下游当真实位姿读;轨迹点带真实时间戳、
|
| 828 |
+
信息严格更多,是 SLAM 位姿的唯一落盘形态。轨迹不再单独落 txt
|
| 829 |
+
侧车,全部信息都在一条 episode parquet 里。
|
| 830 |
"""
|
| 831 |
if pose7 is None:
|
| 832 |
return
|
| 833 |
values = [float(value) for value in pose7[:7]]
|
| 834 |
if len(values) != 7 or not all(np.isfinite(values)):
|
| 835 |
return
|
|
|
|
| 836 |
if timestamp is not None:
|
| 837 |
try:
|
| 838 |
t = float(timestamp)
|
|
|
|
| 867 |
|
| 868 |
def write_tactile_force_matrix(self, side: str, encoded,
|
| 869 |
prefix: str = ""):
|
| 870 |
+
"""触觉力矩阵快照(P4 泵线程预编码的行差分/原值列表)。"""
|
| 871 |
if encoded is None or side not in ("left", "right"):
|
| 872 |
return
|
| 873 |
self._put_gripper_snapshot(
|
| 874 |
f"{prefix}gripper_{side}_force_matrix", encoded)
|
| 875 |
|
| 876 |
+
def set_force_matrix_spec(self, prefix: str, spec: str) -> None:
|
| 877 |
+
"""登记本段录制的力矩阵规格(录制开始时调一次,须在 start_episode 后)。
|
| 878 |
+
|
| 879 |
+
只有 writer 需要知道倍率——×10/×100/×1000 的落盘类型都是 int16,
|
| 880 |
+
元素类型分辨不出倍率,倍率得随 info.json features.scale 落盘,
|
| 881 |
+
训练侧才知道该 ÷N 还是 ÷M。
|
| 882 |
+
"""
|
| 883 |
+
if self._writer is None:
|
| 884 |
+
return
|
| 885 |
+
for side in ("left", "right"):
|
| 886 |
+
self._writer.set_force_matrix_spec(
|
| 887 |
+
f"{prefix}gripper_{side}_force_matrix", spec)
|
| 888 |
+
|
| 889 |
def _pop_gripper_snapshots(self) -> Dict[str, object]:
|
| 890 |
"""取走并清空本帧窗口内的夹爪快照(写入线程调用)。
|
| 891 |
|
collector/core/task_service.py
CHANGED
|
@@ -11,6 +11,7 @@
|
|
| 11 |
|
| 12 |
from __future__ import annotations
|
| 13 |
import threading
|
|
|
|
| 14 |
|
| 15 |
import requests
|
| 16 |
from PyQt5.QtCore import QObject, pyqtSignal, QTimer
|
|
@@ -20,6 +21,10 @@ from core import task_record
|
|
| 20 |
|
| 21 |
CONNECT_TIMEOUT = 10 # HTTP 请求超时(秒)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
def _normalize_tasks(raw: list[dict]) -> list[dict]:
|
| 25 |
"""Map backend fields to internal field names.
|
|
@@ -96,6 +101,7 @@ class TaskService(QObject):
|
|
| 96 |
|
| 97 |
# 进度增量上报(多电脑协同聚合)
|
| 98 |
self._progress_supported = True # 后端 404 → False 静默降级本地口径
|
|
|
|
| 99 |
self._flush_fail: dict[str, int] = {} # task_id → 连续失败次数(防日志刷屏)
|
| 100 |
self._flush_lock = threading.Lock() # 防 flush_now 与轮询 tick 并发重复 POST
|
| 101 |
self._poll_fail = 0 # 轮询连续失败次数(防日志刷屏)
|
|
@@ -187,6 +193,7 @@ class TaskService(QObject):
|
|
| 187 |
self._session.cookies.clear()
|
| 188 |
self._logged_in = False
|
| 189 |
self._progress_supported = True # 新后端可能已实现进度端点
|
|
|
|
| 190 |
self._trigger_login_and_poll()
|
| 191 |
|
| 192 |
def set_credentials(self, username: str, password: str):
|
|
@@ -260,10 +267,14 @@ class TaskService(QObject):
|
|
| 260 |
"""水位合并上报:每任务一次 POST increment = local - synced。
|
| 261 |
|
| 262 |
幂等键含设备名与水位(重试不重复计数);崩溃安全由 tasks.json 落盘
|
| 263 |
-
保证;401/403 跳过本轮不标记死(重新登录后自然恢复)
|
|
|
|
| 264 |
"""
|
| 265 |
if not self._progress_supported:
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
| 267 |
if not self._flush_lock.acquire(blocking=False):
|
| 268 |
return # 已有一次 flush 在途(tick 或 flush_now),让给先到者
|
| 269 |
try:
|
|
@@ -276,11 +287,17 @@ class TaskService(QObject):
|
|
| 276 |
new_backend, err = self._post_progress(tid, session_id, inc, device)
|
| 277 |
if err == "404":
|
| 278 |
self._progress_supported = False # 后端未升级 → 静默降级本地口径
|
|
|
|
|
|
|
| 279 |
return
|
| 280 |
if new_backend is None:
|
| 281 |
self._note_fail(tid) # auth/net/http:跳过本轮,下个 tick 重试
|
| 282 |
continue
|
| 283 |
self._flush_fail.pop(tid, None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
task_record.mark_synced(tid, p["synced_count"] + inc, new_backend)
|
| 285 |
changed = True
|
| 286 |
if changed:
|
|
|
|
| 11 |
|
| 12 |
from __future__ import annotations
|
| 13 |
import threading
|
| 14 |
+
import time
|
| 15 |
|
| 16 |
import requests
|
| 17 |
from PyQt5.QtCore import QObject, pyqtSignal, QTimer
|
|
|
|
| 21 |
|
| 22 |
CONNECT_TIMEOUT = 10 # HTTP 请求超时(秒)
|
| 23 |
|
| 24 |
+
# 进度端点 404 后的冷却期:不是永久拉黑,过这段时间再探一次。
|
| 25 |
+
# 服务端补上端点后,采集端**不必重启**就能自动恢复上报。
|
| 26 |
+
PROGRESS_RETRY_INTERVAL_S = 600
|
| 27 |
+
|
| 28 |
|
| 29 |
def _normalize_tasks(raw: list[dict]) -> list[dict]:
|
| 30 |
"""Map backend fields to internal field names.
|
|
|
|
| 101 |
|
| 102 |
# 进度增量上报(多电脑协同聚合)
|
| 103 |
self._progress_supported = True # 后端 404 → False 静默降级本地口径
|
| 104 |
+
self._progress_retry_at = 0.0 # 降级期间下一次试探的时刻(monotonic)
|
| 105 |
self._flush_fail: dict[str, int] = {} # task_id → 连续失败次数(防日志刷屏)
|
| 106 |
self._flush_lock = threading.Lock() # 防 flush_now 与轮询 tick 并发重复 POST
|
| 107 |
self._poll_fail = 0 # 轮询连续失败次数(防日志刷屏)
|
|
|
|
| 193 |
self._session.cookies.clear()
|
| 194 |
self._logged_in = False
|
| 195 |
self._progress_supported = True # 新后端可能已实现进度端点
|
| 196 |
+
self._progress_retry_at = 0.0
|
| 197 |
self._trigger_login_and_poll()
|
| 198 |
|
| 199 |
def set_credentials(self, username: str, password: str):
|
|
|
|
| 267 |
"""水位合并上报:每任务一次 POST increment = local - synced。
|
| 268 |
|
| 269 |
幂等键含设备名与水位(重试不重复计数);崩溃安全由 tasks.json 落盘
|
| 270 |
+
保证;401/403 跳过本轮不标记死(重新登录后自然恢复);404 降级但带
|
| 271 |
+
冷却期重探(PROGRESS_RETRY_INTERVAL_S),后端补上端点后自动恢复。
|
| 272 |
"""
|
| 273 |
if not self._progress_supported:
|
| 274 |
+
# 曾经 404:后端没这个端点。不永久拉黑 —— 冷却期过后再探一次,
|
| 275 |
+
# 服务端补上端点后采集端无需重启即可自动恢复上报。
|
| 276 |
+
if time.monotonic() < self._progress_retry_at:
|
| 277 |
+
return
|
| 278 |
if not self._flush_lock.acquire(blocking=False):
|
| 279 |
return # 已有一次 flush 在途(tick 或 flush_now),让给先到者
|
| 280 |
try:
|
|
|
|
| 287 |
new_backend, err = self._post_progress(tid, session_id, inc, device)
|
| 288 |
if err == "404":
|
| 289 |
self._progress_supported = False # 后端未升级 → 静默降级本地口径
|
| 290 |
+
self._progress_retry_at = (
|
| 291 |
+
time.monotonic() + PROGRESS_RETRY_INTERVAL_S)
|
| 292 |
return
|
| 293 |
if new_backend is None:
|
| 294 |
self._note_fail(tid) # auth/net/http:跳过本轮,下个 tick 重试
|
| 295 |
continue
|
| 296 |
self._flush_fail.pop(tid, None)
|
| 297 |
+
if not self._progress_supported:
|
| 298 |
+
# 冷却期里的那次试探成功了 → 后端已实现该端点,结束降级
|
| 299 |
+
self._progress_supported = True
|
| 300 |
+
self._progress_retry_at = 0.0
|
| 301 |
task_record.mark_synced(tid, p["synced_count"] + inc, new_backend)
|
| 302 |
changed = True
|
| 303 |
if changed:
|
collector/docs/core.md
CHANGED
|
@@ -551,9 +551,10 @@ GET `/api/v1/device/tasks?device_name=…`。设计模式参照已移除的 `Syn
|
|
| 551 |
| 名称 | 类型 | 默认值 | 说明 |
|
| 552 |
| --- | --- | --- | --- |
|
| 553 |
| `CONNECT_TIMEOUT` | int | 10 | HTTP 请求超时(秒) |
|
|
|
|
| 554 |
| 轮询间隔 | int | `settings.TASK_POLL_INTERVAL_MS`(默认 30000) | 读不到时 `getattr` 兜底 5000 毫秒(代码兜底值,非配置默认) |
|
| 555 |
| 设备认领名 | str | `settings.DEVICE_NAME` | 读不到时回退 `"EGO_001"`;作为 `device_name` 查询参数 |
|
| 556 |
-
| API 端点 | — | `POST /api/v1/auth/login`、`GET /api/v1/device/tasks`、`POST /api/v1/device/tasks/progress` | 登录 body 含 `username/password/remember_me`;进度上报 body 含 `task_id/session_id/increment/device_name`,`session_id = "{device}:{task_id}:{水位}"` 幂等(后端按 `(device_name, session_id)` 去重,重复请求返回当前全局数不重复加;游客上报公共任务应放行);404 → `_progress_supported=False`
|
| 557 |
| `User-Agent` | str | `"DAQ-SDK/1.0"` | — |
|
| 558 |
|
| 559 |
**调用关系**:被 `ui/main_window.py` 实例化。依赖 `requests` 与 `PyQt5.QtCore`。
|
|
@@ -967,7 +968,13 @@ rows/cols 映射,点击"选择"弹出子级 `MatrixConfigDialog` 逐部位编
|
|
| 967 |
`increment_task_completed` 本机 `local_count` +1 → 显示值重算,与本地会话
|
| 968 |
文件是否被删无关),随后 `TaskService._flush_progress` 把本机未上报增量
|
| 969 |
以水位合并方式 POST `/api/v1/device/tasks/progress`(幂等键
|
| 970 |
-
`{device}:{task_id}:{水位}`,断网/失败由下个轮询 tick 兜底重试
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
|
| 972 |
**上传链路**:`ui/upload_dialog.py` 经 `core/uploader.py`
|
| 973 |
(`UploadManager`:ffmpeg 预压缩 → zip 打包 → `core/api_client.py` 上传 →
|
|
|
|
| 551 |
| 名称 | 类型 | 默认值 | 说明 |
|
| 552 |
| --- | --- | --- | --- |
|
| 553 |
| `CONNECT_TIMEOUT` | int | 10 | HTTP 请求超时(秒) |
|
| 554 |
+
| `PROGRESS_RETRY_INTERVAL_S` | float | 600 | 进度端点 404 后进入降级,冷却期满再探一次(见 `_progress_retry_at`) |
|
| 555 |
| 轮询间隔 | int | `settings.TASK_POLL_INTERVAL_MS`(默认 30000) | 读不到时 `getattr` 兜底 5000 毫秒(代码兜底值,非配置默认) |
|
| 556 |
| 设备认领名 | str | `settings.DEVICE_NAME` | 读不到时回退 `"EGO_001"`;作为 `device_name` 查询参数 |
|
| 557 |
+
| API 端点 | — | `POST /api/v1/auth/login`、`GET /api/v1/device/tasks`、`POST /api/v1/device/tasks/progress` | 登录 body 含 `username/password/remember_me`;进度上报 body 含 `task_id/session_id/increment/device_name`,`session_id = "{device}:{task_id}:{水位}"` 幂等(后端按 `(device_name, session_id)` 去重,重复请求返回当前全局数不重复加;游客上报公共任务应放行);404 → `_progress_supported=False` 降级本地口径,冷却期过后自动重探恢复(不必重启);`set_server_url` 立即解除降级 |
|
| 558 |
| `User-Agent` | str | `"DAQ-SDK/1.0"` | — |
|
| 559 |
|
| 560 |
**调用关系**:被 `ui/main_window.py` 实例化。依赖 `requests` 与 `PyQt5.QtCore`。
|
|
|
|
| 968 |
`increment_task_completed` 本机 `local_count` +1 → 显示值重算,与本地会话
|
| 969 |
文件是否被删无关),随后 `TaskService._flush_progress` 把本机未上报增量
|
| 970 |
以水位合并方式 POST `/api/v1/device/tasks/progress`(幂等键
|
| 971 |
+
`{device}:{task_id}:{水位}`,断网/失败由下个轮询 tick 兜底重试;端点不存在
|
| 972 |
+
时降级 10 分钟后再探,服务端升级后自动恢复上报,无需重启采集端)。
|
| 973 |
+
|
| 974 |
+
**进度口径**:进度只由「录制完成」推动 —— 上传不改变任务进度。后端
|
| 975 |
+
`GET /api/v1/device/tasks` 的 `current_count` 取各设备上报录制数之和
|
| 976 |
+
(从未收到上报的历史项目才回退到项目目录下的 session 数),`progress_source`
|
| 977 |
+
字段标明该项目当前用的是 `"reported"` 还是 `"sessions"`。
|
| 978 |
|
| 979 |
**上传链路**:`ui/upload_dialog.py` 经 `core/uploader.py`
|
| 980 |
(`UploadManager`:ffmpeg 预压缩 → zip 打包 → `core/api_client.py` 上传 →
|
collector/docs/file_format.html
CHANGED
|
@@ -337,12 +337,12 @@ fnum = (N - 1) % 1000 <span class="c"># 三位零起:episode-000 .. epis
|
|
| 337 |
<div class="sec-head"><span class="sec-no">§6</span><h2>meta/episodes/(每段一个文件)</h2></div>
|
| 338 |
<h3>6.1 文件与原子性</h3>
|
| 339 |
<ul>
|
| 340 |
-
<li>每 episode 一个文件 <code>chunk-{c:03d}/episode-{f:03d}.parquet</code>(与 data/videos 同编号:episode-000 = episode 1),<strong>恒 1 行</strong>(
|
| 341 |
<li>episode 结束时单行原子写:临时文件 + <code>os.replace</code> 原子替换;同号重录 = 覆盖该文件。读取方<span class="tag must">MUST</span>容忍文件在任意时刻被原子替换(每次打开重新读取,勿缓存 fd)。</li>
|
| 342 |
<li>新布局写入<span class="tag must">MUST NOT</span>依赖 flock(单文件原子替换即完整);flock 锚点 <code>.lock</code> 仅剩旧分片回退的读-改-写路径使用(见 §7.4)。</li>
|
| 343 |
<li><b>旧分片回退(读侧<span class="tag must">MUST</span>容忍)</b>:v1.1.0 早期目录可能存在「每 chunk 一个分片」(文件名 = chunk 编号,≤1000 行,行序按 <code>episode_index</code> 升序)。读侧定位行必须按 <code>episode_index</code> 列过滤、<strong>不靠文件名</strong>(v1.1.2 起分片保留 file- 前缀、每段文件改 episode- 前缀,路径不再重名)。迁移工具 <code>--split-episodes</code> 可原地拆分(幂等)。</li>
|
| 344 |
</ul>
|
| 345 |
-
<h3>6.2 列(
|
| 346 |
<div class="tblwrap"><table>
|
| 347 |
<tr><th>列</th><th>类型</th><th>说明</th></tr>
|
| 348 |
<tr><td><code>episode_index</code></td><td>int64</td><td>全局序号 N(1 起)</td></tr>
|
|
@@ -355,7 +355,9 @@ fnum = (N - 1) % 1000 <span class="c"># 三位零起:episode-000 .. epis
|
|
| 355 |
<tr><td><code>drop_stats</code></td><td>str</td><td>JSON 字符串(如 <code>{"imu_overflow": 0}</code>),读取方须 <code>json.loads</code></td></tr>
|
| 356 |
<tr><td><code>video_codec</code></td><td>str</td><td>JSON 字符串:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8</td></tr>
|
| 357 |
<tr><td><code>calibration</code></td><td>str</td><td>JSON 字符串:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真</td></tr>
|
|
|
|
| 358 |
</table></div>
|
|
|
|
| 359 |
</section>
|
| 360 |
|
| 361 |
<section id="s7">
|
|
@@ -382,6 +384,19 @@ fnum = (N - 1) % 1000 <span class="c"># 三位零起:episode-000 .. epis
|
|
| 382 |
<tr><td><code>action</code></td><td>list<float32, 1></td><td>恒写(现为 0)</td></tr>
|
| 383 |
<tr><td><code>status.<did></code></td><td>str</td><td>稀疏设备状态列(<code>"connected"</code>/<code>"disconnected"</code> 等)</td></tr>
|
| 384 |
</table></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
<h3>7.3 时间对齐模型</h3>
|
| 386 |
<p><strong>表为帧行为主</strong>:一行 = 一个 30fps 帧;视频帧/传感器读数/帧行共用同一 <code>frame_index</code>(写入线程同拍产出)。IMU 为变长 list 列挂在帧行上,录制时按 <code>hardware_ns</code> 设备时钟窗口挂靠。读取零重采样;宿主时间锚定靠 <code>timestamp</code> + <code>wall_time</code>。客户 9 列平表由导出工具展开插值合成,非本契约内容。</p>
|
| 387 |
<h3>7.4 meta/episodes/.lock(运行时辅助文件,非数据)</h3>
|
|
|
|
| 337 |
<div class="sec-head"><span class="sec-no">§6</span><h2>meta/episodes/(每段一个文件)</h2></div>
|
| 338 |
<h3>6.1 文件与原子性</h3>
|
| 339 |
<ul>
|
| 340 |
+
<li>每 episode 一个文件 <code>chunk-{c:03d}/episode-{f:03d}.parquet</code>(与 data/videos 同编号:episode-000 = episode 1),<strong>恒 1 行</strong>(11 列,见 §6.2)。</li>
|
| 341 |
<li>episode 结束时单行原子写:临时文件 + <code>os.replace</code> 原子替换;同号重录 = 覆盖该文件。读取方<span class="tag must">MUST</span>容忍文件在任意时刻被原子替换(每次打开重新读取,勿缓存 fd)。</li>
|
| 342 |
<li>新布局写入<span class="tag must">MUST NOT</span>依赖 flock(单文件原子替换即完整);flock 锚点 <code>.lock</code> 仅剩旧分片回退的读-改-写路径使用(见 §7.4)。</li>
|
| 343 |
<li><b>旧分片回退(读侧<span class="tag must">MUST</span>容忍)</b>:v1.1.0 早期目录可能存在「每 chunk 一个分片」(文件名 = chunk 编号,≤1000 行,行序按 <code>episode_index</code> 升序)。读侧定位行必须按 <code>episode_index</code> 列过滤、<strong>不靠文件名</strong>(v1.1.2 起分片保留 file- 前缀、每段文件改 episode- 前缀,路径不再重名)。迁移工具 <code>--split-episodes</code> 可原地拆分(幂等)。</li>
|
| 344 |
</ul>
|
| 345 |
+
<h3>6.2 列(11 列)</h3>
|
| 346 |
<div class="tblwrap"><table>
|
| 347 |
<tr><th>列</th><th>类型</th><th>说明</th></tr>
|
| 348 |
<tr><td><code>episode_index</code></td><td>int64</td><td>全局序号 N(1 起)</td></tr>
|
|
|
|
| 355 |
<tr><td><code>drop_stats</code></td><td>str</td><td>JSON 字符串(如 <code>{"imu_overflow": 0}</code>),读取方须 <code>json.loads</code></td></tr>
|
| 356 |
<tr><td><code>video_codec</code></td><td>str</td><td>JSON 字符串:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8</td></tr>
|
| 357 |
<tr><td><code>calibration</code></td><td>str</td><td>JSON 字符串:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真</td></tr>
|
| 358 |
+
<tr><td><code>force_matrix_specs</code></td><td>str</td><td>JSON 字符串:本段力矩阵列规格(列名 → 描述),<strong>倍率的权威来源</strong>,见 §7.2.1。v1.3.x 新增;旧 episode 无此列(读侧<span class="tag must">MUST</span>容忍缺失,退回 info.json)</td></tr>
|
| 359 |
</table></div>
|
| 360 |
+
<p><b>追加旧任务(写侧<span class="tag must">MUST</span>)</b>:向 v1.3.x 之前的任务继续录 episode 时,重写整表须对缺列补默认值(<code>force_matrix_specs</code> → <code>"{}"</code>,现由 <code>_episode_rows_table</code> 按 schema 填),否则新行与旧行拼不成一张表。读侧同理<span class="tag must">MUST</span>容忍该列缺失。</p>
|
| 361 |
</section>
|
| 362 |
|
| 363 |
<section id="s7">
|
|
|
|
| 384 |
<tr><td><code>action</code></td><td>list<float32, 1></td><td>恒写(现为 0)</td></tr>
|
| 385 |
<tr><td><code>status.<did></code></td><td>str</td><td>稀疏设备状态列(<code>"connected"</code>/<code>"disconnected"</code> 等)</td></tr>
|
| 386 |
</table></div>
|
| 387 |
+
<h4>7.2.1 力矩阵列(UMI 夹爪)</h4>
|
| 388 |
+
<p><code>observation.[gripper_N_]gripper_{left,right}_force_matrix</code> —— 稀疏 <code>list</code> 列,每个样本是一整帧 <code>(250,250,3)</code>(fx/fy/fz,单位 mN)的扁平编码,长度恒 <code>250 × 750 = 187500</code>,行差分按 <code>(250, 750)</code> 分块还原:</p>
|
| 389 |
+
<div class="tblwrap"><table>
|
| 390 |
+
<tr><th>编码</th><th>列类型</th><th>解码</th></tr>
|
| 391 |
+
<tr><td><code>row_flat_raw</code></td><td>list<float32></td><td>原值直存(无差分无量化),<code>reshape(250,250,3)</code>;<b>不要 cumsum</b></td></tr>
|
| 392 |
+
<tr><td><code>row_diff_quantized</code></td><td>list<int16></td><td>先 <code>cumsum</code> 还原差分(int16 回绕,累加器用 int32),再 <code>reshape</code>,最后 ÷<code>scale</code></td></tr>
|
| 393 |
+
</table></div>
|
| 394 |
+
<p><b><code>scale</code> 是读取端的必需信息,不能从数据推断</b>:×10/×100/×1000 三档的列类型都是 <code>list<int16></code>、元素也都是 int,只有 <code>scale</code> 能决定 ÷10 还是 ÷1000。漏读 = 数值整体放大 N 倍(图形形状仍对,故为静默错)。<code>row_flat_raw</code> 恒 1。</p>
|
| 395 |
+
<ul>
|
| 396 |
+
<li><b>权威顺序(读侧<span class="tag must">MUST</span>)</b>:① 同号 <code>meta/episodes/chunk-NNN/episode-NNN.parquet</code> 的 <code>force_matrix_specs</code>(每段一份,权威);② <code><task>/meta/info.json</code> 的 <code>features[列].scale</code>(任务级回退);③ 都没有 → 1(未定标)。</li>
|
| 397 |
+
<li><b>为什么必须有 ①</b>:<code>info.json</code> 是任务级且「值以最新 episode 为准」,同任务里换过力矩阵档位,早先几段的 <code>scale</code> 会被后一段覆盖(实测 ×10/×100/×1000 三段连录后再录一段 float32,三段全被顶成 1)。① 每段写一次、只增不改,不受后续录制影响。</li>
|
| 398 |
+
<li><b>自检判据</b>:同一帧 Σ(fz 平面) ≈ 同帧 <code>observation.*_gripper_*_force</code> 的 fz 分量(float32 档实测比值 1.000)。历史未定标 int16 档因逐点向零截断,该比值明显小于 1(实测 0.04~0.55)——这是截断造成的,不是倍率。<code>scripts/repair_force_matrix_scale.py</code> 用该判据给旧 episode 补写 ①(只补 meta 行,不碰 data 字节)。</li>
|
| 399 |
+
</ul>
|
| 400 |
<h3>7.3 时间对齐模型</h3>
|
| 401 |
<p><strong>表为帧行为主</strong>:一行 = 一个 30fps 帧;视频帧/传感器读数/帧行共用同一 <code>frame_index</code>(写入线程同拍产出)。IMU 为变长 list 列挂在帧行上,录制时按 <code>hardware_ns</code> 设备时钟窗口挂靠。读取零重采样;宿主时间锚定靠 <code>timestamp</code> + <code>wall_time</code>。客户 9 列平表由导出工具展开插值合成,非本契约内容。</p>
|
| 402 |
<h3>7.4 meta/episodes/.lock(运行时辅助文件,非数据)</h3>
|
collector/docs/file_format.md
CHANGED
|
@@ -140,7 +140,7 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 140 |
### 6.1 文件与原子性
|
| 141 |
|
| 142 |
- **每 episode 一个文件** `chunk-{c:03d}/episode-{f:03d}.parquet`(与 data/videos
|
| 143 |
-
同编号:episode-000 = episode 1),**恒 1 行**(
|
| 144 |
- episode 结束时**单行原子写**:临时文件 + `os.replace` 原子替换;同号重录 =
|
| 145 |
覆盖该文件。读取方 MUST 容忍文件在任意时刻被原子替换(每次打开重新
|
| 146 |
读取,勿缓存 fd)。
|
|
@@ -154,7 +154,7 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 154 |
`scripts/migrate_pooled_storage.py --split-episodes` 可把旧分片原地拆成
|
| 155 |
每段文件(幂等)。
|
| 156 |
|
| 157 |
-
### 6.2 列(
|
| 158 |
|
| 159 |
| 列 | 类型 | 说明 |
|
| 160 |
|---|---|---|
|
|
@@ -168,6 +168,11 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 168 |
| `drop_stats` | str | **JSON 字符串**(如 `{"imu_overflow": 0}`),读取方须 `json.loads` |
|
| 169 |
| `video_codec` | str | **JSON 字符串**:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8 |
|
| 170 |
| `calibration` | str | **JSON 字符串**:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
## 7. data/(每 episode 一个 parquet)
|
| 173 |
|
|
@@ -196,6 +201,39 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 196 |
| `action` | list<float32, 1> | 恒写(现为 0) |
|
| 197 |
| `status.<did>` | str | 稀疏设备状态列(`"connected"`/`"disconnected"` 等) |
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
### 7.3 时间对齐模型(MUST 理解)
|
| 200 |
|
| 201 |
**表为帧行为主**:一行 = 一个 30fps 帧;视频帧/传感器读数/帧行共用同一
|
|
|
|
| 140 |
### 6.1 文件与原子性
|
| 141 |
|
| 142 |
- **每 episode 一个文件** `chunk-{c:03d}/episode-{f:03d}.parquet`(与 data/videos
|
| 143 |
+
同编号:episode-000 = episode 1),**恒 1 行**(11 列,见 §6.2)。
|
| 144 |
- episode 结束时**单行原子写**:临时文件 + `os.replace` 原子替换;同号重录 =
|
| 145 |
覆盖该文件。读取方 MUST 容忍文件在任意时刻被原子替换(每次打开重新
|
| 146 |
读取,勿缓存 fd)。
|
|
|
|
| 154 |
`scripts/migrate_pooled_storage.py --split-episodes` 可把旧分片原地拆成
|
| 155 |
每段文件(幂等)。
|
| 156 |
|
| 157 |
+
### 6.2 列(11 列,MUST)
|
| 158 |
|
| 159 |
| 列 | 类型 | 说明 |
|
| 160 |
|---|---|---|
|
|
|
|
| 168 |
| `drop_stats` | str | **JSON 字符串**(如 `{"imu_overflow": 0}`),读取方须 `json.loads` |
|
| 169 |
| `video_codec` | str | **JSON 字符串**:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8 |
|
| 170 |
| `calibration` | str | **JSON 字符串**:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真 |
|
| 171 |
+
| `force_matrix_specs` | str | **JSON 字符串**:本段力矩阵列规格(列名 → 描述),**倍率的权威来源**,见 §7.2.1。v1.3.x 新增;旧 episode 无此列(读侧按缺列容忍,退回 info.json) |
|
| 172 |
+
|
| 173 |
+
**追加旧任务(写侧 MUST)**:向 v1.3.x 之前的任务继续录 episode 时,重写整表
|
| 174 |
+
须对缺列补默认值(`force_matrix_specs` → `"{}"`,现由 `_episode_rows_table`
|
| 175 |
+
按 schema 填),否则新行与旧行拼不成一张表。读侧同理 **MUST 容忍该列缺失**。
|
| 176 |
|
| 177 |
## 7. data/(每 episode 一个 parquet)
|
| 178 |
|
|
|
|
| 201 |
| `action` | list<float32, 1> | 恒写(现为 0) |
|
| 202 |
| `status.<did>` | str | 稀疏设备状态列(`"connected"`/`"disconnected"` 等) |
|
| 203 |
|
| 204 |
+
#### 7.2.1 力矩阵列(UMI 夹爪)
|
| 205 |
+
|
| 206 |
+
`observation.[gripper_N_]gripper_{left,right}_force_matrix` —— 稀疏 `list` 列,
|
| 207 |
+
每个样本是一整帧 `(250,250,3)`(fx/fy/fz,单位 mN)的扁平编码,长度恒
|
| 208 |
+
`250 × 750 = 187500` 行差分按 `(250, 750)` 分块还原:
|
| 209 |
+
|
| 210 |
+
| 编码 | 列类型 | 解码 |
|
| 211 |
+
|---|---|---|
|
| 212 |
+
| `row_flat_raw` | `list<float32>` | 原值直存(无差分无量化),`reshape(250,250,3)`;**不要 cumsum** |
|
| 213 |
+
| `row_diff_quantized` | `list<int16>` | 先 `cumsum` 还原差分(int16 回绕,累加器用 int32),再 `reshape`,最后 ÷`scale` |
|
| 214 |
+
|
| 215 |
+
**`scale` 是读取端的必需信息,不能从数据推断**:×10/×100/×1000 三档的列类型
|
| 216 |
+
都是 `list<int16>`、元素也都是 int,只有 `scale` 能决定 ÷10 还是 ÷1000。
|
| 217 |
+
漏读 = 数值整体放大 N 倍(图形形状仍对,故为静默错)。`row_flat_raw` 恒 1。
|
| 218 |
+
|
| 219 |
+
**权威顺序(读侧 MUST)**:
|
| 220 |
+
|
| 221 |
+
1. 同号 `meta/episodes/chunk-NNN/episode-NNN.parquet` 的 `force_matrix_specs`
|
| 222 |
+
—— **每段一份,权威**;
|
| 223 |
+
2. `<task>/meta/info.json` 的 `features[列].scale` —— 任务级**回退**;
|
| 224 |
+
3. 都没有 → 1(未定标)。
|
| 225 |
+
|
| 226 |
+
**为什么必须有 (1)**:`info.json` 是任务级且「值以最新 episode 为准」,
|
| 227 |
+
同任务里换过力矩阵档位,早先几段的 `scale` 会被后一段覆盖(实测 ×10/×100/
|
| 228 |
+
×1000 三段连录后再录一段 float32,三段全被顶成 1)。(1) 每段写一次、只增不改,
|
| 229 |
+
不受后续录制影响。
|
| 230 |
+
|
| 231 |
+
**自检判据**:同一帧 `Σ(fz 平面)` ≈ 同帧 `observation.*_gripper_*_force` 的
|
| 232 |
+
fz 分量(float32 档实测比值 1.000)。历史未定标 int16 档因逐点向零截断,
|
| 233 |
+
该比值明显小于 1(实测 0.04~0.55)——这是截断造成的,不是倍率。
|
| 234 |
+
`scripts/repair_force_matrix_scale.py` 用该判据给旧 episode 补写 (1)(只补
|
| 235 |
+
meta 行,不碰 data 字节)。
|
| 236 |
+
|
| 237 |
### 7.3 时间对齐模型(MUST 理解)
|
| 238 |
|
| 239 |
**表为帧行为主**:一行 = 一个 30fps 帧;视频帧/传感器读数/帧行共用同一
|
collector/scripts/repair_force_matrix_scale.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""补写历史 episode 的力矩阵倍率(meta/episodes 的 force_matrix_specs 列)。
|
| 4 |
+
|
| 5 |
+
venv/bin/python scripts/repair_force_matrix_scale.py <任务目录> # 只看
|
| 6 |
+
venv/bin/python scripts/repair_force_matrix_scale.py <任务目录> --apply # 写入
|
| 7 |
+
|
| 8 |
+
为什么要修
|
| 9 |
+
──────────
|
| 10 |
+
力矩阵落盘规格 int16×10/×100/×1000 的列类型都是 list<int16>、元素也都是
|
| 11 |
+
int,**倍率从数据上完全分辨不出**,只能靠随段记录的 scale 还原。倍率原先
|
| 12 |
+
只写在任务级 meta/info.json 的 features[列].scale 里,而它「值以最新
|
| 13 |
+
episode 为准」——同一个任务里换过档位,早先几段的 scale 就被后一段覆盖掉
|
| 14 |
+
(实测 ×10 / ×100 / ×1000 三段连录、再录一段 float32 后,三段全变成 1,
|
| 15 |
+
回放时数值分别放大 10 / 100 / 1000 倍)。本脚本把推断出的倍率补写进
|
| 16 |
+
**每段一份**的 meta/episodes/chunk-NNN/episode-NNN.parquet。
|
| 17 |
+
|
| 18 |
+
怎么推断
|
| 19 |
+
────────
|
| 20 |
+
同一帧的力矩阵 fz 平面逐点求和,等于 SDK 的 fz 总量(float32 档实测
|
| 21 |
+
比值 1.000)。定标档存的是 ×N 后的值,所以
|
| 22 |
+
|
| 23 |
+
倍率 = median( Σ(解码后的 fz 平面,按 scale=1 解) / force 列 fz )
|
| 24 |
+
|
| 25 |
+
×10 档实测 10.003、×100 档 99.998、×1000 档 1000.0007 —— 精确到 0.1%。
|
| 26 |
+
倍率必须落在已知档位 {1,10,100,1000} 的 ±3% 内才认(两两相差 ≥10 倍,
|
| 27 |
+
这个判据很宽松);否则报「无法判定」并跳过,绝不猜着写。
|
| 28 |
+
|
| 29 |
+
**×1 只在实测比值 ≤ UNSCALED_MAX 时才判**(1.15,见下),中间地带一律
|
| 30 |
+
无法判定:定标档的量化误差是每点 1/(2N) mN,接触点少、力又小的帧上这个
|
| 31 |
+
误差占总量不可忽略 —— 一段真 ×10 的录制理论上能测到 9 出头,此时若把
|
| 32 |
+
「不到 9.7 就算未定标」当规则,就会把它判成 ×1、数值放小 10 倍。判不出
|
| 33 |
+
比判错好:判不出只是留着回退 info.json,判错是静默 10 倍偏差。
|
| 34 |
+
|
| 35 |
+
判 ×1 的依据是**逐点向零截断只会让和变小**(同号为主):未定标档实测老
|
| 36 |
+
数据只剩真值的 4%~55%,即比值 0.04~0.55,离 1.15 还有个数量级的富余;
|
| 37 |
+
真值低到截断后归零时和也接近 0,同样落在这一侧。这条也顺带把老 episode
|
| 38 |
+
写成自带倍率,免得将来同任务里录了 ×1000 之后,它们回退到任务级
|
| 39 |
+
info.json 被按 ×1000 还原(数值缩 1000 倍)。
|
| 40 |
+
仅对**同任务里出现过多档**的旧数据需要跑这个脚本;单档跑到底的任务里
|
| 41 |
+
info.json 本来就是对的,读取端回退到它即可。
|
| 42 |
+
|
| 43 |
+
改什么
|
| 44 |
+
──────
|
| 45 |
+
只改 meta/episodes 那一行(单行 parquet,重写整个文件但内容逐列保留),
|
| 46 |
+
**不碰 data/ 里的矩阵数据一个字节**。
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
import argparse
|
| 50 |
+
import json
|
| 51 |
+
import os
|
| 52 |
+
import sys
|
| 53 |
+
|
| 54 |
+
import numpy as np
|
| 55 |
+
import pyarrow as pa
|
| 56 |
+
import pyarrow.parquet as pq
|
| 57 |
+
|
| 58 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 59 |
+
sys.path.insert(0, REPO_ROOT)
|
| 60 |
+
|
| 61 |
+
from core.egodata_writer import ( # noqa: E402
|
| 62 |
+
_EPISODE_SCHEMA, _atomic_write_parquet, _episode_rows_table,
|
| 63 |
+
_read_episode_rows)
|
| 64 |
+
from core.helpers import ( # noqa: E402
|
| 65 |
+
pooled_data_parquet_path, pooled_episodes_path)
|
| 66 |
+
|
| 67 |
+
TIERS = (1, 10, 100, 1000)
|
| 68 |
+
TIER_TOLERANCE = 0.03 # 实测倍率与标称档位的相对误差上限
|
| 69 |
+
MIN_FRAMES = 5 # 参与统计的最少有效帧
|
| 70 |
+
UNSCALED_MAX = 1.15 # 判 ×1 的实测比值上限(截断只会让和变小,
|
| 71 |
+
# 超过它就不是截断能解释的了;1~10 之间
|
| 72 |
+
# 判不出,见文件头「怎么推断」)
|
| 73 |
+
MATRIX_ROW_LEN = 750 # 250 列 × 3 通道
|
| 74 |
+
_MATRIX_SUFFIX = "_force_matrix"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _decode_int16_ref(enc: np.ndarray) -> np.ndarray:
|
| 78 |
+
"""按 scale=1 解出 (250,250,3) —— 与 demo 的整数分支同一口径。"""
|
| 79 |
+
rows = np.cumsum(
|
| 80 |
+
enc.reshape(-1, MATRIX_ROW_LEN).astype(np.int32), axis=1)
|
| 81 |
+
return rows.astype(np.int16).reshape(250, 250, 3)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _list_column_to_numpy(column):
|
| 85 |
+
"""list<数值> 列 → (offsets, values);走 pyarrow 缓冲区,避开 pylist。"""
|
| 86 |
+
dtype = (np.float32 if pa.types.is_floating(column.type.value_type)
|
| 87 |
+
else np.int16)
|
| 88 |
+
offsets, values, base = [], [], 0
|
| 89 |
+
for chunk in column.chunks:
|
| 90 |
+
offs = np.asarray(chunk.offsets, np.int64)
|
| 91 |
+
vals = np.asarray(chunk.values, dtype=dtype)
|
| 92 |
+
offsets.append(offs[:-1] + base)
|
| 93 |
+
values.append(vals)
|
| 94 |
+
base += int(vals.size)
|
| 95 |
+
if not offsets:
|
| 96 |
+
return np.zeros(1, np.int64), np.zeros(0, dtype)
|
| 97 |
+
return (np.concatenate(offsets + [np.array([base], np.int64)]),
|
| 98 |
+
np.concatenate(values))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def infer_scale(data_path: str, column: str, force_column: str):
|
| 102 |
+
"""实测该列的倍率 → (倍率, 证据串);判不出返回 (None, 原因)。
|
| 103 |
+
|
| 104 |
+
倍率来自「矩阵平面和 ÷ 同帧 force 列 fz」的中位比,必须与某个已知
|
| 105 |
+
档位相差 ≤3% 才认。force 列缺失/全零/有效帧不足都判不出。
|
| 106 |
+
"""
|
| 107 |
+
schema = pq.read_schema(data_path)
|
| 108 |
+
if force_column not in schema.names:
|
| 109 |
+
return None, "无 force 列可比对"
|
| 110 |
+
table = pq.read_table(data_path, columns=[column, force_column])
|
| 111 |
+
offsets, values = _list_column_to_numpy(table.column(column))
|
| 112 |
+
force = np.asarray(table.column(force_column).to_pylist(), np.float32)
|
| 113 |
+
n = table.num_rows
|
| 114 |
+
is_float = values.dtype == np.float32
|
| 115 |
+
|
| 116 |
+
# 稀疏列:表行号就是帧号,第 row 行有样本时其样本即该帧的矩阵。
|
| 117 |
+
# 只遍历有样本的行(空行的 offsets 首尾相等,不能拿行号当样本序号)。
|
| 118 |
+
ratios = []
|
| 119 |
+
for row in np.flatnonzero(np.diff(offsets) > 0):
|
| 120 |
+
row = int(row)
|
| 121 |
+
if row >= n:
|
| 122 |
+
break
|
| 123 |
+
enc = values[int(offsets[row]):int(offsets[row + 1])]
|
| 124 |
+
if enc.size != 250 * MATRIX_ROW_LEN:
|
| 125 |
+
continue # 损坏行
|
| 126 |
+
plane = (enc.reshape(250, 250, 3) if is_float
|
| 127 |
+
else _decode_int16_ref(enc))
|
| 128 |
+
total = float(plane[:, :, 2].astype(np.float64).sum())
|
| 129 |
+
fz = float(force[row][2]) if force.ndim == 2 else float(force[row])
|
| 130 |
+
if abs(fz) < 50.0: # 近零帧比不出倍率(分母噪声)
|
| 131 |
+
continue
|
| 132 |
+
ratios.append(total / fz)
|
| 133 |
+
if len(ratios) >= 200:
|
| 134 |
+
break
|
| 135 |
+
if len(ratios) < MIN_FRAMES:
|
| 136 |
+
return None, f"有效帧不足({len(ratios)})"
|
| 137 |
+
median = float(np.median(ratios))
|
| 138 |
+
counts = f"{len(ratios)} 帧"
|
| 139 |
+
tier = min(TIERS, key=lambda t: abs(t - median))
|
| 140 |
+
rel = abs(median - tier) / tier
|
| 141 |
+
if rel <= TIER_TOLERANCE:
|
| 142 |
+
return tier, f"实测 {median:.4f} → ×{tier}({counts},偏差 {rel:.2%})"
|
| 143 |
+
if median <= UNSCALED_MAX:
|
| 144 |
+
return 1, (f"实测 {median:.4f} ≤ {UNSCALED_MAX} → ×1({counts};"
|
| 145 |
+
f"向零截断只会让和变小,偏小只能来自未定标档)")
|
| 146 |
+
return None, (f"实测 {median:.4f} 无处可归({counts}):既不在档位 "
|
| 147 |
+
f"±{TIER_TOLERANCE:.0%} 内,又比 ×1 的上限 "
|
| 148 |
+
f"{UNSCALED_MAX} 高 —— 小接触/小力的定标档量化噪声就能"
|
| 149 |
+
f"压到这个区间,猜不得")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def plan_task(task_dir: str):
|
| 153 |
+
"""扫任务下所有 episode,列出「该补倍率」的那些 → [(stem, 索引, 提议)]。"""
|
| 154 |
+
episodes_dir = os.path.join(task_dir, "meta", "episodes")
|
| 155 |
+
found = []
|
| 156 |
+
for root, _dirs, files in os.walk(episodes_dir):
|
| 157 |
+
for name in sorted(files):
|
| 158 |
+
if not (name.startswith("episode-") and name.endswith(".parquet")):
|
| 159 |
+
continue
|
| 160 |
+
meta_path = os.path.join(root, name)
|
| 161 |
+
rows = _read_episode_rows(meta_path)
|
| 162 |
+
rows = [r for r in rows if r.get("episode_index") is not None]
|
| 163 |
+
if len(rows) != 1:
|
| 164 |
+
print(f" [{name}] 元数据行数 {len(rows)} ≠ 1,跳过")
|
| 165 |
+
continue
|
| 166 |
+
row = rows[0]
|
| 167 |
+
try:
|
| 168 |
+
existing = json.loads(row.get("force_matrix_specs") or "{}")
|
| 169 |
+
except (TypeError, ValueError):
|
| 170 |
+
existing = {}
|
| 171 |
+
index = int(row["episode_index"])
|
| 172 |
+
data_path = pooled_data_parquet_path(task_dir, index)
|
| 173 |
+
if not os.path.isfile(data_path):
|
| 174 |
+
print(f" [{name}] 找不到 {data_path},跳过")
|
| 175 |
+
continue
|
| 176 |
+
schema = pq.read_schema(data_path)
|
| 177 |
+
cols = [c for c in schema.names
|
| 178 |
+
if c.endswith(_MATRIX_SUFFIX)]
|
| 179 |
+
if not cols:
|
| 180 |
+
continue # 本段没有力矩阵列,无需倍率
|
| 181 |
+
missing = [c for c in cols
|
| 182 |
+
if not isinstance(existing.get(c), dict)
|
| 183 |
+
or not existing[c].get("scale")]
|
| 184 |
+
if not missing:
|
| 185 |
+
continue # 已有权威记录,不动
|
| 186 |
+
found.append((name, index, data_path, cols, existing))
|
| 187 |
+
return found
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def build_specs(data_path: str, cols, existing: dict):
|
| 191 |
+
"""逐列推断 → (规格 dict, 判不出的列说明)。
|
| 192 |
+
|
| 193 |
+
每列的证据各自独立,一列判不出只跳过那一列(读取端对它是回退 info.json),
|
| 194 |
+
不牵连同段其余列。已有权威值的列不重推——录制端写下的倍率是事实,推断
|
| 195 |
+
只是补救手段。
|
| 196 |
+
"""
|
| 197 |
+
specs = dict(existing)
|
| 198 |
+
failed = []
|
| 199 |
+
schema = pq.read_schema(data_path)
|
| 200 |
+
for column in cols:
|
| 201 |
+
key = column.split("observation.", 1)[-1]
|
| 202 |
+
if isinstance(specs.get(column), dict) and specs[column].get("scale"):
|
| 203 |
+
print(f" {key}: 已有权威值 {specs[column]},保持不动")
|
| 204 |
+
continue
|
| 205 |
+
force_column = f"observation.{key[:-len('_force_matrix')]}_force"
|
| 206 |
+
scale, evidence = infer_scale(data_path, column, force_column)
|
| 207 |
+
if scale is None:
|
| 208 |
+
print(f" {key}: {evidence} → 跳过该列")
|
| 209 |
+
failed.append(f"{key}: {evidence}")
|
| 210 |
+
continue
|
| 211 |
+
float32 = pa.types.is_floating(
|
| 212 |
+
schema.field(column).type.value_type)
|
| 213 |
+
specs[column] = {
|
| 214 |
+
"dtype": "float32" if float32 else "int16",
|
| 215 |
+
"shape": [250, 250, 3],
|
| 216 |
+
"encoding": "row_flat_raw" if float32 else "row_diff_quantized",
|
| 217 |
+
"scale": int(scale),
|
| 218 |
+
}
|
| 219 |
+
print(f" {key}: {evidence}")
|
| 220 |
+
return specs, failed
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def repair(task_dir: str, apply: bool) -> int:
|
| 224 |
+
print(f"任务目录: {task_dir}")
|
| 225 |
+
print(f"模式: {'写入' if apply else '只读预览(加 --apply 才写)'}")
|
| 226 |
+
candidates = plan_task(task_dir)
|
| 227 |
+
if not candidates:
|
| 228 |
+
print("\n没有需要补写倍率的 episode。")
|
| 229 |
+
return 0
|
| 230 |
+
print(f"\n发现 {len(candidates)} 段缺倍率记录:")
|
| 231 |
+
pending = []
|
| 232 |
+
skipped = []
|
| 233 |
+
for name, index, data_path, cols, existing in candidates:
|
| 234 |
+
print(f"\n [{name}] episode_index={index},{len(cols)} 个力矩阵列")
|
| 235 |
+
specs, failed = build_specs(data_path, cols, existing)
|
| 236 |
+
if specs == existing: # 补不进去(列都判不出,或都已记录)
|
| 237 |
+
skipped.append(f"{name}({'、'.join(failed) if failed else '已记录'})")
|
| 238 |
+
continue
|
| 239 |
+
if failed:
|
| 240 |
+
skipped.append(f"{name}({len(failed)} 列判不出:{failed[0]})")
|
| 241 |
+
pending.append((name, index, specs))
|
| 242 |
+
|
| 243 |
+
if skipped:
|
| 244 |
+
print("\n以下段落这次没(全部)写进去(读取端回退 info.json):")
|
| 245 |
+
for line in skipped:
|
| 246 |
+
print(f" - {line}")
|
| 247 |
+
if not pending:
|
| 248 |
+
print("\n没有新判出的倍率,未做任何改动。")
|
| 249 |
+
return 0
|
| 250 |
+
if not apply:
|
| 251 |
+
print(f"\n预览完毕:{len(pending)} 段可补写。确认无误后加 --apply。")
|
| 252 |
+
return 0
|
| 253 |
+
|
| 254 |
+
print()
|
| 255 |
+
for name, index, specs in pending:
|
| 256 |
+
path = pooled_episodes_path(task_dir, index)
|
| 257 |
+
rows = _read_episode_rows(path)
|
| 258 |
+
rows = [r for r in rows if r.get("episode_index") == index]
|
| 259 |
+
if len(rows) != 1:
|
| 260 |
+
print(f" [{name}] 写入前复查:行数 {len(rows)} ≠ 1,跳过")
|
| 261 |
+
continue
|
| 262 |
+
row = dict(rows[0])
|
| 263 |
+
# 只补缺失的列,已有的权威值不覆盖
|
| 264 |
+
merged = json.loads(row.get("force_matrix_specs") or "{}")
|
| 265 |
+
merged.update(specs)
|
| 266 |
+
row["force_matrix_specs"] = json.dumps(merged, ensure_ascii=False)
|
| 267 |
+
table = _episode_rows_table([row])
|
| 268 |
+
if table.schema != _EPISODE_SCHEMA: # 防御:schema 必须一致
|
| 269 |
+
print(f" [{name}] schema 不符,跳过")
|
| 270 |
+
continue
|
| 271 |
+
_atomic_write_parquet(table, path)
|
| 272 |
+
print(f" [{name}] 已补写 {len(specs)} 列 → {os.path.relpath(path, REPO_ROOT)}")
|
| 273 |
+
print("\n完成。重新打开 demo 即可按真实倍率还原。")
|
| 274 |
+
return 0
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def main() -> int:
|
| 278 |
+
parser = argparse.ArgumentParser(
|
| 279 |
+
description="补写历史 episode 的力矩阵倍率(meta/episodes 行)")
|
| 280 |
+
parser.add_argument("task_dir", help="任务目录(含 data/ 与 meta/ 的那层)")
|
| 281 |
+
parser.add_argument("--apply", action="store_true",
|
| 282 |
+
help="真正写入;不给则只预览")
|
| 283 |
+
args = parser.parse_args()
|
| 284 |
+
if not os.path.isdir(os.path.join(args.task_dir, "meta")):
|
| 285 |
+
print(f"不是任务目录(缺 meta/): {args.task_dir}")
|
| 286 |
+
return 2
|
| 287 |
+
return repair(os.path.abspath(args.task_dir), args.apply)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
sys.exit(main())
|
collector/tools/demos/gripper_force_matrix_demo/gripper_force_matrix_demo.py
CHANGED
|
@@ -22,21 +22,54 @@
|
|
| 22 |
力总值列(float32 mN,SDK 同帧输出,可选):
|
| 23 |
observation.{prefix}gripper_{left,right}_force [fx, fy, fz]
|
| 24 |
|
| 25 |
-
显示什么(与主程序触觉面板
|
| 26 |
每侧 = 热力图(上,可滚轮缩放/拖拽/双击复位)+ 力曲线(下)
|
| 27 |
热力图 = core/gripper/tactile_process_worker.pressure_to_heatmap 原样移植:
|
| 28 |
-
fz 平面 →
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
力曲线 = ui/gripper_widgets.ForceCurveWidget 原样移植:
|
| 31 |
±3000mN 对称量程、Fx/Fy/Fz 三线、300 点滚动窗口
|
| 32 |
-
只显示 fz 平面(主程序口径)。矩阵里的 fx/fy 平面在现有
|
| 33 |
-
均 < 1,
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
内存: 打开一份 episode 会把两侧矩阵列整体读进内存(≈ 帧数 × 375KB/侧,
|
| 42 |
696 帧双触觉约 490MB);逐帧解码后只保留当帧矩阵。
|
|
@@ -46,12 +79,14 @@
|
|
| 46 |
|
| 47 |
import argparse
|
| 48 |
import json
|
|
|
|
| 49 |
import os
|
| 50 |
import re
|
| 51 |
import sys
|
| 52 |
|
| 53 |
import cv2
|
| 54 |
import numpy as np
|
|
|
|
| 55 |
import pyarrow.parquet as pq
|
| 56 |
|
| 57 |
from PyQt5.QtCore import QLibraryInfo, QPointF, QRectF, Qt, QTimer
|
|
@@ -83,6 +118,12 @@ FZ_PLANE = 2 # 显示平面 = fz(主程序触觉面板口
|
|
| 83 |
|
| 84 |
_FORCE_RANGE_MN = 3000.0 # 力曲线量程(主程序同值)
|
| 85 |
_CURVE_POINTS = 300 # 力曲线滚动窗口点数(主程序同值)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
_CURVE_COLORS = {
|
| 87 |
"fx": QColor("#4fc3f7"), # 蓝
|
| 88 |
"fy": QColor("#aed581"), # 绿
|
|
@@ -98,19 +139,41 @@ _EPISODE_RE = re.compile(r"^episode-(\d+)\.parquet$")
|
|
| 98 |
# 1. 力矩阵反解 + 热力图(与主程序逐行一致)
|
| 99 |
# ══════════════════════════════════════════════════════════════════
|
| 100 |
|
| 101 |
-
def decode_force_matrix(encoded) -> np.ndarray | None:
|
| 102 |
-
"""
|
| 103 |
|
| 104 |
与 ui/main_window.encode_gripper_force_matrix 的反解口径一致:
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
"""
|
| 109 |
-
arr = np.asarray(encoded
|
| 110 |
if arr.size == 0 or arr.size % ROW_LEN:
|
| 111 |
return None # 空样本或长度不符(损坏行)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
rows = np.cumsum(arr.reshape(-1, ROW_LEN).astype(np.int32), axis=1)
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
def pressure_to_heatmap(pressure_matrix, device_type="bevel", scale=None):
|
|
@@ -254,7 +317,10 @@ class HeatmapView(QWidget):
|
|
| 254 |
cx = self.width() / 2 + self._offset.x()
|
| 255 |
cy = self.height() / 2 + self._offset.y()
|
| 256 |
target = QRectF(cx - w / 2, cy - h / 2, w, h)
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
| 258 |
painter.drawPixmap(target, self._pixmap, QRectF(self._pixmap.rect()))
|
| 259 |
painter.end()
|
| 260 |
|
|
@@ -335,23 +401,28 @@ class TactileSidePanel(QWidget):
|
|
| 335 |
# ══════════════════════════════════════════════════════════════════
|
| 336 |
|
| 337 |
def _list_column_to_numpy(column):
|
| 338 |
-
"""list<
|
| 339 |
|
| 340 |
-
走 pyarrow 缓冲区转 numpy:整段矩阵是上亿个
|
| 341 |
会生成同等数量的 Python 对象(几 GB),必须绕开。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
"""
|
|
|
|
|
|
|
| 343 |
offsets, values, base = [], [], 0
|
| 344 |
for chunk in column.chunks:
|
| 345 |
offs = np.asarray(chunk.offsets, dtype=np.int64)
|
| 346 |
-
vals = np.asarray(chunk.values, dtype=
|
| 347 |
offsets.append(offs[:-1] + base)
|
| 348 |
values.append(vals)
|
| 349 |
base += int(vals.size)
|
| 350 |
if not offsets:
|
| 351 |
-
return np.zeros(1, np.int64), np.zeros(0,
|
| 352 |
all_offsets = np.concatenate(offsets + [np.array([base], np.int64)])
|
| 353 |
-
all_values =
|
| 354 |
-
else np.zeros(0, np.int16))
|
| 355 |
return all_offsets, all_values
|
| 356 |
|
| 357 |
|
|
@@ -366,13 +437,63 @@ def _read_fps(parquet_path: str) -> float:
|
|
| 366 |
return 30.0
|
| 367 |
|
| 368 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
class TactileStream:
|
| 370 |
"""单侧触觉流:力矩阵稀疏列(保持上一帧)+ 力总值列。"""
|
| 371 |
|
| 372 |
-
def __init__(self, table, prefix: str, side: str, n_frames: int
|
|
|
|
| 373 |
self.prefix = prefix
|
| 374 |
self.side = side
|
| 375 |
name = f"observation.{prefix}gripper_{side}_force_matrix"
|
|
|
|
|
|
|
| 376 |
self.offsets, self.values = _list_column_to_numpy(table.column(name))
|
| 377 |
lengths = np.diff(self.offsets)
|
| 378 |
# 稀疏列 → 每帧实际显示的样本行:本帧无新样本则沿用上一帧
|
|
@@ -388,7 +509,12 @@ class TactileStream:
|
|
| 388 |
self._cache_matrix = None
|
| 389 |
|
| 390 |
def matrix(self, idx: int):
|
| 391 |
-
"""第 idx 帧显示的三力平面 (250,250,3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
if not 0 <= idx < self.hold.size:
|
| 393 |
return None
|
| 394 |
row = int(self.hold[idx])
|
|
@@ -397,7 +523,7 @@ class TactileStream:
|
|
| 397 |
if row == self._cache_row:
|
| 398 |
return self._cache_matrix
|
| 399 |
start, end = int(self.offsets[row]), int(self.offsets[row + 1])
|
| 400 |
-
matrix = decode_force_matrix(self.values[start:end])
|
| 401 |
self._cache_row, self._cache_matrix = row, matrix
|
| 402 |
return matrix
|
| 403 |
|
|
@@ -412,11 +538,46 @@ class TactileStream:
|
|
| 412 |
matrix.astype(np.float32).sum(axis=(0, 1)))
|
| 413 |
|
| 414 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
class TactileEpisode:
|
| 416 |
"""一份 episode parquet:发现全部夹爪/左右触觉流并提供逐帧取数。"""
|
| 417 |
|
| 418 |
def __init__(self, parquet_path: str):
|
| 419 |
self.path = os.path.abspath(parquet_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
# 只读触觉相关列:整段矩阵本就占内存,别再捎带手套/骨架等列
|
| 421 |
schema = pq.read_schema(parquet_path)
|
| 422 |
matrix_names = [name for name in schema.names
|
|
@@ -441,7 +602,27 @@ class TactileEpisode:
|
|
| 441 |
prefix = match.group("prefix")
|
| 442 |
side = match.group("side")
|
| 443 |
self.rigs.setdefault(prefix, {})[side] = TactileStream(
|
| 444 |
-
self.table, prefix, side, self.n_frames
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
| 446 |
def rig_label(self, prefix: str) -> str:
|
| 447 |
match = re.match(r"^gripper_(\d+)_$", prefix or "")
|
|
@@ -488,6 +669,18 @@ def _resolve_episodes(path: str):
|
|
| 488 |
# 4. 窗口
|
| 489 |
# ══════════════════════════════════════════════════════════════════
|
| 490 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
class DemoWindow(QMainWindow):
|
| 492 |
|
| 493 |
def __init__(self, path=None):
|
|
@@ -498,6 +691,8 @@ class DemoWindow(QMainWindow):
|
|
| 498 |
self.idx = 0
|
| 499 |
self.playing = False
|
| 500 |
self._prefix = ""
|
|
|
|
|
|
|
| 501 |
|
| 502 |
central = QWidget()
|
| 503 |
# 暗色底:面板未出图时空区域不露白色窗口背景(调色板填充,
|
|
@@ -525,8 +720,14 @@ class DemoWindow(QMainWindow):
|
|
| 525 |
bar_palette.setColor(bar_widget.backgroundRole(), QColor("#d9d9d9"))
|
| 526 |
bar_widget.setPalette(bar_palette)
|
| 527 |
bar_widget.setAutoFillBackground(True)
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
|
| 531 |
self.btn_open = QPushButton("打开 Parquet")
|
| 532 |
self.btn_play = QPushButton("播放")
|
|
@@ -541,6 +742,19 @@ class DemoWindow(QMainWindow):
|
|
| 541 |
self.combo_episode.setEnabled(False)
|
| 542 |
self.combo_rig = QComboBox()
|
| 543 |
self.combo_rig.setEnabled(False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 544 |
self.chk_loop = QCheckBox("循环")
|
| 545 |
self.chk_loop.setChecked(True)
|
| 546 |
self.lbl_frame = QLabel("- / -")
|
|
@@ -551,9 +765,17 @@ class DemoWindow(QMainWindow):
|
|
| 551 |
bar.addWidget(self.btn_prev)
|
| 552 |
bar.addWidget(self.slider, 1)
|
| 553 |
bar.addWidget(self.btn_next)
|
| 554 |
-
bar.addWidget(self.combo_rig)
|
| 555 |
bar.addWidget(self.chk_loop)
|
| 556 |
bar.addWidget(self.lbl_frame)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
root.addWidget(bar_widget)
|
| 558 |
|
| 559 |
self.btn_open.clicked.connect(self.open_file_dialog)
|
|
@@ -564,6 +786,8 @@ class DemoWindow(QMainWindow):
|
|
| 564 |
self.slider.sliderReleased.connect(self._on_slider_released)
|
| 565 |
self.combo_episode.activated.connect(self._on_episode_chosen)
|
| 566 |
self.combo_rig.activated.connect(self._on_rig_chosen)
|
|
|
|
|
|
|
| 567 |
|
| 568 |
self.timer = QTimer(self)
|
| 569 |
self.timer.setTimerType(Qt.PreciseTimer) # 节奏计时器要精确节拍
|
|
@@ -622,6 +846,10 @@ class DemoWindow(QMainWindow):
|
|
| 622 |
for side, panel in self.panels.items():
|
| 623 |
panel.setVisible(side in sides)
|
| 624 |
panel.reset()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
|
| 626 |
self.slider.blockSignals(True)
|
| 627 |
self.slider.setRange(0, max(0, data.n_frames - 1))
|
|
@@ -637,6 +865,7 @@ class DemoWindow(QMainWindow):
|
|
| 637 |
os.path.basename(data.path), data.fps, data.n_frames))
|
| 638 |
print("[力矩阵] {} 帧 {} 台夹爪,矩阵列常驻 {:.0f} MB".format(
|
| 639 |
data.n_frames, len(data.rigs), data.matrix_bytes() / 1e6))
|
|
|
|
| 640 |
self.render_frame(0)
|
| 641 |
|
| 642 |
def _on_episode_chosen(self, index):
|
|
@@ -651,6 +880,54 @@ class DemoWindow(QMainWindow):
|
|
| 651 |
for side, panel in self.panels.items():
|
| 652 |
panel.setVisible(side in sides)
|
| 653 |
panel.reset()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
self.render_frame(self.idx)
|
| 655 |
|
| 656 |
# ── 播放控制 ──────────────────────────────────────
|
|
@@ -695,6 +972,7 @@ class DemoWindow(QMainWindow):
|
|
| 695 |
return
|
| 696 |
index = max(0, min(index, self.data.n_frames - 1))
|
| 697 |
self.idx = index
|
|
|
|
| 698 |
for side, panel in self.panels.items():
|
| 699 |
stream = self.data.rigs.get(self._prefix, {}).get(side)
|
| 700 |
if stream is None:
|
|
@@ -703,7 +981,8 @@ class DemoWindow(QMainWindow):
|
|
| 703 |
if matrix is not None:
|
| 704 |
# 稀疏帧返回 None 时不动画面:与实时画面保持上一次结果一致
|
| 705 |
panel.show_tactile(
|
| 706 |
-
pressure_to_heatmap(matrix[:, :, FZ_PLANE]
|
|
|
|
| 707 |
stream.force_at(index))
|
| 708 |
self.slider.blockSignals(True)
|
| 709 |
self.slider.setValue(index)
|
|
|
|
| 22 |
力总值列(float32 mN,SDK 同帧输出,可选):
|
| 23 |
observation.{prefix}gripper_{left,right}_force [fx, fy, fz]
|
| 24 |
|
| 25 |
+
显示什么(与主程序触觉面板同源):
|
| 26 |
每侧 = 热力图(上,可滚轮缩放/拖拽/双击复位)+ 力曲线(下)
|
| 27 |
热力图 = core/gripper/tactile_process_worker.pressure_to_heatmap 原样移植:
|
| 28 |
+
fz 平面 → clip(0) → ×增益 → JET → resize(320, 240)
|
| 29 |
+
函数默认(scale=None)仍是 0902 固定量程 ×50(bevel)/ ×200(curved),
|
| 30 |
+
滑块拖到 ×50 与该路径逐像素一致;主程序实时链路已改走自适应增益
|
| 31 |
+
(见下「为什么要自适应」),默认满量程参考值 3.0 → ×85
|
| 32 |
+
本 demo 默认「自适应量程」:按整段录制非零 fz 的 p99.5 定标
|
| 33 |
+
(钳 ×8~×128),左右各自独立 —— 与主程序的差别是这里能看到整段
|
| 34 |
+
数据、一次性定标,主程序在线上只能逐帧慢速跟随
|
| 35 |
力曲线 = ui/gripper_widgets.ForceCurveWidget 原样移植:
|
| 36 |
±3000mN 对称量程、Fx/Fy/Fz 三线、300 点滚动窗口
|
| 37 |
+
只显示 fz 平面(主程序口径)。矩阵里的 fx/fy 平面在 int16 规格的现有
|
| 38 |
+
录制中逐点值均 < 1,取整后整平面为全零,切过去只会是空画面,故不提供
|
| 39 |
+
切换;float32 规格的录制里 fx/fy 有真实值(见下),本 demo 仍只画 fz。
|
| 40 |
+
|
| 41 |
+
落盘规格(主程序工具栏「🎚 力矩阵精度」下拉,5 档):
|
| 42 |
+
int16(默认)encode_gripper_force_matrix 把 float32 矩阵 clip 到
|
| 43 |
+
±32767 后直接 astype(int16)(**向零截断,无缩放因子**)再做行差分。
|
| 44 |
+
SDK 逐点力值多为小数,落盘只保留整数部分(1 mN 台阶)。
|
| 45 |
+
int16×10 / ×100 / ×1000 定标档:先 ×N 再 rint 到整数存 int16,
|
| 46 |
+
解码后 ÷N 还原,分辨率 1/N mN。
|
| 47 |
+
float32 原值直存,小数位完整保留(列类型 list<float32>)。
|
| 48 |
+
★ 前四档的列类型都是 list<int16>、元素都是 int,**倍率分辨不出来**,
|
| 49 |
+
唯一凭据是倍率记录本身。本 demo 按三级优先取(见 matrix_scale):
|
| 50 |
+
① meta/episodes/chunk-NNN/episode-NNN.parquet 的 force_matrix_specs
|
| 51 |
+
列(JSON,**每段一份、跟着数据走**,权威来源)
|
| 52 |
+
② meta/info.json 的 features[列名]["scale"](任务级回退:单档跑
|
| 53 |
+
到底的任务里它是对的,混档任务里它只反映最后一段)
|
| 54 |
+
③ 1(老 episode 无记录 = 未定标,正是当年那批录制的真实倍率)
|
| 55 |
+
漏读倍率只会让数值整体放大 N 倍——画面形状还是对的,属于最难发现
|
| 56 |
+
的静默错。为什么需要①:info.json 是任务级的,值以最新 episode 为准,
|
| 57 |
+
同一任务里换过档位就会把早先几段覆盖掉。
|
| 58 |
+
读取端按列类型自动分派(decode_force_matrix / _list_column_to_numpy),
|
| 59 |
+
各档 episode 都能打开;**不要硬转 int16**,那会把 float32 列静默截断。
|
| 60 |
+
|
| 61 |
+
为什么要自适应(实测 episode-014,int16 规格):
|
| 62 |
+
逐点值普遍只有 1~3(episode-014 左:1×23.4 万、2×1.3 万;右:
|
| 63 |
+
1×39.5 万、2×9.7 万、3×2.3 万,峰值 7)。固定 ×50 时 1→50/255,
|
| 64 |
+
整幅图停在深蓝区,用力大小只剩接触面积在变,颜色几乎不动。
|
| 65 |
+
按数据定标后同样的用力会走到青/绿/红,颜色才随力变。主程序同样出于
|
| 66 |
+
这个原因改成「下限固定(bevel 参考 3.0 → ×85)+ 慢速自适应」,只是
|
| 67 |
+
它逐帧在线、参考值以 τ≈8s 跟随;量程开关与参考值见
|
| 68 |
+
config/settings.py 的 GRIPPER_TACTILE_HEATMAP_AUTO / _REF / _REF_MAX。
|
| 69 |
+
float32 规格下逐点带小数、分布更连续,同一段数据定标出来的增益会略有
|
| 70 |
+
不同(见 auto_gain),梯度也更明显。
|
| 71 |
+
力总值列(float32)不受截断影响,曲线与录制时一致 —— 判断用力大小
|
| 72 |
+
看曲线,看空间分布看热力图。
|
| 73 |
|
| 74 |
内存: 打开一份 episode 会把两侧矩阵列整体读进内存(≈ 帧数 × 375KB/侧,
|
| 75 |
696 帧双触觉约 490MB);逐帧解码后只保留当帧矩阵。
|
|
|
|
| 79 |
|
| 80 |
import argparse
|
| 81 |
import json
|
| 82 |
+
import math
|
| 83 |
import os
|
| 84 |
import re
|
| 85 |
import sys
|
| 86 |
|
| 87 |
import cv2
|
| 88 |
import numpy as np
|
| 89 |
+
import pyarrow as pa
|
| 90 |
import pyarrow.parquet as pq
|
| 91 |
|
| 92 |
from PyQt5.QtCore import QLibraryInfo, QPointF, QRectF, Qt, QTimer
|
|
|
|
| 118 |
|
| 119 |
_FORCE_RANGE_MN = 3000.0 # 力曲线量程(主程序同值)
|
| 120 |
_CURVE_POINTS = 300 # 力曲线滚动窗口点数(主程序同值)
|
| 121 |
+
|
| 122 |
+
_DEFAULT_GAIN = 50.0 # 主程序固定量程(bevel 传感器 ×50)
|
| 123 |
+
_GAIN_MIN, _GAIN_MAX = 8.0, 256.0 # 手动增益滑块的对数范围
|
| 124 |
+
_AUTO_GAIN_PCT = 99.5 # 自适应定标:整段非零 fz 的 p99.5 → 255
|
| 125 |
+
_AUTO_GAIN_CLAMP = (8.0, 128.0) # 自适应增益上下限(避免空录制被推到爆红)
|
| 126 |
+
_AUTO_GAIN_SAMPLES = 150 # 定标采样帧数上限(够估百分位,解码不拖慢加载)
|
| 127 |
_CURVE_COLORS = {
|
| 128 |
"fx": QColor("#4fc3f7"), # 蓝
|
| 129 |
"fy": QColor("#aed581"), # 绿
|
|
|
|
| 139 |
# 1. 力矩阵反解 + 热力图(与主程序逐行一致)
|
| 140 |
# ══════════════════════════════════════════════════════════════════
|
| 141 |
|
| 142 |
+
def decode_force_matrix(encoded, scale: int = 1) -> np.ndarray | None:
|
| 143 |
+
"""力矩阵 → (250,250,3) 三力平面(单位 mN)。按数值 dtype 自动分派。
|
| 144 |
|
| 145 |
与 ui/main_window.encode_gripper_force_matrix 的反解口径一致:
|
| 146 |
+
|
| 147 |
+
整数(int16 行差分量化):
|
| 148 |
+
reshape(-1,750) → cumsum(axis=1) → reshape(250,250,3)。
|
| 149 |
+
cumsum 走 int32 再截断回 int16(mod 2^16 补码回绕),与编码端
|
| 150 |
+
的 int16 差分算术可逆。再 ÷scale 还原 mN——scale=1(默认档)
|
| 151 |
+
时**逐点已被截断到整数**,小数位不可恢复。
|
| 152 |
+
浮点(float32 原值):
|
| 153 |
+
reshape(-1,750) → reshape(250,250,3),无量化、无回绕、无定标。
|
| 154 |
+
|
| 155 |
+
scale 必须来自 meta/info.json 的 features[...]["scale"],**不能从数据
|
| 156 |
+
推断**:×10 与 ×1000 的列类型都是 list<int16>、元素也都是 int,猜不出来。
|
| 157 |
+
漏传 scale 只会让数值整体放大 N 倍(画面形状仍对,是那种「看着有数据
|
| 158 |
+
但数值全错」的静默错),所以 TactileStream 一律显式传。
|
| 159 |
+
|
| 160 |
+
dtype 由入参决定,不要假设一定是 int16:float32 列若被硬转 int16
|
| 161 |
+
会静默截断(画面看着「有数据」但精度已丢),所以先判 dtype 再解码。
|
| 162 |
"""
|
| 163 |
+
arr = np.asarray(encoded)
|
| 164 |
if arr.size == 0 or arr.size % ROW_LEN:
|
| 165 |
return None # 空样本或长度不符(损坏行)
|
| 166 |
+
if np.issubdtype(arr.dtype, np.floating):
|
| 167 |
+
return arr.astype(np.float32, copy=False).reshape(
|
| 168 |
+
MATRIX_DIM, MATRIX_DIM, 3)
|
| 169 |
+
arr = arr.astype(np.int16, copy=False).ravel()
|
| 170 |
rows = np.cumsum(arr.reshape(-1, ROW_LEN).astype(np.int32), axis=1)
|
| 171 |
+
rows = rows.astype(np.int16).reshape(MATRIX_DIM, MATRIX_DIM, 3)
|
| 172 |
+
if scale and scale != 1:
|
| 173 |
+
# 定标档返 float32:0.1 mN 分辨率必须用小数值表达,
|
| 174 |
+
# int16 装不下(÷10 后仍有小数位)
|
| 175 |
+
return rows.astype(np.float32) / np.float32(scale)
|
| 176 |
+
return rows
|
| 177 |
|
| 178 |
|
| 179 |
def pressure_to_heatmap(pressure_matrix, device_type="bevel", scale=None):
|
|
|
|
| 317 |
cx = self.width() / 2 + self._offset.x()
|
| 318 |
cy = self.height() / 2 + self._offset.y()
|
| 319 |
target = QRectF(cx - w / 2, cy - h / 2, w, h)
|
| 320 |
+
# 与主程序 ZoomableVideoWidget 一致:始终平滑缩放。热力图源只有
|
| 321 |
+
# 320×240,铺满面板要放大 2 倍左右,最近邻会把它插成马赛克块,
|
| 322 |
+
# 看着比主程序"粗"——平滑插值才是实时画面那种柔和效果。
|
| 323 |
+
painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
|
| 324 |
painter.drawPixmap(target, self._pixmap, QRectF(self._pixmap.rect()))
|
| 325 |
painter.end()
|
| 326 |
|
|
|
|
| 401 |
# ══════════════════════════════════════════════════════════════════
|
| 402 |
|
| 403 |
def _list_column_to_numpy(column):
|
| 404 |
+
"""list<数值> 列 → (offsets int64[n+1], values[flat])。
|
| 405 |
|
| 406 |
+
走 pyarrow 缓冲区转 numpy:整段矩阵是上亿个元素,走 to_pylist
|
| 407 |
会生成同等数量的 Python 对象(几 GB),必须绕开。
|
| 408 |
+
|
| 409 |
+
元素类型按 parquet schema 取(int16 行差分 / float32 原值),
|
| 410 |
+
**不能硬转 int16**——float32 列硬转会把小数位静默截掉,画面和
|
| 411 |
+
力值都还在,只是精度没了,属于最难发现的一类错。
|
| 412 |
"""
|
| 413 |
+
dtype = (np.float32 if pa.types.is_floating(column.type.value_type)
|
| 414 |
+
else np.int16)
|
| 415 |
offsets, values, base = [], [], 0
|
| 416 |
for chunk in column.chunks:
|
| 417 |
offs = np.asarray(chunk.offsets, dtype=np.int64)
|
| 418 |
+
vals = np.asarray(chunk.values, dtype=dtype)
|
| 419 |
offsets.append(offs[:-1] + base)
|
| 420 |
values.append(vals)
|
| 421 |
base += int(vals.size)
|
| 422 |
if not offsets:
|
| 423 |
+
return np.zeros(1, np.int64), np.zeros(0, dtype)
|
| 424 |
all_offsets = np.concatenate(offsets + [np.array([base], np.int64)])
|
| 425 |
+
all_values = np.concatenate(values) if values else np.zeros(0, dtype)
|
|
|
|
| 426 |
return all_offsets, all_values
|
| 427 |
|
| 428 |
|
|
|
|
| 437 |
return 30.0
|
| 438 |
|
| 439 |
|
| 440 |
+
def _read_episode_matrix_specs(parquet_path: str) -> dict:
|
| 441 |
+
"""读同编号 meta/episodes/chunk-NNN/episode-NNN.parquet 的力矩阵规格。
|
| 442 |
+
|
| 443 |
+
这是**每段一份**的权威来源(列 force_matrix_specs,JSON 字符串):
|
| 444 |
+
主程序工具栏可选 int16 / int16×10 / int16×100 / int16×1000 / float32,
|
| 445 |
+
前四档的落盘类型都是 list<int16>、元素也都是 int,**倍率从数据上完全
|
| 446 |
+
分辨不出**,只有这里记的 scale 能决定该 ÷10 还是 ÷1000。
|
| 447 |
+
|
| 448 |
+
为什么不信 meta/info.json:那是**任务级**、值以最新 episode 为准,
|
| 449 |
+
同一任务里换过档位就会把早先几段覆盖掉(实测 ×10/×100/×1000 三段
|
| 450 |
+
连录、再录一段 float32 之后,info.json 里三段的 scale 全变成 1)。
|
| 451 |
+
读不到(老数据/非池化布局)返回 {},由调用方回退 info.json。
|
| 452 |
+
"""
|
| 453 |
+
parquet_path = os.path.abspath(parquet_path)
|
| 454 |
+
chunk_dir = os.path.dirname(parquet_path) # …/data/chunk-NNN
|
| 455 |
+
task_dir = os.path.dirname(os.path.dirname(chunk_dir))
|
| 456 |
+
meta_path = os.path.join(task_dir, "meta", "episodes",
|
| 457 |
+
os.path.basename(chunk_dir),
|
| 458 |
+
os.path.basename(parquet_path))
|
| 459 |
+
try:
|
| 460 |
+
if "force_matrix_specs" not in pq.read_schema(meta_path).names:
|
| 461 |
+
return {}
|
| 462 |
+
raw = pq.read_table(
|
| 463 |
+
meta_path, columns=["force_matrix_specs"]
|
| 464 |
+
).column("force_matrix_specs")[0].as_py()
|
| 465 |
+
specs = json.loads(raw) if raw else {}
|
| 466 |
+
return specs if isinstance(specs, dict) else {}
|
| 467 |
+
except Exception: # 老任务/非池化布局/单文件副本:当作没有
|
| 468 |
+
return {}
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _read_info_features(parquet_path: str) -> dict:
|
| 472 |
+
"""读 <task>/meta/info.json 的 features(任务级回退来源);缺失回 {}。
|
| 473 |
+
|
| 474 |
+
只在每段元数据读不到时兜底:单档跑到底的任务里它是对的,混档任务里
|
| 475 |
+
它只反映最后一段。含 scale 的列(力矩阵)才用得上,其余键忽略。
|
| 476 |
+
"""
|
| 477 |
+
task_dir = os.path.dirname(os.path.dirname(os.path.dirname(parquet_path)))
|
| 478 |
+
try:
|
| 479 |
+
with open(os.path.join(task_dir, "meta", "info.json"),
|
| 480 |
+
"r", encoding="utf-8") as fh:
|
| 481 |
+
feats = json.load(fh).get("features") or {}
|
| 482 |
+
return feats if isinstance(feats, dict) else {}
|
| 483 |
+
except (OSError, ValueError, TypeError):
|
| 484 |
+
return {}
|
| 485 |
+
|
| 486 |
+
|
| 487 |
class TactileStream:
|
| 488 |
"""单侧触觉流:力矩阵稀疏列(保持上一帧)+ 力总值列。"""
|
| 489 |
|
| 490 |
+
def __init__(self, table, prefix: str, side: str, n_frames: int,
|
| 491 |
+
scale: int = 1):
|
| 492 |
self.prefix = prefix
|
| 493 |
self.side = side
|
| 494 |
name = f"observation.{prefix}gripper_{side}_force_matrix"
|
| 495 |
+
# 倍率随 episode 走(每段录制在开始时锁定),不是全局设置
|
| 496 |
+
self.scale = scale
|
| 497 |
self.offsets, self.values = _list_column_to_numpy(table.column(name))
|
| 498 |
lengths = np.diff(self.offsets)
|
| 499 |
# 稀疏列 → 每帧实际显示的样本行:本帧无新样本则沿用上一帧
|
|
|
|
| 509 |
self._cache_matrix = None
|
| 510 |
|
| 511 |
def matrix(self, idx: int):
|
| 512 |
+
"""第 idx 帧显示的三力平面 (250,250,3)(单位 mN);无数据返回 None。
|
| 513 |
+
|
| 514 |
+
dtype 随录制规格:int16(行差分量化、倍率 1)或 float32
|
| 515 |
+
(原值,含所有 int16×N ���标档——定标档要 ÷N,返 float32)。
|
| 516 |
+
数值已按 self.scale 还原到 mN,可直接参与量程/曲线计算。
|
| 517 |
+
"""
|
| 518 |
if not 0 <= idx < self.hold.size:
|
| 519 |
return None
|
| 520 |
row = int(self.hold[idx])
|
|
|
|
| 523 |
if row == self._cache_row:
|
| 524 |
return self._cache_matrix
|
| 525 |
start, end = int(self.offsets[row]), int(self.offsets[row + 1])
|
| 526 |
+
matrix = decode_force_matrix(self.values[start:end], self.scale)
|
| 527 |
self._cache_row, self._cache_matrix = row, matrix
|
| 528 |
return matrix
|
| 529 |
|
|
|
|
| 538 |
matrix.astype(np.float32).sum(axis=(0, 1)))
|
| 539 |
|
| 540 |
|
| 541 |
+
def auto_gain(stream: "TactileStream", n_frames: int) -> float:
|
| 542 |
+
"""按整段录制的非零 fz 分布定显示增益:p99.5 → 255,钳到 ×8~×128。
|
| 543 |
+
|
| 544 |
+
逐点力值普遍只有个位数(int16 规格下更是只剩 1~3 的整数,见文件头
|
| 545 |
+
「为什么要自适应」),主程序固定 ×50 时整幅图停在深蓝区,用力大小
|
| 546 |
+
只剩接触面积在变。按整段数据定标后同样的用力会走到青/绿/红。
|
| 547 |
+
float32 规格保留小数位,同一段数据的 p99.5 会更细(梯度可见)。
|
| 548 |
+
采样解码(上限 _AUTO_GAIN_SAMPLES 帧)估计百分位,不逐帧扫全片。
|
| 549 |
+
整段无样本(全零/空列)时回退主程序量程。
|
| 550 |
+
"""
|
| 551 |
+
if n_frames <= 0:
|
| 552 |
+
return _DEFAULT_GAIN
|
| 553 |
+
step = max(1, n_frames // _AUTO_GAIN_SAMPLES)
|
| 554 |
+
chunks = []
|
| 555 |
+
for index in range(0, n_frames, step):
|
| 556 |
+
matrix = stream.matrix(index)
|
| 557 |
+
if matrix is None:
|
| 558 |
+
continue
|
| 559 |
+
plane = matrix[:, :, FZ_PLANE]
|
| 560 |
+
nonzero = plane[plane > 0]
|
| 561 |
+
if nonzero.size:
|
| 562 |
+
chunks.append(nonzero)
|
| 563 |
+
if not chunks:
|
| 564 |
+
return _DEFAULT_GAIN
|
| 565 |
+
peak = float(np.percentile(np.concatenate(chunks), _AUTO_GAIN_PCT))
|
| 566 |
+
if peak <= 0:
|
| 567 |
+
return _DEFAULT_GAIN
|
| 568 |
+
return float(min(_AUTO_GAIN_CLAMP[1],
|
| 569 |
+
max(_AUTO_GAIN_CLAMP[0], 255.0 / peak)))
|
| 570 |
+
|
| 571 |
+
|
| 572 |
class TactileEpisode:
|
| 573 |
"""一份 episode parquet:发现全部夹爪/左右触觉流并提供逐帧取数。"""
|
| 574 |
|
| 575 |
def __init__(self, parquet_path: str):
|
| 576 |
self.path = os.path.abspath(parquet_path)
|
| 577 |
+
# 力矩阵规格:每段 meta 优先(权威),info.json 兜底(任务级、
|
| 578 |
+
# 只反映最后一段),都没有则按未定标 ÷1 —— 老 episode 正是如此
|
| 579 |
+
self.matrix_specs = _read_episode_matrix_specs(self.path)
|
| 580 |
+
self.info_features = _read_info_features(self.path)
|
| 581 |
# 只读触觉相关列:整段矩阵本就占内存,别再捎带手套/骨架等列
|
| 582 |
schema = pq.read_schema(parquet_path)
|
| 583 |
matrix_names = [name for name in schema.names
|
|
|
|
| 602 |
prefix = match.group("prefix")
|
| 603 |
side = match.group("side")
|
| 604 |
self.rigs.setdefault(prefix, {})[side] = TactileStream(
|
| 605 |
+
self.table, prefix, side, self.n_frames,
|
| 606 |
+
self.matrix_scale(name))
|
| 607 |
+
|
| 608 |
+
def matrix_scale(self, column: str) -> int:
|
| 609 |
+
"""该力矩阵列的定标倍率:每段 meta → info.json → 1(未定标)。
|
| 610 |
+
|
| 611 |
+
每段 meta 一旦给出可用倍率就到此为止——它对该段是权威的,
|
| 612 |
+
哪怕值恰好是 1(float32 档、或真的没定标),也不能被任务级
|
| 613 |
+
info.json 里别的段的倍率顶掉。
|
| 614 |
+
"""
|
| 615 |
+
for source in (self.matrix_specs, self.info_features):
|
| 616 |
+
feat = source.get(column)
|
| 617 |
+
if not isinstance(feat, dict):
|
| 618 |
+
continue
|
| 619 |
+
try:
|
| 620 |
+
scale = int(feat["scale"])
|
| 621 |
+
except (KeyError, TypeError, ValueError):
|
| 622 |
+
continue
|
| 623 |
+
if scale > 0:
|
| 624 |
+
return scale
|
| 625 |
+
return 1
|
| 626 |
|
| 627 |
def rig_label(self, prefix: str) -> str:
|
| 628 |
match = re.match(r"^gripper_(\d+)_$", prefix or "")
|
|
|
|
| 669 |
# 4. 窗口
|
| 670 |
# ══════════════════════════════════════════════════════════════════
|
| 671 |
|
| 672 |
+
def _slider_to_gain(value: int) -> float:
|
| 673 |
+
"""增益滑块 0~100 → 对数映射 ×8~×256(低端手感更细)。"""
|
| 674 |
+
ratio = _GAIN_MAX / _GAIN_MIN
|
| 675 |
+
return _GAIN_MIN * ratio ** (float(value) / 100.0)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _gain_to_slider(gain: float) -> int:
|
| 679 |
+
gain = min(_GAIN_MAX, max(_GAIN_MIN, float(gain)))
|
| 680 |
+
ratio = _GAIN_MAX / _GAIN_MIN
|
| 681 |
+
return int(round(100.0 * math.log(gain / _GAIN_MIN) / math.log(ratio)))
|
| 682 |
+
|
| 683 |
+
|
| 684 |
class DemoWindow(QMainWindow):
|
| 685 |
|
| 686 |
def __init__(self, path=None):
|
|
|
|
| 691 |
self.idx = 0
|
| 692 |
self.playing = False
|
| 693 |
self._prefix = ""
|
| 694 |
+
self._gain = _DEFAULT_GAIN # 手动增益(关掉自适应时生效)
|
| 695 |
+
self._auto_gains = {} # 当前夹爪各侧的自适应增益
|
| 696 |
|
| 697 |
central = QWidget()
|
| 698 |
# 暗色底:面板未出图时空区域不露白色窗口背景(调色板填充,
|
|
|
|
| 720 |
bar_palette.setColor(bar_widget.backgroundRole(), QColor("#d9d9d9"))
|
| 721 |
bar_widget.setPalette(bar_palette)
|
| 722 |
bar_widget.setAutoFillBackground(True)
|
| 723 |
+
# 两行控制条:第一行文件/播放(进度条要够宽),第二行夹爪/显示增益
|
| 724 |
+
bar_box = QVBoxLayout(bar_widget)
|
| 725 |
+
bar_box.setContentsMargins(6, 4, 6, 4)
|
| 726 |
+
bar_box.setSpacing(4)
|
| 727 |
+
bar = QHBoxLayout()
|
| 728 |
+
bar.setSpacing(6)
|
| 729 |
+
gain_bar = QHBoxLayout()
|
| 730 |
+
gain_bar.setSpacing(6)
|
| 731 |
|
| 732 |
self.btn_open = QPushButton("打开 Parquet")
|
| 733 |
self.btn_play = QPushButton("播放")
|
|
|
|
| 742 |
self.combo_episode.setEnabled(False)
|
| 743 |
self.combo_rig = QComboBox()
|
| 744 |
self.combo_rig.setEnabled(False)
|
| 745 |
+
self.chk_auto = QCheckBox("自适应")
|
| 746 |
+
self.chk_auto.setChecked(True) # 默认按录制数据定标,颜色才随力变
|
| 747 |
+
self.chk_auto.setEnabled(False)
|
| 748 |
+
self.chk_auto.setToolTip(
|
| 749 |
+
"按整段录制的非零 fz 定标(每侧独立),颜色随力变化明显;\n"
|
| 750 |
+
"关掉后用下面的滑块固定增益,拖到 ×50 与主程序逐像素一致")
|
| 751 |
+
self.slider_gain = QSlider(Qt.Horizontal)
|
| 752 |
+
self.slider_gain.setRange(0, 100)
|
| 753 |
+
self.slider_gain.setValue(_gain_to_slider(_DEFAULT_GAIN))
|
| 754 |
+
self.slider_gain.setFixedWidth(110)
|
| 755 |
+
self.slider_gain.setEnabled(False)
|
| 756 |
+
self.lbl_gain = QLabel("增益 ×50")
|
| 757 |
+
self.lbl_gain.setMinimumWidth(112) # 容得下「增益 ×128 / ×64」
|
| 758 |
self.chk_loop = QCheckBox("循环")
|
| 759 |
self.chk_loop.setChecked(True)
|
| 760 |
self.lbl_frame = QLabel("- / -")
|
|
|
|
| 765 |
bar.addWidget(self.btn_prev)
|
| 766 |
bar.addWidget(self.slider, 1)
|
| 767 |
bar.addWidget(self.btn_next)
|
|
|
|
| 768 |
bar.addWidget(self.chk_loop)
|
| 769 |
bar.addWidget(self.lbl_frame)
|
| 770 |
+
|
| 771 |
+
gain_bar.addWidget(self.combo_rig)
|
| 772 |
+
gain_bar.addWidget(self.chk_auto)
|
| 773 |
+
gain_bar.addWidget(self.slider_gain)
|
| 774 |
+
gain_bar.addWidget(self.lbl_gain)
|
| 775 |
+
gain_bar.addStretch(1)
|
| 776 |
+
|
| 777 |
+
bar_box.addLayout(bar)
|
| 778 |
+
bar_box.addLayout(gain_bar)
|
| 779 |
root.addWidget(bar_widget)
|
| 780 |
|
| 781 |
self.btn_open.clicked.connect(self.open_file_dialog)
|
|
|
|
| 786 |
self.slider.sliderReleased.connect(self._on_slider_released)
|
| 787 |
self.combo_episode.activated.connect(self._on_episode_chosen)
|
| 788 |
self.combo_rig.activated.connect(self._on_rig_chosen)
|
| 789 |
+
self.chk_auto.toggled.connect(self._on_auto_toggled)
|
| 790 |
+
self.slider_gain.valueChanged.connect(self._on_gain_changed)
|
| 791 |
|
| 792 |
self.timer = QTimer(self)
|
| 793 |
self.timer.setTimerType(Qt.PreciseTimer) # 节奏计时器要精确节拍
|
|
|
|
| 846 |
for side, panel in self.panels.items():
|
| 847 |
panel.setVisible(side in sides)
|
| 848 |
panel.reset()
|
| 849 |
+
self.chk_auto.setEnabled(bool(sides))
|
| 850 |
+
self.slider_gain.setEnabled(bool(sides)
|
| 851 |
+
and not self.chk_auto.isChecked())
|
| 852 |
+
self._recompute_auto_gains()
|
| 853 |
|
| 854 |
self.slider.blockSignals(True)
|
| 855 |
self.slider.setRange(0, max(0, data.n_frames - 1))
|
|
|
|
| 865 |
os.path.basename(data.path), data.fps, data.n_frames))
|
| 866 |
print("[力矩阵] {} 帧 {} 台夹爪,矩阵列常驻 {:.0f} MB".format(
|
| 867 |
data.n_frames, len(data.rigs), data.matrix_bytes() / 1e6))
|
| 868 |
+
self._update_gain_label()
|
| 869 |
self.render_frame(0)
|
| 870 |
|
| 871 |
def _on_episode_chosen(self, index):
|
|
|
|
| 880 |
for side, panel in self.panels.items():
|
| 881 |
panel.setVisible(side in sides)
|
| 882 |
panel.reset()
|
| 883 |
+
self._recompute_auto_gains()
|
| 884 |
+
self._update_gain_label()
|
| 885 |
+
self.render_frame(self.idx)
|
| 886 |
+
|
| 887 |
+
# ── 显示增益(自适应 / 手动)──────────────────────
|
| 888 |
+
|
| 889 |
+
def _recompute_auto_gains(self):
|
| 890 |
+
"""按当前夹爪各侧的整段数据重算自适应增益(采样解码,加载时才做)。"""
|
| 891 |
+
sides = self.data.rigs.get(self._prefix, {}) if self.data else {}
|
| 892 |
+
self._auto_gains = {
|
| 893 |
+
side: auto_gain(stream, self.data.n_frames)
|
| 894 |
+
for side, stream in sides.items()}
|
| 895 |
+
|
| 896 |
+
def _effective_gains(self):
|
| 897 |
+
"""本帧每侧实际使用的增益:自适应按侧给,手动则两侧同一个值。"""
|
| 898 |
+
sides = self.data.rigs.get(self._prefix, {}) if self.data else {}
|
| 899 |
+
if self.chk_auto.isChecked():
|
| 900 |
+
return {side: self._auto_gains.get(side, _DEFAULT_GAIN)
|
| 901 |
+
for side in sides}
|
| 902 |
+
return {side: self._gain for side in sides}
|
| 903 |
+
|
| 904 |
+
def _update_gain_label(self):
|
| 905 |
+
if self.data is None:
|
| 906 |
+
self.lbl_gain.setText("增益 ×{:.0f}".format(self._gain))
|
| 907 |
+
return
|
| 908 |
+
if self.chk_auto.isChecked():
|
| 909 |
+
gains = self._effective_gains()
|
| 910 |
+
text = " / ".join("×{:.0f}".format(gains[side])
|
| 911 |
+
for side in sorted(gains))
|
| 912 |
+
self.lbl_gain.setText("增益 {}".format(text))
|
| 913 |
+
else:
|
| 914 |
+
self.lbl_gain.setText("增益 ×{:.0f}".format(self._gain))
|
| 915 |
+
|
| 916 |
+
def _on_auto_toggled(self, checked):
|
| 917 |
+
self.slider_gain.setEnabled(self.data is not None and not checked)
|
| 918 |
+
if not checked:
|
| 919 |
+
# 取消自适应时把滑块挪到当前自适应值,画面不会突然变暗
|
| 920 |
+
gains = list(self._auto_gains.values()) or [_DEFAULT_GAIN]
|
| 921 |
+
self.slider_gain.blockSignals(True)
|
| 922 |
+
self.slider_gain.setValue(_gain_to_slider(max(gains)))
|
| 923 |
+
self.slider_gain.blockSignals(False)
|
| 924 |
+
self._gain = _slider_to_gain(self.slider_gain.value())
|
| 925 |
+
self._update_gain_label()
|
| 926 |
+
self.render_frame(self.idx)
|
| 927 |
+
|
| 928 |
+
def _on_gain_changed(self, value):
|
| 929 |
+
self._gain = _slider_to_gain(value)
|
| 930 |
+
self._update_gain_label()
|
| 931 |
self.render_frame(self.idx)
|
| 932 |
|
| 933 |
# ── 播放控制 ──────────────────────────────────────
|
|
|
|
| 972 |
return
|
| 973 |
index = max(0, min(index, self.data.n_frames - 1))
|
| 974 |
self.idx = index
|
| 975 |
+
gains = self._effective_gains()
|
| 976 |
for side, panel in self.panels.items():
|
| 977 |
stream = self.data.rigs.get(self._prefix, {}).get(side)
|
| 978 |
if stream is None:
|
|
|
|
| 981 |
if matrix is not None:
|
| 982 |
# 稀疏帧返回 None 时不动画面:与实时画面保持上一次结果一致
|
| 983 |
panel.show_tactile(
|
| 984 |
+
pressure_to_heatmap(matrix[:, :, FZ_PLANE],
|
| 985 |
+
scale=gains.get(side, _DEFAULT_GAIN)),
|
| 986 |
stream.force_at(index))
|
| 987 |
self.slider.blockSignals(True)
|
| 988 |
self.slider.setValue(index)
|
collector/tools/tests/test_gripper_force_matrix_demo.py
CHANGED
|
@@ -9,7 +9,7 @@
|
|
| 9 |
1. 解码/热力图与主程序口径一致(对比 core.gripper.tactile_process_worker)
|
| 10 |
2. 合成 episode:稀疏列保持上一帧、rig1/rig2 发现、默认选样本多的夹爪、
|
| 11 |
力列缺失时回退三平面求和
|
| 12 |
-
3. GUI 路径:加载 / 渲染 / 跳帧 / 播放节拍 / 切
|
| 13 |
4. 真实录制(data/recordings 下任一含力矩阵列的 episode)→ 加载并渲染
|
| 14 |
退出码 0 = 全部通过。
|
| 15 |
"""
|
|
@@ -56,7 +56,7 @@ def load_demo_module():
|
|
| 56 |
|
| 57 |
|
| 58 |
def encode_matrix(matrix: np.ndarray) -> list:
|
| 59 |
-
"""与 ui/main_window.encode_gripper_force_matrix 同一口径。"""
|
| 60 |
flat = np.asarray(matrix, np.float32).reshape(matrix.shape[0], -1)
|
| 61 |
q = np.clip(flat, -32767.0, 32767.0).astype(np.int16)
|
| 62 |
diff = np.empty_like(q)
|
|
@@ -65,6 +65,26 @@ def encode_matrix(matrix: np.ndarray) -> list:
|
|
| 65 |
return np.frombuffer(diff.tobytes(), dtype=np.int16).tolist()
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def contact_matrix(value: float, center=(120, 120)) -> np.ndarray:
|
| 69 |
"""250×250×3:中心一个方块接触区,fz=value。"""
|
| 70 |
matrix = np.zeros((250, 250, 3), np.float32)
|
|
@@ -74,41 +94,95 @@ def contact_matrix(value: float, center=(120, 120)) -> np.ndarray:
|
|
| 74 |
return matrix
|
| 75 |
|
| 76 |
|
| 77 |
-
def make_synthetic_episode(root: str, n: int = 12
|
|
|
|
|
|
|
|
|
|
| 78 |
"""合成一份双夹爪 episode:
|
| 79 |
|
| 80 |
- rig1 左侧:矩阵只在第 2 帧有新样本,第 3~5 帧为空(测保持上一帧);
|
| 81 |
第 6 帧新样本。力列缺失(测回退三平面求和)
|
| 82 |
- rig1 右侧:每帧都有样本 + 力列(测力列优先)
|
| 83 |
- rig2 左侧:只有 1 个样本(测默认选样本多的夹爪 = rig1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
"""
|
| 85 |
-
task = os.path.join(root,
|
| 86 |
os.makedirs(os.path.join(task, "data", "chunk-000"), exist_ok=True)
|
| 87 |
os.makedirs(os.path.join(task, "meta"), exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
with open(os.path.join(task, "meta", "info.json"), "w",
|
| 89 |
encoding="utf-8") as fh:
|
| 90 |
-
json.dump({"fps": 30}, fh)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
empty = []
|
| 93 |
-
left_rows = [empty, empty,
|
| 94 |
-
empty, empty, empty,
|
| 95 |
left_rows += [empty] * (n - len(left_rows))
|
| 96 |
-
right_rows = [
|
| 97 |
for i in range(n)]
|
| 98 |
-
rig2_rows = [empty, empty, empty,
|
| 99 |
rig2_rows += [empty] * (n - len(rig2_rows))
|
| 100 |
right_force = [[float(i), -float(i) / 2, 100.0 + i] for i in range(n)]
|
| 101 |
|
| 102 |
table = pa.table({
|
| 103 |
"frame_index": pa.array(range(n), pa.int64()),
|
| 104 |
"observation.gripper_left_force_matrix":
|
| 105 |
-
pa.array(left_rows, pa.list_(
|
| 106 |
"observation.gripper_right_force_matrix":
|
| 107 |
-
pa.array(right_rows, pa.list_(
|
| 108 |
"observation.gripper_right_force":
|
| 109 |
pa.array(right_force, pa.list_(pa.float32(), 3)),
|
| 110 |
"observation.gripper_2_gripper_left_force_matrix":
|
| 111 |
-
pa.array(rig2_rows, pa.list_(
|
| 112 |
})
|
| 113 |
path = os.path.join(task, "data", "chunk-000", "episode-000.parquet")
|
| 114 |
pq.write_table(table, path)
|
|
@@ -144,6 +218,14 @@ def main() -> int:
|
|
| 144 |
check("长度不符/空样本 → None",
|
| 145 |
mod.decode_force_matrix(np.zeros(7, np.int16)) is None
|
| 146 |
and mod.decode_force_matrix([]) is None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
try:
|
| 148 |
import core.gripper.tactile_process_worker as worker
|
| 149 |
same = True
|
|
@@ -154,6 +236,60 @@ def main() -> int:
|
|
| 154 |
same = False
|
| 155 |
break
|
| 156 |
check("热力图 = tactile_process_worker.pressure_to_heatmap", same)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
except Exception as exc: # 主程序模块不可导入时不阻塞
|
| 158 |
print(f" [SKIP] 热力图对比({exc})")
|
| 159 |
|
|
@@ -188,6 +324,134 @@ def main() -> int:
|
|
| 188 |
right.force_at(5) == (5.0, -2.5, 105.0),
|
| 189 |
str(right.force_at(5)))
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
print("[3] GUI 路径")
|
| 192 |
window = mod.DemoWindow()
|
| 193 |
window.show() # 离屏下 isVisible/isHidden 需先 show
|
|
@@ -237,6 +501,28 @@ def main() -> int:
|
|
| 237 |
app.processEvents()
|
| 238 |
check("关循环在尾帧停住",
|
| 239 |
window.idx == 11 and not window.timer.isActive())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
window.close()
|
| 241 |
|
| 242 |
print("[4] 目录加载")
|
|
|
|
| 9 |
1. 解码/热力图与主程序口径一致(对比 core.gripper.tactile_process_worker)
|
| 10 |
2. 合成 episode:稀疏列保持上一帧、rig1/rig2 发现、默认选样本多的夹爪、
|
| 11 |
力列缺失时回退三平面求和
|
| 12 |
+
3. GUI 路径:加载 / 渲染 / 跳帧 / 播放节拍 / 切夹爪 / 显示增益 / 目录加载
|
| 13 |
4. 真实录制(data/recordings 下任一含力矩阵列的 episode)→ 加载并渲染
|
| 14 |
退出码 0 = 全部通过。
|
| 15 |
"""
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def encode_matrix(matrix: np.ndarray) -> list:
|
| 59 |
+
"""与 ui/main_window.encode_gripper_force_matrix 同一口径(int16 规格)。"""
|
| 60 |
flat = np.asarray(matrix, np.float32).reshape(matrix.shape[0], -1)
|
| 61 |
q = np.clip(flat, -32767.0, 32767.0).astype(np.int16)
|
| 62 |
diff = np.empty_like(q)
|
|
|
|
| 65 |
return np.frombuffer(diff.tobytes(), dtype=np.int16).tolist()
|
| 66 |
|
| 67 |
|
| 68 |
+
def encode_matrix_f32(matrix: np.ndarray) -> list:
|
| 69 |
+
"""同一编码器的 float32 规格分支:原值直存、扁平、元素为 float。"""
|
| 70 |
+
return np.asarray(matrix, np.float32).reshape(-1).tolist()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def encode_matrix_scaled(matrix: np.ndarray, scale: int) -> list:
|
| 74 |
+
"""同一编码器的 int16×N 定标分支:×N → rint → 行差分,元素仍是 int。
|
| 75 |
+
|
| 76 |
+
注意元素类型与未定标的 int16 档完全一样 —— 这正是 demo 必须去
|
| 77 |
+
info.json 读 scale 的原因,靠数据本身分辨不出来。
|
| 78 |
+
"""
|
| 79 |
+
flat = np.asarray(matrix, np.float32).reshape(matrix.shape[0], -1)
|
| 80 |
+
q = np.clip(np.rint(flat * np.float32(scale)),
|
| 81 |
+
-32767.0, 32767.0).astype(np.int16)
|
| 82 |
+
diff = np.empty_like(q)
|
| 83 |
+
diff[:, 0] = q[:, 0]
|
| 84 |
+
diff[:, 1:] = q[:, 1:] - q[:, :-1]
|
| 85 |
+
return np.frombuffer(diff.tobytes(), dtype=np.int16).tolist()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
def contact_matrix(value: float, center=(120, 120)) -> np.ndarray:
|
| 89 |
"""250×250×3:中心一个方块接触区,fz=value。"""
|
| 90 |
matrix = np.zeros((250, 250, 3), np.float32)
|
|
|
|
| 94 |
return matrix
|
| 95 |
|
| 96 |
|
| 97 |
+
def make_synthetic_episode(root: str, n: int = 12, float32: bool = False,
|
| 98 |
+
name: str = "synthetic_gripper_task",
|
| 99 |
+
scale: int = 1, info_scale=None,
|
| 100 |
+
meta_scale=None) -> str:
|
| 101 |
"""合成一份双夹爪 episode:
|
| 102 |
|
| 103 |
- rig1 左侧:矩阵只在第 2 帧有新样本,第 3~5 帧为空(测保持上一帧);
|
| 104 |
第 6 帧新样本。力列缺失(测回退三平面求和)
|
| 105 |
- rig1 右侧:每帧都有样本 + 力列(测力列优先)
|
| 106 |
- rig2 左侧:只有 1 个样本(测默认选样本多的夹爪 = rig1)
|
| 107 |
+
|
| 108 |
+
float32=True 时三列都按 float32 规格写(原值直存、无量化),
|
| 109 |
+
取值用带小数的值以证明小数位真的被保留。
|
| 110 |
+
scale>1 时按 int16×scale 写(列类型仍是 int16)—— 倍率写哪儿由下面
|
| 111 |
+
两个参数决定,两者不一致的用例见 [2e]:
|
| 112 |
+
|
| 113 |
+
- `info_scale`:写进任务级 info.json features.scale(回退来源),
|
| 114 |
+
None = 与 `scale` 相同;
|
| 115 |
+
- `meta_scale`:非 None 时另写一份 meta/episodes 行(每段权威来源),
|
| 116 |
+
值就是它 —— 与 `scale` 不一致即模拟「同任务里换过档位,info.json
|
| 117 |
+
被后一段顶掉」的现场。
|
| 118 |
"""
|
| 119 |
+
task = os.path.join(root, name)
|
| 120 |
os.makedirs(os.path.join(task, "data", "chunk-000"), exist_ok=True)
|
| 121 |
os.makedirs(os.path.join(task, "meta"), exist_ok=True)
|
| 122 |
+
|
| 123 |
+
enc = encode_matrix_f32 if float32 else (
|
| 124 |
+
(lambda m: encode_matrix_scaled(m, scale)) if scale > 1
|
| 125 |
+
else encode_matrix)
|
| 126 |
+
item = pa.float32() if float32 else pa.int16()
|
| 127 |
+
cols = ["observation.gripper_left_force_matrix",
|
| 128 |
+
"observation.gripper_right_force_matrix",
|
| 129 |
+
"observation.gripper_2_gripper_left_force_matrix"]
|
| 130 |
+
if info_scale is None:
|
| 131 |
+
info_scale = scale
|
| 132 |
+
features = {c: {"dtype": "float32" if float32 else "int16",
|
| 133 |
+
"shape": [250, 250, 3],
|
| 134 |
+
"encoding": ("row_flat_raw" if float32
|
| 135 |
+
else "row_diff_quantized"),
|
| 136 |
+
"scale": 1 if float32 else info_scale}
|
| 137 |
+
for c in cols}
|
| 138 |
with open(os.path.join(task, "meta", "info.json"), "w",
|
| 139 |
encoding="utf-8") as fh:
|
| 140 |
+
json.dump({"fps": 30, "features": features}, fh)
|
| 141 |
+
|
| 142 |
+
if meta_scale is not None:
|
| 143 |
+
# 走 writer 自己的行构造器,保证与生产 schema 同型(少一列就会
|
| 144 |
+
# 拼不成一张表,这里正好把两端的契约钉在一起)
|
| 145 |
+
from core.egodata_writer import _episode_rows_table
|
| 146 |
+
meta_dir = os.path.join(task, "meta", "episodes", "chunk-000")
|
| 147 |
+
os.makedirs(meta_dir, exist_ok=True)
|
| 148 |
+
specs = {c: {"dtype": "float32" if float32 else "int16",
|
| 149 |
+
"shape": [250, 250, 3],
|
| 150 |
+
"encoding": ("row_flat_raw" if float32
|
| 151 |
+
else "row_diff_quantized"),
|
| 152 |
+
"scale": 1 if float32 else meta_scale}
|
| 153 |
+
for c in cols}
|
| 154 |
+
pq.write_table(_episode_rows_table([{
|
| 155 |
+
"episode_index": 1, "task_index": 0, "start_frame_index": 0,
|
| 156 |
+
"end_frame_index": n - 1, "length": n, "created_at": 0.0,
|
| 157 |
+
"duration_sec": n / 30.0, "drop_stats": "{}",
|
| 158 |
+
"video_codec": "{}", "calibration": "{}",
|
| 159 |
+
"force_matrix_specs": json.dumps(specs),
|
| 160 |
+
}]), os.path.join(meta_dir, "episode-000.parquet"))
|
| 161 |
+
|
| 162 |
+
# float32 规格用带小数的幅值:int16 规格下 0.9 会整幅归零
|
| 163 |
+
lv = (5.75, 9.125) if float32 else (5.0, 9.0)
|
| 164 |
+
rv = (3.375, 0.875)
|
| 165 |
|
| 166 |
empty = []
|
| 167 |
+
left_rows = [empty, empty, enc(contact_matrix(lv[0])),
|
| 168 |
+
empty, empty, empty, enc(contact_matrix(lv[1]))]
|
| 169 |
left_rows += [empty] * (n - len(left_rows))
|
| 170 |
+
right_rows = [enc(contact_matrix(rv[0] + i * rv[1]))
|
| 171 |
for i in range(n)]
|
| 172 |
+
rig2_rows = [empty, empty, empty, enc(contact_matrix(2.0))]
|
| 173 |
rig2_rows += [empty] * (n - len(rig2_rows))
|
| 174 |
right_force = [[float(i), -float(i) / 2, 100.0 + i] for i in range(n)]
|
| 175 |
|
| 176 |
table = pa.table({
|
| 177 |
"frame_index": pa.array(range(n), pa.int64()),
|
| 178 |
"observation.gripper_left_force_matrix":
|
| 179 |
+
pa.array(left_rows, pa.list_(item)),
|
| 180 |
"observation.gripper_right_force_matrix":
|
| 181 |
+
pa.array(right_rows, pa.list_(item)),
|
| 182 |
"observation.gripper_right_force":
|
| 183 |
pa.array(right_force, pa.list_(pa.float32(), 3)),
|
| 184 |
"observation.gripper_2_gripper_left_force_matrix":
|
| 185 |
+
pa.array(rig2_rows, pa.list_(item)),
|
| 186 |
})
|
| 187 |
path = os.path.join(task, "data", "chunk-000", "episode-000.parquet")
|
| 188 |
pq.write_table(table, path)
|
|
|
|
| 218 |
check("长度不符/空样本 → None",
|
| 219 |
mod.decode_force_matrix(np.zeros(7, np.int16)) is None
|
| 220 |
and mod.decode_force_matrix([]) is None)
|
| 221 |
+
plane = rng.uniform(0, 30, (250, 250)).astype(np.float32)
|
| 222 |
+
check("scale=50 即主程序固定量程",
|
| 223 |
+
np.array_equal(mod.pressure_to_heatmap(plane, scale=50.0),
|
| 224 |
+
mod.pressure_to_heatmap(plane)))
|
| 225 |
+
check("增益滑块对数映射往返",
|
| 226 |
+
all(abs(mod._slider_to_gain(mod._gain_to_slider(g)) - g) < 0.05 * g
|
| 227 |
+
for g in (8.0, 50.0, 128.0, 256.0)),
|
| 228 |
+
f"×50 → 滑块 {mod._gain_to_slider(50.0)}")
|
| 229 |
try:
|
| 230 |
import core.gripper.tactile_process_worker as worker
|
| 231 |
same = True
|
|
|
|
| 236 |
same = False
|
| 237 |
break
|
| 238 |
check("热力图 = tactile_process_worker.pressure_to_heatmap", same)
|
| 239 |
+
|
| 240 |
+
print("[1b] 主程序自适应显示量程(HeatmapScaleTracker)")
|
| 241 |
+
idle = np.zeros((250, 250), np.float32)
|
| 242 |
+
tracker = worker.HeatmapScaleTracker("bevel")
|
| 243 |
+
floor_gain = 255.0 / tracker.floor
|
| 244 |
+
check("无接触 → 增益取下限(255/FLOOR)",
|
| 245 |
+
abs(tracker.scale(idle) - floor_gain) < 1e-6
|
| 246 |
+
and abs(tracker.ref - tracker.floor) < 1e-9,
|
| 247 |
+
f"×{floor_gain:.1f}(FLOOR={tracker.floor:g})")
|
| 248 |
+
sparse = idle.copy()
|
| 249 |
+
sparse[10, 10] = 250.0 # 零星噪点 < MIN_PIXELS
|
| 250 |
+
check("零星噪点不抬量程",
|
| 251 |
+
abs(tracker.scale(sparse) - floor_gain) < 1e-6
|
| 252 |
+
and abs(tracker.ref - tracker.floor) < 1e-9)
|
| 253 |
+
contact = idle.copy()
|
| 254 |
+
contact[100:120, 100:120] = 2.0 # 典型接触:p99 仍在下限之下
|
| 255 |
+
check("典型接触(值 2 < FLOOR)不降增益",
|
| 256 |
+
abs(tracker.scale(contact) - floor_gain) < 1e-6,
|
| 257 |
+
f"ref={tracker.ref:.2f}")
|
| 258 |
+
hard = idle.copy()
|
| 259 |
+
hard[100:140, 100:140] = tracker.ceiling * 4 # 远超上限
|
| 260 |
+
first = tracker.scale(hard)
|
| 261 |
+
for _ in range(1200): # τ≈8s@30fps,1200 帧 ≈ 5τ
|
| 262 |
+
last = tracker.scale(hard)
|
| 263 |
+
check("持续重压 → 参考值升到上限、增益随之下降",
|
| 264 |
+
abs(tracker.ref - tracker.ceiling) < 0.2
|
| 265 |
+
and abs(last - 255.0 / tracker.ceiling) < 0.5
|
| 266 |
+
and first > last,
|
| 267 |
+
f"×{first:.1f} → ×{last:.1f}(上限 {tracker.ceiling:g})")
|
| 268 |
+
for _ in range(2000):
|
| 269 |
+
idle_gain = tracker.scale(idle)
|
| 270 |
+
check("松开 → 参考值衰减回下限",
|
| 271 |
+
abs(tracker.ref - tracker.floor) < 0.2
|
| 272 |
+
and abs(idle_gain - floor_gain) < 0.5,
|
| 273 |
+
f"ref={tracker.ref:.3f} ×{idle_gain:.1f}")
|
| 274 |
+
|
| 275 |
+
class _FakeSensor:
|
| 276 |
+
device_type = "bevel"
|
| 277 |
+
|
| 278 |
+
fake = _FakeSensor()
|
| 279 |
+
worker._HEATMAP_AUTO_CACHE["value"] = True
|
| 280 |
+
gain = worker.heatmap_scale_for(fake, contact)
|
| 281 |
+
check("heatmap_scale_for 把跟踪器挂在传感器上",
|
| 282 |
+
abs(gain - floor_gain) < 1e-6
|
| 283 |
+
and isinstance(getattr(fake, "_ksq_heatmap_scale", None),
|
| 284 |
+
worker.HeatmapScaleTracker))
|
| 285 |
+
state = worker.snapshot_sensor_state(fake)
|
| 286 |
+
check("_ksq_ 状态不进跨进程快照",
|
| 287 |
+
"_ksq_heatmap_scale" not in state
|
| 288 |
+
and not any(k.startswith("_ksq_heatmap") for k in state))
|
| 289 |
+
worker._HEATMAP_AUTO_CACHE["value"] = False
|
| 290 |
+
check("关闭自适应 → 回固定量程(None)",
|
| 291 |
+
worker.heatmap_scale_for(fake, contact) is None)
|
| 292 |
+
worker._HEATMAP_AUTO_CACHE.pop("value", None)
|
| 293 |
except Exception as exc: # 主程序模块不可导入时不阻塞
|
| 294 |
print(f" [SKIP] 热力图对比({exc})")
|
| 295 |
|
|
|
|
| 324 |
right.force_at(5) == (5.0, -2.5, 105.0),
|
| 325 |
str(right.force_at(5)))
|
| 326 |
|
| 327 |
+
print("[2b] 自适应量程")
|
| 328 |
+
g_left = mod.auto_gain(left, episode.n_frames)
|
| 329 |
+
g_right = mod.auto_gain(right, episode.n_frames)
|
| 330 |
+
check("自适应增益落在钳位区间",
|
| 331 |
+
all(8.0 <= g <= 128.0 for g in (g_left, g_right)),
|
| 332 |
+
f"left=×{g_left:.1f} right=×{g_right:.1f}")
|
| 333 |
+
check("力值大的那侧增益更小", g_right < g_left,
|
| 334 |
+
f"left 峰值 9 → ×{g_left:.1f},right 峰值 14 → ×{g_right:.1f}")
|
| 335 |
+
empty_stream = mod.TactileStream(pa.table({
|
| 336 |
+
"observation.gripper_left_force_matrix":
|
| 337 |
+
pa.array([[] for _ in range(4)], pa.list_(pa.int16()))}),
|
| 338 |
+
"", "left", 4)
|
| 339 |
+
check("整段无样本 → 回退主程序量程",
|
| 340 |
+
mod.auto_gain(empty_stream, 4) == 50.0)
|
| 341 |
+
|
| 342 |
+
print("[2c] float32 规格 episode")
|
| 343 |
+
fpath = make_synthetic_episode(tmp, float32=True,
|
| 344 |
+
name="synthetic_gripper_f32")
|
| 345 |
+
check("float32 列的元素类型 = float32",
|
| 346 |
+
pq.read_schema(fpath).field(
|
| 347 |
+
"observation.gripper_left_force_matrix"
|
| 348 |
+
).type.value_type == pa.float32())
|
| 349 |
+
fep = mod.TactileEpisode(fpath)
|
| 350 |
+
fleft = fep.rigs[""]["left"]
|
| 351 |
+
check("_list_column_to_numpy 不硬转 int16(小数位保留)",
|
| 352 |
+
fleft.values.dtype == np.float32,
|
| 353 |
+
f"values.dtype={fleft.values.dtype}")
|
| 354 |
+
m = fleft.matrix(2)
|
| 355 |
+
check("float32 矩阵解码形状/dtype",
|
| 356 |
+
m is not None and m.shape == (250, 250, 3)
|
| 357 |
+
and m.dtype == np.float32,
|
| 358 |
+
f"{None if m is None else (m.shape, m.dtype)}")
|
| 359 |
+
check("float32 矩阵是原值而非 cumsum(无差分)",
|
| 360 |
+
m is not None and abs(float(m[120, 120, 2]) - 5.75) < 1e-6,
|
| 361 |
+
f"中心 fz={None if m is None else float(m[120, 120, 2]):.4f}(期望 5.75)")
|
| 362 |
+
check("float32 亚毫牛小数位保留(fx=5.75×0.25)",
|
| 363 |
+
m is not None and abs(float(m[120, 120, 0]) - 1.4375) < 1e-6,
|
| 364 |
+
f"中心 fx={None if m is None else float(m[120, 120, 0]):.4f}(期望 1.4375)")
|
| 365 |
+
check("int16 与 float32 走同一解码入口、结果不同",
|
| 366 |
+
not np.array_equal(
|
| 367 |
+
mod.decode_force_matrix(encode_matrix_f32(contact_matrix(5.75))),
|
| 368 |
+
mod.decode_force_matrix(encode_matrix(contact_matrix(5.75)))),
|
| 369 |
+
"同一矩阵两种规格解码结果必须体现精度差异")
|
| 370 |
+
fempty = mod.TactileStream(pa.table({
|
| 371 |
+
"observation.gripper_left_force_matrix":
|
| 372 |
+
pa.array([[] for _ in range(4)], pa.list_(pa.float32()))}),
|
| 373 |
+
"", "left", 4)
|
| 374 |
+
check("float32 空列 → 同样回退主程序量程",
|
| 375 |
+
fempty.values.dtype == np.float32
|
| 376 |
+
and mod.auto_gain(fempty, 4) == 50.0,
|
| 377 |
+
f"dtype={fempty.values.dtype}")
|
| 378 |
+
|
| 379 |
+
print("[2d] int16×N 定标档 episode(只有 info.json、无 meta 行)")
|
| 380 |
+
for scale in (10, 100):
|
| 381 |
+
spath = make_synthetic_episode(tmp, scale=scale,
|
| 382 |
+
name=f"synthetic_gripper_x{scale}")
|
| 383 |
+
stype = pq.read_schema(spath).field(
|
| 384 |
+
"observation.gripper_left_force_matrix").type
|
| 385 |
+
check(f"×{scale} 列类型仍是 list<int16>(与未定标档数据上无法区分)",
|
| 386 |
+
stype == pa.list_(pa.int16()), str(stype))
|
| 387 |
+
sep = mod.TactileEpisode(spath)
|
| 388 |
+
sleft = sep.rigs[""]["left"]
|
| 389 |
+
check(f"×{scale} demo 从 info.json 读到倍率",
|
| 390 |
+
sleft.scale == scale, f"scale={sleft.scale}")
|
| 391 |
+
sm = sleft.matrix(2)
|
| 392 |
+
check(f"×{scale} 矩阵已 ÷{scale} 还原 mN(真值 5.0)",
|
| 393 |
+
sm is not None and abs(float(sm[120, 120, 2]) - 5.0) < 1e-4,
|
| 394 |
+
f"中心 fz={None if sm is None else float(sm[120, 120, 2]):.4f}")
|
| 395 |
+
check(f"×{scale} 定标档返 float32(÷N 后需有小数值域)",
|
| 396 |
+
sm is not None and sm.dtype == np.float32,
|
| 397 |
+
f"dtype={None if sm is None else sm.dtype}")
|
| 398 |
+
# 契约反证:不传 scale 就是静默放大 N 倍(画面形状还对,最难发现)
|
| 399 |
+
miss = mod.decode_force_matrix(
|
| 400 |
+
encode_matrix_scaled(contact_matrix(5.0), scale))
|
| 401 |
+
check(f"×{scale} 漏传 scale → 数值放大 {scale} 倍(静默错)",
|
| 402 |
+
abs(float(miss[120, 120, 2]) - 5.0 * scale) < 1e-3,
|
| 403 |
+
f"漏读得 {float(miss[120, 120, 2]):.1f},应为 5.0")
|
| 404 |
+
|
| 405 |
+
print("[2e] 倍率来源优先级:每段 meta > info.json > 1")
|
| 406 |
+
# ① 两处都有且不一致:同任务换过档位的现场——本段是 ×10,后来录的
|
| 407 |
+
# 一段把任务级 info.json 顶成了 ×1000。必须听每段自己的。
|
| 408 |
+
both = make_synthetic_episode(
|
| 409 |
+
tmp, scale=10, info_scale=1000, meta_scale=10,
|
| 410 |
+
name="synthetic_spec_meta_wins")
|
| 411 |
+
bs = mod.TactileEpisode(both).rigs[""]["left"]
|
| 412 |
+
check("meta 与 info.json 冲突 → 取 meta(×10,不被任务级覆盖)",
|
| 413 |
+
bs.scale == 10, f"scale={bs.scale}(期望 10,info.json 说 1000)")
|
| 414 |
+
bm = bs.matrix(2)
|
| 415 |
+
check("冲突时数值按 meta 还原(真值 5.0 mN)",
|
| 416 |
+
bm is not None and abs(float(bm[120, 120, 2]) - 5.0) < 1e-4,
|
| 417 |
+
f"中心 fz={None if bm is None else float(bm[120, 120, 2]):.4f}")
|
| 418 |
+
|
| 419 |
+
# ② meta 说 1(未定标/float32 档),info.json 说 1000:1 也是权威值,
|
| 420 |
+
# 不能被别的段的档位顶掉——这条最容易写反。
|
| 421 |
+
one = make_synthetic_episode(
|
| 422 |
+
tmp, scale=1, info_scale=1000, meta_scale=1,
|
| 423 |
+
name="synthetic_spec_meta_one")
|
| 424 |
+
os_ = mod.TactileEpisode(one).rigs[""]["left"]
|
| 425 |
+
check("meta 值为 1 也算权威 → 不退回 info.json 的 1000",
|
| 426 |
+
os_.scale == 1, f"scale={os_.scale}(期望 1)")
|
| 427 |
+
om = os_.matrix(2)
|
| 428 |
+
check("此时按 ÷1 解(真值 5.0 mN,若按 1000 会缩成 0.005)",
|
| 429 |
+
om is not None and abs(float(om[120, 120, 2]) - 5.0) < 1e-4,
|
| 430 |
+
f"中心 fz={None if om is None else float(om[120, 120, 2]):.4f}")
|
| 431 |
+
|
| 432 |
+
# ③ 只有 info.json(v1.3.x 之前的录制):回退仍要工作
|
| 433 |
+
legacy_path = make_synthetic_episode( # 不给 meta_scale = 无 meta 行
|
| 434 |
+
tmp, scale=100, name="synthetic_legacy_no_meta")
|
| 435 |
+
ls = mod.TactileEpisode(legacy_path).rigs[""]["left"]
|
| 436 |
+
check("无 meta 行 → 回退 info.json(老 episode 兼容)",
|
| 437 |
+
ls.scale == 100, f"scale={ls.scale}(期望 100,来自 info.json)")
|
| 438 |
+
lm = ls.matrix(2)
|
| 439 |
+
check("回退路径数值同样还原(真值 5.0 mN)",
|
| 440 |
+
lm is not None and abs(float(lm[120, 120, 2]) - 5.0) < 1e-4,
|
| 441 |
+
f"中心 fz={None if lm is None else float(lm[120, 120, 2]):.4f}")
|
| 442 |
+
|
| 443 |
+
# ④ 两处都没有 → 1(读取器返回空,调用链不崩)
|
| 444 |
+
nometa = os.path.join(tmp, "synthetic_no_features")
|
| 445 |
+
os.makedirs(os.path.join(nometa, "meta"), exist_ok=True)
|
| 446 |
+
os.makedirs(os.path.join(nometa, "data", "chunk-000"), exist_ok=True)
|
| 447 |
+
with open(os.path.join(nometa, "meta", "info.json"), "w",
|
| 448 |
+
encoding="utf-8") as fh:
|
| 449 |
+
json.dump({"fps": 30}, fh) # 老 episode:无 features 键
|
| 450 |
+
nopath = os.path.join(nometa, "data", "chunk-000", "e.parquet")
|
| 451 |
+
check("meta 行与 info.json 都没有 → 两个读者都返回空、不抛异常",
|
| 452 |
+
mod._read_episode_matrix_specs(nopath) == {}
|
| 453 |
+
and mod._read_info_features(nopath) == {})
|
| 454 |
+
|
| 455 |
print("[3] GUI 路径")
|
| 456 |
window = mod.DemoWindow()
|
| 457 |
window.show() # 离屏下 isVisible/isHidden 需先 show
|
|
|
|
| 501 |
app.processEvents()
|
| 502 |
check("关循环在尾帧停住",
|
| 503 |
window.idx == 11 and not window.timer.isActive())
|
| 504 |
+
|
| 505 |
+
print("[3b] 显示增益")
|
| 506 |
+
check("默认自适应且两侧都有增益",
|
| 507 |
+
window.chk_auto.isChecked()
|
| 508 |
+
and set(window._auto_gains) == {"left", "right"}
|
| 509 |
+
and not window.slider_gain.isEnabled(),
|
| 510 |
+
window.lbl_gain.text())
|
| 511 |
+
window.chk_auto.setChecked(False) # → toggled 信号走手动分支
|
| 512 |
+
app.processEvents()
|
| 513 |
+
check("关掉自适应 → 滑块可用、增益取自滑块",
|
| 514 |
+
window.slider_gain.isEnabled()
|
| 515 |
+
and abs(window._effective_gains()["left"] - window._gain) < 1e-6,
|
| 516 |
+
window.lbl_gain.text())
|
| 517 |
+
window.slider_gain.setValue(mod._gain_to_slider(50.0))
|
| 518 |
+
app.processEvents()
|
| 519 |
+
check("滑块拖到 ×50 = 主程序量程",
|
| 520 |
+
abs(window._gain - 50.0) < 0.6, f"×{window._gain:.1f}")
|
| 521 |
+
window.chk_auto.setChecked(True)
|
| 522 |
+
app.processEvents()
|
| 523 |
+
check("重新勾选自适应 → 增益回到按数据定标",
|
| 524 |
+
abs(window._effective_gains()["left"] - g_left) < 1e-6,
|
| 525 |
+
window.lbl_gain.text())
|
| 526 |
window.close()
|
| 527 |
|
| 528 |
print("[4] 目录加载")
|
collector/tools/tests/test_gripper_matrix_encoding.py
CHANGED
|
@@ -1,7 +1,14 @@
|
|
| 1 |
-
"""P4 力矩阵编码器单测:
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
lerobot_v3.quantize_force_matrix 语义一致,仅扩展到三力平面。
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
import os
|
| 7 |
import sys
|
|
@@ -43,6 +50,89 @@ def main():
|
|
| 43 |
assert not any(z), "zero matrix must stay zero"
|
| 44 |
print("PASS: 全零矩阵编码为全零")
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
print("PASS: 力矩阵编码器单测全部通过")
|
| 47 |
|
| 48 |
|
|
|
|
| 1 |
+
"""P4 力矩阵编码器单测:五档落盘规格。
|
| 2 |
|
| 3 |
+
int16(默认) 行差分 (250,250,3) 可逆 + 饱和截断 + 向零截断的精度损失
|
| 4 |
+
int16×10/100/1000 定标档:先 ×N 再 rint,解码 ÷N 还原,分辨率 1/N mN
|
| 5 |
+
float32 原值直存往返无损 + 元素类型为 float
|
| 6 |
+
|
| 7 |
+
编码函数在 ui/main_window.py(泵线程用),int16 分支与 online/ 参考实现
|
| 8 |
lerobot_v3.quantize_force_matrix 语义一致,仅扩展到三力平面。
|
| 9 |
+
|
| 10 |
+
★ 元素类型只区分「家族」:四档 int16 系都给 int,倍率看不出来。
|
| 11 |
+
writer / demo 靠 info.json features.scale 还原,本文件校验那条契约。
|
| 12 |
"""
|
| 13 |
import os
|
| 14 |
import sys
|
|
|
|
| 50 |
assert not any(z), "zero matrix must stay zero"
|
| 51 |
print("PASS: 全零矩阵编码为全零")
|
| 52 |
|
| 53 |
+
# ── int16 截断的精度损失(默认规格的代价,float32 规格存在的理由)──
|
| 54 |
+
fine = np.full((250, 250, 3), 0.9, np.float32) # 亚毫牛信号
|
| 55 |
+
dec = decode(encode_gripper_force_matrix(fine))
|
| 56 |
+
assert not dec.any(), "0.9 应被向零截断为 0"
|
| 57 |
+
print("PASS: int16 规格下 0.9 mN 整幅归零(亚毫牛信号丢失)")
|
| 58 |
+
|
| 59 |
+
mixed = np.zeros((250, 250, 3), np.float32)
|
| 60 |
+
mixed[10, 10, 2] = 5.75
|
| 61 |
+
got = decode(encode_gripper_force_matrix(mixed))[10, 10, 2]
|
| 62 |
+
assert got == 5, got
|
| 63 |
+
print(f"PASS: int16 规格下 5.75 → {int(got)}(小数位不可恢复)")
|
| 64 |
+
|
| 65 |
+
# ── 定标档:×10/×100/×1000 解码 ÷N 还原,精度随倍率提升 ──
|
| 66 |
+
# 0.9 mN 在 int16 档整幅归零;×10 应还原成 0.9(rint(9)=9 → ÷10)
|
| 67 |
+
for scale in (10, 100, 1000):
|
| 68 |
+
spec = f"int16x{scale}"
|
| 69 |
+
got = decode(encode_gripper_force_matrix(fine, spec)) \
|
| 70 |
+
.astype(np.float32) / np.float32(scale)
|
| 71 |
+
assert np.allclose(got, fine, atol=0.5 / scale), \
|
| 72 |
+
f"{spec} 应还原 0.9 mN(容差半个 LSB),得到 {got[0, 0, 0]}"
|
| 73 |
+
print("PASS: ×10/×100/×1000 定标档把 0.9 mN 还原(int16 档归零)")
|
| 74 |
+
|
| 75 |
+
# 5.75 mN:int16 档丢成 5;×10 存 58 → 5.8(rint 进整,误差 ≤0.05)
|
| 76 |
+
# 注意定标档用 rint 而非向零截断,所以是 5.8 不是 5.7
|
| 77 |
+
got10 = decode(encode_gripper_force_matrix(mixed, "int16x10")) \
|
| 78 |
+
.astype(np.float32) / np.float32(10)
|
| 79 |
+
assert abs(float(got10[10, 10, 2]) - 5.8) < 1e-6, got10[10, 10, 2]
|
| 80 |
+
print(f"PASS: ×10 档 5.75 → {float(got10[10, 10, 2]):.1f}(rint 进整,非截断)")
|
| 81 |
+
|
| 82 |
+
# 定标档的元素同样是 int(倍率分辨不出,只能靠 scale)
|
| 83 |
+
enc10 = encode_gripper_force_matrix(mixed, "int16x10")
|
| 84 |
+
assert isinstance(enc10[0], int), \
|
| 85 |
+
f"定标档元素应为 int,得到 {type(enc10[0])}"
|
| 86 |
+
|
| 87 |
+
# 定标档的饱和上限随倍率下降:±32767/倍率 mN(×1000 即 ±32.767 mN)
|
| 88 |
+
satm = np.zeros((250, 250, 3), np.float32)
|
| 89 |
+
satm[10, 10, 2] = 40.0 # 40 mN
|
| 90 |
+
q10 = decode(encode_gripper_force_matrix(satm, "int16x10"))
|
| 91 |
+
assert q10[10, 10, 2] == 400, q10[10, 10, 2] # 40×10=400,远未饱和
|
| 92 |
+
q1000 = decode(encode_gripper_force_matrix(satm, "int16x1000"))
|
| 93 |
+
assert q1000[10, 10, 2] == 32767, q1000[10, 10, 2] # 40×1000=40000 饱和
|
| 94 |
+
print("PASS: 定标档饱和上限随倍率下降(40 mN 在 ×1000 饱和、×10 不饱和)")
|
| 95 |
+
|
| 96 |
+
# ── float32 规格:往返无损、无饱和、元素类型是 float ──
|
| 97 |
+
enc32 = encode_gripper_force_matrix(fine, "float32")
|
| 98 |
+
assert len(enc32) == 250 * 250 * 3, len(enc32)
|
| 99 |
+
assert isinstance(enc32[0], float), \
|
| 100 |
+
f"float32 规格必须给 float 元素(writer 据此定型),得到 {type(enc32[0])}"
|
| 101 |
+
back = np.asarray(enc32, np.float32).reshape(250, 250, 3)
|
| 102 |
+
assert np.array_equal(back, fine), "float32 往返应逐位一致"
|
| 103 |
+
assert np.array_equal(back, np.asarray(fine.reshape(-1).tolist(),
|
| 104 |
+
np.float32).reshape(250, 250, 3))
|
| 105 |
+
print("PASS: float32 规格往返逐位无损,0.9 mN 保留")
|
| 106 |
+
|
| 107 |
+
# int16 规格的元素必须是 int(家族靠元素类型区分,不能靠数值巧合)
|
| 108 |
+
assert isinstance(enc[0], int), \
|
| 109 |
+
f"int16 规格必须给 int 元素,得到 {type(enc[0])}"
|
| 110 |
+
|
| 111 |
+
big = np.array([[[40000.0, -40000.0, 1.0]]], dtype=np.float32)
|
| 112 |
+
enc_big = encode_gripper_force_matrix(big, "float32")
|
| 113 |
+
assert enc_big[0] == 40000.0 and enc_big[1] == -40000.0, enc_big[:3]
|
| 114 |
+
print("PASS: float32 规格无 ±32767 饱和(40000 原样保留)")
|
| 115 |
+
|
| 116 |
+
assert np.array_equal(
|
| 117 |
+
np.asarray(encode_gripper_force_matrix(m, "float32"),
|
| 118 |
+
np.float32).reshape(250, 250, 3), m), \
|
| 119 |
+
"float32 规格对典型幅值也应逐位无损"
|
| 120 |
+
print("PASS: float32 规格对 ±3000 随机矩阵往返无损")
|
| 121 |
+
|
| 122 |
+
# ── 参数默认 = int16,且与历史契约逐位一致(既有录制的可复现性)��─
|
| 123 |
+
# 这是编码器签名的兼容默认,与工具栏默认档(settings 的 SPEC_DEFAULT)无关
|
| 124 |
+
assert encode_gripper_force_matrix(m) == encode_gripper_force_matrix(m, "int16")
|
| 125 |
+
print("PASS: 省略 spec 等于 int16 档(编码器兼容默认,非工具栏默认档)")
|
| 126 |
+
|
| 127 |
+
# 未知规格要显式报错,不能静默按某档处理
|
| 128 |
+
try:
|
| 129 |
+
encode_gripper_force_matrix(m, "int16x7")
|
| 130 |
+
except ValueError as exc:
|
| 131 |
+
assert "int16x7" in str(exc), exc
|
| 132 |
+
print("PASS: 未知规格被拒绝(ValueError)")
|
| 133 |
+
else:
|
| 134 |
+
raise AssertionError("未知规格应报错")
|
| 135 |
+
|
| 136 |
print("PASS: 力矩阵编码器单测全部通过")
|
| 137 |
|
| 138 |
|
collector/tools/tests/test_gripper_matrix_writer.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""力矩阵落盘规格(int16 / float32)在 writer 侧的契约自检:
|
| 4 |
+
|
| 5 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python \
|
| 6 |
+
tools/tests/test_gripper_matrix_writer.py
|
| 7 |
+
|
| 8 |
+
覆盖:
|
| 9 |
+
1. 元素类型定型:int 列表 → int16 行差分;float 列表 → float32 原值
|
| 10 |
+
2. parquet 列类型随规格(list<int16> / list<float32>),且能按规格反解
|
| 11 |
+
3. info.json features 的 dtype / encoding / scale 与规格一致
|
| 12 |
+
4. 录制中改规格 → 显式报错(不让 pyarrow 抛难懂的转换异常)
|
| 13 |
+
5. 空样本帧不定型(首帧为空也能在后续样本上定型)
|
| 14 |
+
6. 定标档(×10/×100/×1000):列类型仍是 int16、倍率靠 features.scale,
|
| 15 |
+
未登记时回退 1(历史 episode 就是未定标的,行为必须不变)
|
| 16 |
+
退出码 0 = 全部通过。
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import shutil
|
| 24 |
+
import sys
|
| 25 |
+
import tempfile
|
| 26 |
+
|
| 27 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
import pyarrow.parquet as pq
|
| 32 |
+
|
| 33 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 34 |
+
os.path.abspath(__file__))))
|
| 35 |
+
sys.path.insert(0, REPO_ROOT)
|
| 36 |
+
|
| 37 |
+
from core.egodata_writer import ( # noqa: E402
|
| 38 |
+
EgoDataWriter, _EPISODE_SCHEMA, _read_episode_rows)
|
| 39 |
+
from core.helpers import pooled_episodes_path # noqa: E402
|
| 40 |
+
from ui.main_window import encode_gripper_force_matrix # noqa: E402
|
| 41 |
+
|
| 42 |
+
MATRIX_KEY = "gripper_left_force_matrix"
|
| 43 |
+
COLUMN = f"observation.{MATRIX_KEY}"
|
| 44 |
+
|
| 45 |
+
_FAILS: list[str] = []
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def check(name: str, cond: bool, detail: str = ""):
|
| 49 |
+
tag = "PASS" if cond else "FAIL"
|
| 50 |
+
print(f" [{tag}] {name}" + (f" — {detail}" if detail else ""))
|
| 51 |
+
if not cond:
|
| 52 |
+
_FAILS.append(name)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def contact_matrix(value: float) -> np.ndarray:
|
| 56 |
+
"""250×250×3:中心 30×30 接触区,fz=value,fx=value/4。"""
|
| 57 |
+
m = np.zeros((250, 250, 3), np.float32)
|
| 58 |
+
m[105:135, 105:135, 2] = value
|
| 59 |
+
m[105:135, 105:135, 0] = value * 0.25
|
| 60 |
+
return m
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def decode_int16(flat) -> np.ndarray:
|
| 64 |
+
arr = np.asarray(flat, np.int16).reshape(-1, 750)
|
| 65 |
+
return (np.cumsum(arr.astype(np.int32), axis=1).astype(np.int16)
|
| 66 |
+
.reshape(250, 250, 3))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def build_writer(task_dir: str, matrix_lists, n_frames: int) -> EgoDataWriter:
|
| 70 |
+
"""喂 n_frames 帧(matrix_lists[i] 为第 i 帧的编码值,None=不写该帧)。"""
|
| 71 |
+
writer = EgoDataWriter()
|
| 72 |
+
writer._task_dir = task_dir
|
| 73 |
+
writer._episode_index = 0
|
| 74 |
+
for i in range(n_frames):
|
| 75 |
+
gripper = {}
|
| 76 |
+
if matrix_lists[i] is not None:
|
| 77 |
+
gripper[MATRIX_KEY] = matrix_lists[i]
|
| 78 |
+
writer.write_frame_row(i, i / 30.0, gripper=gripper)
|
| 79 |
+
return writer
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def main() -> int:
|
| 83 |
+
tmp = tempfile.mkdtemp(prefix="force_matrix_writer_")
|
| 84 |
+
try:
|
| 85 |
+
print("[1] int16 规格(元素为 int)")
|
| 86 |
+
ref = contact_matrix(5.75)
|
| 87 |
+
int_rows = [encode_gripper_force_matrix(ref)]
|
| 88 |
+
int_rows += [encode_gripper_force_matrix(contact_matrix(3.0 + i))
|
| 89 |
+
for i in range(1, 6)]
|
| 90 |
+
w = build_writer(os.path.join(tmp, "i16"), int_rows, 5)
|
| 91 |
+
check("元素类型判定为 int16", w._matrix_dtype.get(MATRIX_KEY) == "int16",
|
| 92 |
+
str(w._matrix_dtype))
|
| 93 |
+
w._write_data_parquet()
|
| 94 |
+
schema = pq.read_schema(
|
| 95 |
+
os.path.join(tmp, "i16", "data", "chunk-000", "episode-000.parquet"))
|
| 96 |
+
check("parquet 列类型 = list<int16>",
|
| 97 |
+
schema.field(COLUMN).type == pa.list_(pa.int16()),
|
| 98 |
+
str(schema.field(COLUMN).type))
|
| 99 |
+
got = decode_int16(pq.read_table(
|
| 100 |
+
os.path.join(tmp, "i16", "data", "chunk-000", "episode-000.parquet"),
|
| 101 |
+
columns=[COLUMN]).column(COLUMN).to_pylist()[0])
|
| 102 |
+
check("int16 列反解 = 截断后的矩阵",
|
| 103 |
+
np.array_equal(got, ref.astype(np.int16)),
|
| 104 |
+
f"中心 fz={int(got[120, 120, 2])}(期望 5,5.75 被截断)")
|
| 105 |
+
w._write_info_json()
|
| 106 |
+
feats = json.load(open(os.path.join(tmp, "i16", "meta", "info.json"),
|
| 107 |
+
encoding="utf-8"))["features"]
|
| 108 |
+
check("features dtype=int16 / encoding=row_diff_quantized",
|
| 109 |
+
feats[COLUMN]["dtype"] == "int16"
|
| 110 |
+
and feats[COLUMN]["encoding"] == "row_diff_quantized",
|
| 111 |
+
str(feats[COLUMN]))
|
| 112 |
+
check("features shape=[250,250,3]",
|
| 113 |
+
feats[COLUMN]["shape"] == [250, 250, 3],
|
| 114 |
+
str(feats[COLUMN]["shape"]))
|
| 115 |
+
|
| 116 |
+
check("int16 档 features.scale=1(未定标)",
|
| 117 |
+
feats[COLUMN]["scale"] == 1, str(feats[COLUMN].get("scale")))
|
| 118 |
+
|
| 119 |
+
print("[2] float32 规格(元素为 float)")
|
| 120 |
+
f_rows = [encode_gripper_force_matrix(ref, "float32")]
|
| 121 |
+
f_rows += [encode_gripper_force_matrix(contact_matrix(3.375 + i),
|
| 122 |
+
"float32")
|
| 123 |
+
for i in range(1, 6)]
|
| 124 |
+
w2 = build_writer(os.path.join(tmp, "f32"), f_rows, 5)
|
| 125 |
+
check("元素类型判定为 float32",
|
| 126 |
+
w2._matrix_dtype.get(MATRIX_KEY) == "float32",
|
| 127 |
+
str(w2._matrix_dtype))
|
| 128 |
+
w2._write_data_parquet()
|
| 129 |
+
fpath = os.path.join(tmp, "f32", "data", "chunk-000", "episode-000.parquet")
|
| 130 |
+
schema2 = pq.read_schema(fpath)
|
| 131 |
+
check("parquet 列类型 = list<float32>",
|
| 132 |
+
schema2.field(COLUMN).type == pa.list_(pa.float32()),
|
| 133 |
+
str(schema2.field(COLUMN).type))
|
| 134 |
+
back = np.asarray(
|
| 135 |
+
pq.read_table(fpath, columns=[COLUMN]).column(COLUMN).to_pylist()[0],
|
| 136 |
+
np.float32).reshape(250, 250, 3)
|
| 137 |
+
check("float32 列往返逐位无损",
|
| 138 |
+
np.array_equal(back, ref),
|
| 139 |
+
f"中心 fz={float(back[120, 120, 2]):.4f}(期望 5.7500)")
|
| 140 |
+
check("float32 亚毫牛小数位保留",
|
| 141 |
+
abs(float(back[120, 120, 0]) - 1.4375) < 1e-6,
|
| 142 |
+
f"中心 fx={float(back[120, 120, 0]):.4f}(期望 1.4375)")
|
| 143 |
+
w2._write_info_json()
|
| 144 |
+
feats2 = json.load(open(os.path.join(tmp, "f32", "meta", "info.json"),
|
| 145 |
+
encoding="utf-8"))["features"]
|
| 146 |
+
check("features dtype=float32 / encoding=row_flat_raw",
|
| 147 |
+
feats2[COLUMN]["dtype"] == "float32"
|
| 148 |
+
and feats2[COLUMN]["encoding"] == "row_flat_raw",
|
| 149 |
+
str(feats2[COLUMN]))
|
| 150 |
+
check("float32 档 features.scale=1(无定标)",
|
| 151 |
+
feats2[COLUMN]["scale"] == 1, str(feats2[COLUMN].get("scale")))
|
| 152 |
+
|
| 153 |
+
print("[3] 录制中改规格 → 显式报错")
|
| 154 |
+
w3 = build_writer(os.path.join(tmp, "mix"), [int_rows[0]], 1)
|
| 155 |
+
raised = None
|
| 156 |
+
try:
|
| 157 |
+
w3.write_frame_row(1, 0.5, gripper={
|
| 158 |
+
MATRIX_KEY: f_rows[0]})
|
| 159 |
+
except ValueError as exc:
|
| 160 |
+
raised = exc
|
| 161 |
+
check("同一列混型被拒绝(ValueError)", raised is not None,
|
| 162 |
+
str(raised)[:70] if raised else "未报错")
|
| 163 |
+
check("报错信息点明列名与两种规格",
|
| 164 |
+
raised is not None and MATRIX_KEY in str(raised)
|
| 165 |
+
and "int16" in str(raised) and "float32" in str(raised))
|
| 166 |
+
|
| 167 |
+
print("[4] 空样本不定型")
|
| 168 |
+
w4 = EgoDataWriter()
|
| 169 |
+
w4._task_dir = os.path.join(tmp, "empty")
|
| 170 |
+
w4._episode_index = 0
|
| 171 |
+
w4.write_frame_row(0, 0.0, gripper={MATRIX_KEY: []})
|
| 172 |
+
check("空样本首帧不写规格", w4._matrix_dtype.get(MATRIX_KEY) is None,
|
| 173 |
+
str(w4._matrix_dtype))
|
| 174 |
+
w4.write_frame_row(1, 1 / 30.0,
|
| 175 |
+
gripper={MATRIX_KEY: f_rows[0]})
|
| 176 |
+
check("后续样本到来时定型",
|
| 177 |
+
w4._matrix_dtype.get(MATRIX_KEY) == "float32",
|
| 178 |
+
str(w4._matrix_dtype))
|
| 179 |
+
|
| 180 |
+
print("[5] 两种规格互不干扰(双夹爪各一侧不同规格)")
|
| 181 |
+
w5 = EgoDataWriter()
|
| 182 |
+
w5._task_dir = os.path.join(tmp, "dual")
|
| 183 |
+
w5._episode_index = 0
|
| 184 |
+
w5.write_frame_row(0, 0.0, gripper={
|
| 185 |
+
"gripper_left_force_matrix": int_rows[0],
|
| 186 |
+
"gripper_right_force_matrix":
|
| 187 |
+
encode_gripper_force_matrix(contact_matrix(2.5), "float32"),
|
| 188 |
+
})
|
| 189 |
+
check("左右两侧各自定型",
|
| 190 |
+
w5._matrix_dtype.get("gripper_left_force_matrix") == "int16"
|
| 191 |
+
and w5._matrix_dtype.get("gripper_right_force_matrix") == "float32",
|
| 192 |
+
str(w5._matrix_dtype))
|
| 193 |
+
|
| 194 |
+
print("[6] 定标档 ×10/×100/×1000:列类型仍是 int16,倍率走 features.scale")
|
| 195 |
+
for scale in (10, 100, 1000):
|
| 196 |
+
spec = f"int16x{scale}"
|
| 197 |
+
sdir = os.path.join(tmp, spec)
|
| 198 |
+
w6 = EgoDataWriter()
|
| 199 |
+
w6._task_dir = sdir
|
| 200 |
+
w6._episode_index = 0
|
| 201 |
+
ref6 = contact_matrix(5.75)
|
| 202 |
+
rows6 = [encode_gripper_force_matrix(ref6, spec)]
|
| 203 |
+
rows6 += [encode_gripper_force_matrix(contact_matrix(3.75 + i), spec)
|
| 204 |
+
for i in range(1, 4)]
|
| 205 |
+
# 采集侧在录制开始时登记倍率(pipeline.set_force_matrix_spec →
|
| 206 |
+
# writer.set_force_matrix_spec),writer 自己推不出来
|
| 207 |
+
w6.set_force_matrix_spec(MATRIX_KEY, spec)
|
| 208 |
+
for i, enc in enumerate(rows6):
|
| 209 |
+
w6.write_frame_row(i, i / 30.0, gripper={MATRIX_KEY: enc})
|
| 210 |
+
check(f"{spec} 落盘家族仍是 int16(倍率看不出)",
|
| 211 |
+
w6._matrix_dtype.get(MATRIX_KEY) == "int16",
|
| 212 |
+
str(w6._matrix_dtype))
|
| 213 |
+
w6._write_data_parquet()
|
| 214 |
+
spath = os.path.join(sdir, "data", "chunk-000", "episode-000.parquet")
|
| 215 |
+
stype = pq.read_schema(spath).field(COLUMN).type
|
| 216 |
+
check(f"{spec} parquet 列类型 = list<int16>",
|
| 217 |
+
stype == pa.list_(pa.int16()), str(stype))
|
| 218 |
+
got6 = decode_int16(pq.read_table(
|
| 219 |
+
spath, columns=[COLUMN]).column(COLUMN).to_pylist()[0]
|
| 220 |
+
).astype(np.float32) / np.float32(scale)
|
| 221 |
+
# 期望值 = 编码端口径(rint 半偶入)÷scale,而不是「真值 ±半 LSB」:
|
| 222 |
+
# 5.75 在 ×10 档正好落在半格上 → rint 到 58 → 5.8,误差恰为半个 LSB
|
| 223 |
+
expect = float(np.rint(np.float32(5.75) * np.float32(scale))) / scale
|
| 224 |
+
check(f"{spec} 解码÷{scale} 还原 5.75 mN(int16 档会丢成 5)",
|
| 225 |
+
abs(float(got6[120, 120, 2]) - expect) < 1e-4,
|
| 226 |
+
f"中心 fz={float(got6[120, 120, 2]):.4f}"
|
| 227 |
+
f"(期望 {expect:.4f},真值 5.75)")
|
| 228 |
+
w6._write_info_json()
|
| 229 |
+
f6 = json.load(open(os.path.join(sdir, "meta", "info.json"),
|
| 230 |
+
encoding="utf-8"))["features"][COLUMN]
|
| 231 |
+
check(f"{spec} features.scale={scale}",
|
| 232 |
+
f6["scale"] == scale, str(f6))
|
| 233 |
+
check(f"{spec} features dtype 仍报 int16",
|
| 234 |
+
f6["dtype"] == "int16" and f6["encoding"] == "row_diff_quantized",
|
| 235 |
+
str(f6))
|
| 236 |
+
|
| 237 |
+
print("[6b] 未登记倍率 → 回退 1(历史 episode 行为不变)")
|
| 238 |
+
w7 = build_writer(os.path.join(tmp, "noscale"), int_rows[:2], 2)
|
| 239 |
+
w7._write_data_parquet()
|
| 240 |
+
w7._write_info_json()
|
| 241 |
+
f7 = json.load(open(os.path.join(tmp, "noscale", "meta", "info.json"),
|
| 242 |
+
encoding="utf-8"))["features"][COLUMN]
|
| 243 |
+
check("未登记 scale 默认 1", f7["scale"] == 1, str(f7))
|
| 244 |
+
|
| 245 |
+
print("[7] meta/episodes 行带倍率:同任务换档,前一段不被后一段覆盖")
|
| 246 |
+
# 复现现场:同一任务连录 ×10 与 float32 两段。info.json 是任务级、
|
| 247 |
+
# 值以最新 episode 为准 → 第一段的倍率会被顶成 1;每段一行的
|
| 248 |
+
# force_matrix_specs 必须各记各的。
|
| 249 |
+
task = os.path.join(tmp, "pooled")
|
| 250 |
+
# episode_index 是 1 起的全局序号(episode_chunk_file 里 -1 后取整),
|
| 251 |
+
# 传 0 会和 1 撞到同一个文件上
|
| 252 |
+
for index, spec in ((1, "int16x10"), (2, "float32")):
|
| 253 |
+
w8 = EgoDataWriter()
|
| 254 |
+
w8._task_dir = task
|
| 255 |
+
w8._episode_index = index
|
| 256 |
+
w8.set_force_matrix_spec(MATRIX_KEY, spec)
|
| 257 |
+
w8.write_frame_row(0, 0.0, gripper={
|
| 258 |
+
MATRIX_KEY: encode_gripper_force_matrix(contact_matrix(5.75),
|
| 259 |
+
spec)})
|
| 260 |
+
w8._write_data_parquet()
|
| 261 |
+
w8._append_episode_row()
|
| 262 |
+
w8._write_info_json() # 每次录制结束都重写 → 后者顶前者
|
| 263 |
+
|
| 264 |
+
rows = {}
|
| 265 |
+
for index in (1, 2):
|
| 266 |
+
path = pooled_episodes_path(task, index)
|
| 267 |
+
got = _read_episode_rows(path)
|
| 268 |
+
check(f"第 {index} 段 meta 行数 = 1", len(got) == 1, str(len(got)))
|
| 269 |
+
check(f"第 {index} 段 meta 行的 episode_index = {index}",
|
| 270 |
+
got and got[0]["episode_index"] == index,
|
| 271 |
+
str(got[0].get("episode_index")) if got else "无行")
|
| 272 |
+
rows[index] = got[0]
|
| 273 |
+
check("meta 行 schema 与 _EPISODE_SCHEMA 一致(列齐)",
|
| 274 |
+
pq.read_schema(pooled_episodes_path(task, 1)) == _EPISODE_SCHEMA)
|
| 275 |
+
|
| 276 |
+
specs0 = json.loads(rows[1]["force_matrix_specs"])
|
| 277 |
+
specs1 = json.loads(rows[2]["force_matrix_specs"])
|
| 278 |
+
check("第 1 段(×10)meta 行记 scale=10",
|
| 279 |
+
specs0[COLUMN]["scale"] == 10, str(specs0.get(COLUMN)))
|
| 280 |
+
check("第 2 段(float32)meta 行记 scale=1 且 dtype=float32",
|
| 281 |
+
specs1[COLUMN]["scale"] == 1
|
| 282 |
+
and specs1[COLUMN]["dtype"] == "float32"
|
| 283 |
+
and specs1[COLUMN]["encoding"] == "row_flat_raw",
|
| 284 |
+
str(specs1.get(COLUMN)))
|
| 285 |
+
check("规格描述四项齐全(dtype/shape/encoding/scale)",
|
| 286 |
+
set(specs0[COLUMN]) == {"dtype", "shape", "encoding", "scale"}
|
| 287 |
+
and specs0[COLUMN]["shape"] == [250, 250, 3],
|
| 288 |
+
str(specs0[COLUMN]))
|
| 289 |
+
|
| 290 |
+
info_scale = json.load(open(os.path.join(task, "meta", "info.json"),
|
| 291 |
+
encoding="utf-8"))["features"][COLUMN]["scale"]
|
| 292 |
+
check("info.json 确实被后一段顶成 1(这就是必须另存每段的原因)",
|
| 293 |
+
info_scale == 1,
|
| 294 |
+
f"info.json scale={info_scale}(任务级、值以最新 episode 为准)")
|
| 295 |
+
check("两段 meta 行没被互相顶掉(10 与 1 各自保留)",
|
| 296 |
+
specs0[COLUMN]["scale"] == 10 and specs1[COLUMN]["scale"] == 1)
|
| 297 |
+
|
| 298 |
+
# 追加第三段(不带力矩阵列)不得把前两段的规格弄丢
|
| 299 |
+
w9 = EgoDataWriter()
|
| 300 |
+
w9._task_dir = task
|
| 301 |
+
w9._episode_index = 3
|
| 302 |
+
w9.write_frame_row(0, 0.0, gripper={})
|
| 303 |
+
w9._write_data_parquet()
|
| 304 |
+
w9._append_episode_row()
|
| 305 |
+
check("无夹爪列的段写空规格 {}(不是漏列)",
|
| 306 |
+
_read_episode_rows(pooled_episodes_path(task, 3))[0][
|
| 307 |
+
"force_matrix_specs"] == "{}")
|
| 308 |
+
again = _read_episode_rows(pooled_episodes_path(task, 1))
|
| 309 |
+
check("追加新段后旧段 meta 行原样保留",
|
| 310 |
+
len(again) == 1
|
| 311 |
+
and json.loads(again[0]["force_matrix_specs"]) == specs0,
|
| 312 |
+
str(again[0].get("force_matrix_specs")))
|
| 313 |
+
finally:
|
| 314 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 315 |
+
|
| 316 |
+
print()
|
| 317 |
+
if _FAILS:
|
| 318 |
+
print(f"FAILED: {len(_FAILS)} 项 — {_FAILS}")
|
| 319 |
+
return 1
|
| 320 |
+
print("ALL PASS")
|
| 321 |
+
return 0
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
if __name__ == "__main__":
|
| 325 |
+
sys.exit(main())
|
collector/tools/tests/test_gripper_slam_columns.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""SLAM 落盘契约自检:只落 slam_trajectory,不再落 slam_pose(2026-09-10 定案)。
|
| 4 |
+
|
| 5 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python \
|
| 6 |
+
tools/tests/test_gripper_slam_columns.py
|
| 7 |
+
|
| 8 |
+
背景:slam_pose 是「每帧一个位姿」的定长 list<float32>[7] 状态列,但位姿流
|
| 9 |
+
是 20/20/60ms 突发、parquet 行是 1/30s 均匀网格 —— 实测 26.5% 的行拿不到
|
| 10 |
+
位姿被填成 [0]*7,下游会把零当真实位姿读。同一回调里已经写入的
|
| 11 |
+
slam_trajectory(变长、每点带真实时间戳)信息严格更多,故停止落 slam_pose。
|
| 12 |
+
|
| 13 |
+
覆盖:
|
| 14 |
+
1. 喂 slam_pose / gripper_2_slam_pose → 静默忽略:不建列、不写 features
|
| 15 |
+
2. slam_trajectory → 列存在、类型 list<float64>、空行是 []、features 带
|
| 16 |
+
encoding=flat_points_8_txyz_qxyzw、点值逐位往返
|
| 17 |
+
3. 双 rig 前缀命名空间互不干扰
|
| 18 |
+
4. 删分支后 state / force / force_matrix 仍各按原类型落盘(没被 else 误吞)
|
| 19 |
+
5. 全空 episode(一帧夹爪数据都没有)不建任何夹爪列,且不抛异常
|
| 20 |
+
退出码 0 = 全部通过。
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import shutil
|
| 28 |
+
import sys
|
| 29 |
+
import tempfile
|
| 30 |
+
|
| 31 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 32 |
+
|
| 33 |
+
import pyarrow as pa
|
| 34 |
+
import pyarrow.parquet as pq
|
| 35 |
+
|
| 36 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 37 |
+
os.path.abspath(__file__))))
|
| 38 |
+
sys.path.insert(0, REPO_ROOT)
|
| 39 |
+
|
| 40 |
+
from core.egodata_writer import EgoDataWriter # noqa: E402
|
| 41 |
+
|
| 42 |
+
POSE7 = [1.5, -2.25, 0.125, 0.0, 0.0, 0.0, 1.0]
|
| 43 |
+
# 一个双点窗口:[t,x,y,z,qx,qy,qz,qw] × 2
|
| 44 |
+
TRAJ = [10.0, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 1.0,
|
| 45 |
+
10.02, 1.1, 2.1, 3.1, 0.0, 0.0, 0.0, 1.0]
|
| 46 |
+
|
| 47 |
+
_FAILS: list[str] = []
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def check(name: str, cond: bool, detail: str = ""):
|
| 51 |
+
tag = "PASS" if cond else "FAIL"
|
| 52 |
+
print(f" [{tag}] {name}" + (f" — {detail}" if detail else ""))
|
| 53 |
+
if not cond:
|
| 54 |
+
_FAILS.append(name)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def build(task_dir: str, frames) -> EgoDataWriter:
|
| 58 |
+
"""frames[i] = 第 i 帧的 gripper dict(None = 该帧不传 gripper)。"""
|
| 59 |
+
writer = EgoDataWriter()
|
| 60 |
+
writer._task_dir = task_dir
|
| 61 |
+
writer._episode_index = 0
|
| 62 |
+
for i, gripper in enumerate(frames):
|
| 63 |
+
writer.write_frame_row(i, i / 30.0, gripper=gripper or {})
|
| 64 |
+
return writer
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read_schema(task_dir: str):
|
| 68 |
+
return pq.read_schema(
|
| 69 |
+
os.path.join(task_dir, "data", "chunk-000", "episode-000.parquet"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def read_col(task_dir: str, column: str):
|
| 73 |
+
return pq.read_table(
|
| 74 |
+
os.path.join(task_dir, "data", "chunk-000", "episode-000.parquet"),
|
| 75 |
+
columns=[column]).column(column).to_pylist()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def read_features(task_dir: str) -> dict:
|
| 79 |
+
path = os.path.join(task_dir, "meta", "info.json")
|
| 80 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 81 |
+
return json.load(f)["features"]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def main() -> int:
|
| 85 |
+
tmp = tempfile.mkdtemp(prefix="slam_columns_")
|
| 86 |
+
try:
|
| 87 |
+
print("[1] slam_pose 已停落:静默忽略,不建列也不写 features")
|
| 88 |
+
# 复现历史写入端:即便某处仍在喂 slam_pose 键,也不该落盘
|
| 89 |
+
w = build(os.path.join(tmp, "nopose"), [
|
| 90 |
+
{"slam_pose": POSE7, "gripper_2_slam_pose": POSE7},
|
| 91 |
+
{"slam_pose": POSE7},
|
| 92 |
+
{}, # 全空帧也不能炸
|
| 93 |
+
])
|
| 94 |
+
check("slam_pose 未进 _present_gripper",
|
| 95 |
+
"slam_pose" not in w._present_gripper
|
| 96 |
+
and "gripper_2_slam_pose" not in w._present_gripper,
|
| 97 |
+
str(sorted(w._present_gripper)))
|
| 98 |
+
w._write_data_parquet()
|
| 99 |
+
w._write_info_json()
|
| 100 |
+
schema = read_schema(os.path.join(tmp, "nopose"))
|
| 101 |
+
check("parquet 无 observation.slam_pose 列",
|
| 102 |
+
schema.get_field_index("observation.slam_pose") < 0,
|
| 103 |
+
str(schema.names))
|
| 104 |
+
check("parquet 无 observation.gripper_2_slam_pose 列",
|
| 105 |
+
schema.get_field_index("observation.gripper_2_slam_pose") < 0)
|
| 106 |
+
feats = read_features(os.path.join(tmp, "nopose"))
|
| 107 |
+
check("features 无 observation.slam_pose",
|
| 108 |
+
"observation.slam_pose" not in feats, str(sorted(feats)))
|
| 109 |
+
check("features 无 observation.gripper_2_slam_pose",
|
| 110 |
+
"observation.gripper_2_slam_pose" not in feats)
|
| 111 |
+
|
| 112 |
+
print("[2] slam_trajectory 是唯一 SLAM 落盘形态")
|
| 113 |
+
w2 = build(os.path.join(tmp, "traj"), [
|
| 114 |
+
{"slam_trajectory": TRAJ},
|
| 115 |
+
{}, # 空窗口 → 该行 []
|
| 116 |
+
{"slam_trajectory": TRAJ[:8]}, # 单点窗口
|
| 117 |
+
])
|
| 118 |
+
w2._write_data_parquet()
|
| 119 |
+
w2._write_info_json()
|
| 120 |
+
col = "observation.slam_trajectory"
|
| 121 |
+
schema2 = read_schema(os.path.join(tmp, "traj"))
|
| 122 |
+
check("列类型 = list<float64>",
|
| 123 |
+
schema2.field(col).type == pa.list_(pa.float64()),
|
| 124 |
+
str(schema2.field(col).type))
|
| 125 |
+
got = read_col(os.path.join(tmp, "traj"), col)
|
| 126 |
+
check("行�� = 3", len(got) == 3, str(len(got)))
|
| 127 |
+
check("多点点值逐位往返", got[0] == TRAJ, str(got[0]))
|
| 128 |
+
check("无样本帧是 [] 而不是 [0.0]*8", got[1] == [], str(got[1]))
|
| 129 |
+
check("单点窗口 = 8 值", got[2] == TRAJ[:8], str(got[2]))
|
| 130 |
+
feats2 = read_features(os.path.join(tmp, "traj"))[col]
|
| 131 |
+
check("features dtype=float64 / shape=[8]",
|
| 132 |
+
feats2["dtype"] == "float64" and feats2["shape"] == [8],
|
| 133 |
+
str(feats2))
|
| 134 |
+
check("features encoding=flat_points_8_txyz_qxyzw",
|
| 135 |
+
feats2.get("encoding") == "flat_points_8_txyz_qxyzw", str(feats2))
|
| 136 |
+
|
| 137 |
+
print("[3] 双 rig 前缀命名空间互不干扰")
|
| 138 |
+
w3 = build(os.path.join(tmp, "dual"), [
|
| 139 |
+
{"slam_trajectory": TRAJ,
|
| 140 |
+
"gripper_2_slam_trajectory": TRAJ[:8]},
|
| 141 |
+
])
|
| 142 |
+
w3._write_data_parquet()
|
| 143 |
+
w3._write_info_json()
|
| 144 |
+
check("rig1 旧键与 rig2 前缀键各建一列",
|
| 145 |
+
read_col(os.path.join(tmp, "dual"),
|
| 146 |
+
"observation.slam_trajectory")[0] == TRAJ
|
| 147 |
+
and read_col(os.path.join(tmp, "dual"),
|
| 148 |
+
"observation.gripper_2_slam_trajectory")[0]
|
| 149 |
+
== TRAJ[:8])
|
| 150 |
+
check("rig2 键也在 features 里",
|
| 151 |
+
"observation.gripper_2_slam_trajectory"
|
| 152 |
+
in read_features(os.path.join(tmp, "dual")))
|
| 153 |
+
|
| 154 |
+
print("[4] 删分支后 state / force / matrix 未被 else 误吞")
|
| 155 |
+
w4 = build(os.path.join(tmp, "rest"), [
|
| 156 |
+
{"gripper_state": [42.0, 1.0, 3.5],
|
| 157 |
+
"gripper_left_force": [1.0, -2.0, 3.0],
|
| 158 |
+
"gripper_left_force_matrix": [5] * 8},
|
| 159 |
+
])
|
| 160 |
+
w4._write_data_parquet()
|
| 161 |
+
w4._write_info_json()
|
| 162 |
+
schema4 = read_schema(os.path.join(tmp, "rest"))
|
| 163 |
+
check("gripper_state 仍是 list<float32,3>",
|
| 164 |
+
schema4.field("observation.gripper_state").type
|
| 165 |
+
== pa.list_(pa.float32(), 3),
|
| 166 |
+
str(schema4.field("observation.gripper_state").type))
|
| 167 |
+
check("gripper_left_force 仍是 list<float32,3>",
|
| 168 |
+
schema4.field("observation.gripper_left_force").type
|
| 169 |
+
== pa.list_(pa.float32(), 3))
|
| 170 |
+
check("gripper_left_force_matrix 仍是 list<int16>(元素为 int)",
|
| 171 |
+
schema4.field("observation.gripper_left_force_matrix").type
|
| 172 |
+
== pa.list_(pa.int16()),
|
| 173 |
+
str(schema4.field(
|
| 174 |
+
"observation.gripper_left_force_matrix").type))
|
| 175 |
+
check("缺失行的 state/force 仍补 [0.0]*3(契约未变)",
|
| 176 |
+
read_col(os.path.join(tmp, "rest"),
|
| 177 |
+
"observation.gripper_state") == [[42.0, 1.0, 3.5]])
|
| 178 |
+
feats4 = read_features(os.path.join(tmp, "rest"))
|
| 179 |
+
check("三个键都还在 features 里",
|
| 180 |
+
all(f"observation.{k}" in feats4 for k in
|
| 181 |
+
("gripper_state", "gripper_left_force",
|
| 182 |
+
"gripper_left_force_matrix")),
|
| 183 |
+
str(sorted(feats4)))
|
| 184 |
+
|
| 185 |
+
print("[5] 全空 episode 不建任何夹爪列")
|
| 186 |
+
w5 = build(os.path.join(tmp, "none"), [{}, {}])
|
| 187 |
+
w5._write_data_parquet()
|
| 188 |
+
w5._write_info_json()
|
| 189 |
+
schema5 = read_schema(os.path.join(tmp, "none"))
|
| 190 |
+
check("无 observation.slam_* 列",
|
| 191 |
+
not [n for n in schema5.names if "slam_" in n],
|
| 192 |
+
str([n for n in schema5.names if "slam_" in n]))
|
| 193 |
+
check("features 无任何 slam 键",
|
| 194 |
+
not [k for k in read_features(os.path.join(tmp, "none"))
|
| 195 |
+
if "slam_" in k])
|
| 196 |
+
finally:
|
| 197 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 198 |
+
|
| 199 |
+
print()
|
| 200 |
+
if _FAILS:
|
| 201 |
+
print(f"FAILED: {len(_FAILS)} 项 — {_FAILS}")
|
| 202 |
+
return 1
|
| 203 |
+
print("ALL PASS")
|
| 204 |
+
return 0
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
sys.exit(main())
|
collector/tools/tests/test_repair_force_matrix_scale.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""repair_force_matrix_scale 的推断逻辑自检(无 pytorch/Qt 依赖,直接运行):
|
| 4 |
+
|
| 5 |
+
venv/bin/python tools/tests/test_repair_force_matrix_scale.py
|
| 6 |
+
|
| 7 |
+
覆盖:
|
| 8 |
+
1. 四个档位都判得出:float32 / int16×10 / int16×1000 → 实测比值;未定标
|
| 9 |
+
int16(逐点向零截断)→ 和明显小于 1 → 判 ×1
|
| 10 |
+
2. 判不出的情形一律不写:无 force 列可比对、近零帧不算数、有效帧不足
|
| 11 |
+
3. 补写只动 meta 行:data parquet 逐字节不变
|
| 12 |
+
4. 已带倍率的段不重推(录制端写下的值是事实,推断只是补救手段)
|
| 13 |
+
|
| 14 |
+
判据本身(实测比值定档)有测试兜着,是因为这条逻辑一旦判错就是静默
|
| 15 |
+
放大/缩小 N 倍 —— 数值看着"正常",只有和图对比才看得出来。
|
| 16 |
+
退出码 0 = 全部通过。
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import importlib.util
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import shutil
|
| 25 |
+
import sys
|
| 26 |
+
import tempfile
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pyarrow as pa
|
| 30 |
+
import pyarrow.parquet as pq
|
| 31 |
+
|
| 32 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 33 |
+
os.path.abspath(__file__))))
|
| 34 |
+
sys.path.insert(0, REPO_ROOT)
|
| 35 |
+
|
| 36 |
+
from core.egodata_writer import _episode_rows_table # noqa: E402
|
| 37 |
+
from core.helpers import ( # noqa: E402
|
| 38 |
+
pooled_data_parquet_path, pooled_episodes_path)
|
| 39 |
+
|
| 40 |
+
COLUMN = "observation.gripper_left_force_matrix"
|
| 41 |
+
FORCE_COLUMN = "observation.gripper_left_force"
|
| 42 |
+
SIDE = 30 # 接触方块边长 → 900 个受力点
|
| 43 |
+
VALUE = 5.75 # 真值 mN;未定标 int16 档会被截成 5
|
| 44 |
+
N_FRAMES = 8 # ≥ MIN_FRAMES(5)
|
| 45 |
+
|
| 46 |
+
_FAILS: list[str] = []
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def check(name: str, cond: bool, detail: str = ""):
|
| 50 |
+
tag = "PASS" if cond else "FAIL"
|
| 51 |
+
print(f" [{tag}] {name}" + (f" — {detail}" if detail else ""))
|
| 52 |
+
if not cond:
|
| 53 |
+
_FAILS.append(name)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def load_repair_module():
|
| 57 |
+
path = os.path.join(REPO_ROOT, "scripts", "repair_force_matrix_scale.py")
|
| 58 |
+
spec = importlib.util.spec_from_file_location("repair_force_matrix_scale",
|
| 59 |
+
path)
|
| 60 |
+
module = importlib.util.module_from_spec(spec)
|
| 61 |
+
spec.loader.exec_module(module)
|
| 62 |
+
return module
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def plane(value: float = VALUE) -> np.ndarray:
|
| 66 |
+
m = np.zeros((250, 250, 3), np.float32)
|
| 67 |
+
m[120:120 + SIDE, 110:110 + SIDE, 2] = value
|
| 68 |
+
return m
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def encode(matrix: np.ndarray, spec: str) -> list:
|
| 72 |
+
"""四个档位的落盘编码(与 ui.main_window.encode_gripper_force_matrix 同口径)。"""
|
| 73 |
+
flat = np.asarray(matrix, np.float32).reshape(matrix.shape[0], -1)
|
| 74 |
+
if spec == "float32":
|
| 75 |
+
return flat.reshape(-1).tolist()
|
| 76 |
+
n = {"int16": 1, "int16x10": 10, "int16x100": 100,
|
| 77 |
+
"int16x1000": 1000}[spec]
|
| 78 |
+
q = (np.clip(flat, -32767.0, 32767.0).astype(np.int16) if n == 1
|
| 79 |
+
else np.clip(np.rint(flat * np.float32(n)),
|
| 80 |
+
-32767.0, 32767.0).astype(np.int16))
|
| 81 |
+
diff = np.empty_like(q)
|
| 82 |
+
diff[:, 0] = q[:, 0]
|
| 83 |
+
diff[:, 1:] = q[:, 1:] - q[:, :-1]
|
| 84 |
+
return np.frombuffer(diff.tobytes(), dtype=np.int16).tolist()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def make_task(root: str, name: str, spec: str, index: int = 1,
|
| 88 |
+
with_force: bool = True, with_meta_specs: bool = False,
|
| 89 |
+
active_frames: int = N_FRAMES) -> str:
|
| 90 |
+
"""合成一份「旧格式」任务:meta 行没有 force_matrix_specs(除非要求)。
|
| 91 |
+
|
| 92 |
+
力列 fz = 矩阵平面 fz 之和 —— 这是标定档能还原到 1.000 的物理依据;
|
| 93 |
+
未定标档因截断会小于它,正是判据要区分的那条。
|
| 94 |
+
"""
|
| 95 |
+
task = os.path.join(root, name)
|
| 96 |
+
m_true = plane()
|
| 97 |
+
enc = encode(m_true, spec)
|
| 98 |
+
# 前 active_frames 帧有样本,其余留空(稀疏列)
|
| 99 |
+
rows = [enc] * active_frames + [[]] * (N_FRAMES - active_frames)
|
| 100 |
+
cols = {"frame_index": pa.array(range(N_FRAMES), pa.int64()),
|
| 101 |
+
COLUMN: pa.array(rows, pa.list_(
|
| 102 |
+
pa.float32() if spec == "float32" else pa.int16()))}
|
| 103 |
+
if with_force:
|
| 104 |
+
# 力列给真值(矩阵真值之和),与档位无关
|
| 105 |
+
total = float(m_true[:, :, 2].sum())
|
| 106 |
+
cols[FORCE_COLUMN] = pa.array(
|
| 107 |
+
[[0.0, 0.0, total]] * N_FRAMES, pa.list_(pa.float32(), 3))
|
| 108 |
+
data_path = pooled_data_parquet_path(task, index)
|
| 109 |
+
os.makedirs(os.path.dirname(data_path), exist_ok=True)
|
| 110 |
+
pq.write_table(pa.table(cols), data_path)
|
| 111 |
+
|
| 112 |
+
specs = {} if not with_meta_specs else {
|
| 113 |
+
COLUMN: {"dtype": "float32" if spec == "float32" else "int16",
|
| 114 |
+
"shape": [250, 250, 3],
|
| 115 |
+
"encoding": ("row_flat_raw" if spec == "float32"
|
| 116 |
+
else "row_diff_quantized"),
|
| 117 |
+
"scale": 1}}
|
| 118 |
+
meta_path = pooled_episodes_path(task, index)
|
| 119 |
+
os.makedirs(os.path.dirname(meta_path), exist_ok=True)
|
| 120 |
+
pq.write_table(_episode_rows_table([{
|
| 121 |
+
"episode_index": index, "task_index": 0, "start_frame_index": 0,
|
| 122 |
+
"end_frame_index": N_FRAMES - 1, "length": N_FRAMES,
|
| 123 |
+
"created_at": 0.0, "duration_sec": 0.2, "drop_stats": "{}",
|
| 124 |
+
"video_codec": "{}", "calibration": "{}",
|
| 125 |
+
"force_matrix_specs": json.dumps(specs),
|
| 126 |
+
}]), meta_path)
|
| 127 |
+
return task
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main() -> int:
|
| 131 |
+
mod = load_repair_module()
|
| 132 |
+
tmp = tempfile.mkdtemp(prefix="repair_scale_")
|
| 133 |
+
try:
|
| 134 |
+
print("[1] 各档位都判得出(实测比值定档)")
|
| 135 |
+
for spec, want in (("float32", 1), ("int16x10", 10),
|
| 136 |
+
("int16x100", 100), ("int16x1000", 1000),
|
| 137 |
+
("int16", 1)):
|
| 138 |
+
task = make_task(tmp, f"t_{spec}", spec)
|
| 139 |
+
dpath = pooled_data_parquet_path(task, 1)
|
| 140 |
+
got, why = mod.infer_scale(dpath, COLUMN, FORCE_COLUMN)
|
| 141 |
+
check(f"{spec} → ×{want}",
|
| 142 |
+
got == want, f"判得 ×{got}:{why}")
|
| 143 |
+
|
| 144 |
+
print("[2] 判不出的情形一律不写")
|
| 145 |
+
no_force = make_task(tmp, "no_force", "int16x10", with_force=False)
|
| 146 |
+
got, why = mod.infer_scale(pooled_data_parquet_path(no_force, 1),
|
| 147 |
+
COLUMN, FORCE_COLUMN)
|
| 148 |
+
check("无 force 列可比对 → 判不出", got is None, str(why))
|
| 149 |
+
|
| 150 |
+
# 力列恒为 0(近零帧是分母噪声,不能拿来比)→ 有效帧不足
|
| 151 |
+
zero = make_task(tmp, "zero_force", "int16x10")
|
| 152 |
+
zpath = pooled_data_parquet_path(zero, 1)
|
| 153 |
+
table = pq.read_table(zpath)
|
| 154 |
+
table = table.set_column(table.schema.get_field_index(FORCE_COLUMN),
|
| 155 |
+
FORCE_COLUMN,
|
| 156 |
+
pa.array([[0.0, 0.0, 0.0]] * N_FRAMES,
|
| 157 |
+
pa.list_(pa.float32(), 3)))
|
| 158 |
+
pq.write_table(table, zpath)
|
| 159 |
+
got, why = mod.infer_scale(zpath, COLUMN, FORCE_COLUMN)
|
| 160 |
+
check("力列全零 → 有效帧不足、判不出", got is None, str(why))
|
| 161 |
+
|
| 162 |
+
few = make_task(tmp, "few_frames", "int16x10", active_frames=2)
|
| 163 |
+
got, why = mod.infer_scale(pooled_data_parquet_path(few, 1),
|
| 164 |
+
COLUMN, FORCE_COLUMN)
|
| 165 |
+
check("有效帧 < 5 → 判不出(不拿两帧中位数赌)", got is None, str(why))
|
| 166 |
+
|
| 167 |
+
print("[3] 补写只动 meta 行")
|
| 168 |
+
task = make_task(tmp, "apply_int16x10", "int16x10")
|
| 169 |
+
dpath = pooled_data_parquet_path(task, 1)
|
| 170 |
+
|
| 171 |
+
def recorded():
|
| 172 |
+
raw = pq.read_table(pooled_episodes_path(task, 1),
|
| 173 |
+
columns=["force_matrix_specs"]).column(0)[0]
|
| 174 |
+
return json.loads(raw.as_py() or "{}")
|
| 175 |
+
|
| 176 |
+
before = open(dpath, "rb").read()
|
| 177 |
+
check("预览模式不写", mod.repair(task, False) == 0 and recorded() == {},
|
| 178 |
+
"预览后 meta 仍未记录")
|
| 179 |
+
check("apply 写入", mod.repair(task, True) == 0)
|
| 180 |
+
specs = recorded()
|
| 181 |
+
check("写入 ×10(实测比值定档)",
|
| 182 |
+
specs[COLUMN]["scale"] == 10 and specs[COLUMN]["dtype"] == "int16",
|
| 183 |
+
str(specs.get(COLUMN)))
|
| 184 |
+
check("data parquet 逐字节不变(只补 meta)",
|
| 185 |
+
open(dpath, "rb").read() == before)
|
| 186 |
+
|
| 187 |
+
print("[4] 已有权威倍率的段不重推")
|
| 188 |
+
ws = make_task(tmp, "already_has", "int16x1000",
|
| 189 |
+
with_meta_specs=True) # 记为 ×1(模拟旧值)
|
| 190 |
+
check("plan_task 不把已记录的段列为待补",
|
| 191 |
+
all(name != "episode-000.parquet"
|
| 192 |
+
for name, *_ in mod.plan_task(ws)),
|
| 193 |
+
str([n for n, *_ in mod.plan_task(ws)]))
|
| 194 |
+
finally:
|
| 195 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 196 |
+
|
| 197 |
+
print()
|
| 198 |
+
if _FAILS:
|
| 199 |
+
print(f"FAILED: {len(_FAILS)} 项 — {_FAILS}")
|
| 200 |
+
return 1
|
| 201 |
+
print("ALL PASS")
|
| 202 |
+
return 0
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
sys.exit(main())
|
collector/tools/tests/test_task_progress_retry.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""进度上报「404 降级 → 冷却期 → 自动恢复」单测 —— 不联网、不开线程。
|
| 2 |
+
|
| 3 |
+
背景:老后端没有 /api/v1/device/tasks/progress,采集端收到 404 就永久降级
|
| 4 |
+
(整机不再上报进度)。服务端补上该端点后,若不重启采集端就永远恢复不了,
|
| 5 |
+
所以在 404 分支加了冷却期重探(PROGRESS_RETRY_INTERVAL_S)。
|
| 6 |
+
|
| 7 |
+
覆盖:
|
| 8 |
+
1. 404 → 降级 + 排冷却期;冷却期内不再发任何请求
|
| 9 |
+
2. 冷却期过后试探成功 → 自动恢复上报,并回写后端权威数
|
| 10 |
+
3. 冷却期过后仍 404 → 继续降级、冷却期推后
|
| 11 |
+
4. 正常成功路径不受影响(不会把 supported 弄反)
|
| 12 |
+
|
| 13 |
+
用法:
|
| 14 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_task_progress_retry.py
|
| 15 |
+
"""
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 21 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 22 |
+
|
| 23 |
+
from PyQt5.QtWidgets import QApplication
|
| 24 |
+
|
| 25 |
+
from core import task_record
|
| 26 |
+
from core import task_service as ts
|
| 27 |
+
|
| 28 |
+
FAILS = []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def check(cond, msg):
|
| 32 |
+
if cond:
|
| 33 |
+
print(f" PASS: {msg}")
|
| 34 |
+
else:
|
| 35 |
+
print(f" FAIL: {msg}")
|
| 36 |
+
FAILS.append(msg)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
PENDING = [{"id": "task-aaa", "local_count": 12, "synced_count": 0}]
|
| 40 |
+
SYNCED = []
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _install_stubs():
|
| 44 |
+
"""task_record 走内存替身:只关心「谁在什么时候被回写了什么」。"""
|
| 45 |
+
task_record.pending_sync_tasks = lambda: [dict(p) for p in PENDING]
|
| 46 |
+
task_record.mark_synced = (
|
| 47 |
+
lambda tid, sc, backend: SYNCED.append((tid, sc, backend)))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _service(results):
|
| 51 |
+
"""建一个 TaskService,_post_progress 换成按队列出结果的桩。
|
| 52 |
+
|
| 53 |
+
results: [(new_backend | None, err)] —— 每次 POST 消费一条。
|
| 54 |
+
"""
|
| 55 |
+
svc = ts.TaskService("http://127.0.0.1:9")
|
| 56 |
+
svc._trigger_login_and_poll = lambda: None # 别真去联网/起线程
|
| 57 |
+
svc._trigger_poll = lambda: None
|
| 58 |
+
calls = []
|
| 59 |
+
svc._post_progress = lambda tid, sid, inc, dev: (
|
| 60 |
+
calls.append((tid, sid, inc, dev)),
|
| 61 |
+
results.pop(0) if results else (None, "http"),
|
| 62 |
+
)[1]
|
| 63 |
+
svc.calls = calls
|
| 64 |
+
svc.results = results
|
| 65 |
+
return svc
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main():
|
| 69 |
+
_install_stubs()
|
| 70 |
+
|
| 71 |
+
# ── 1. 404 → 降级 + 冷却期 ────────────────────────
|
| 72 |
+
print("[1] 404 降级并排冷却期")
|
| 73 |
+
svc = _service([(None, "404")])
|
| 74 |
+
svc._flush_progress()
|
| 75 |
+
check(svc._progress_supported is False, "404 后进入降级")
|
| 76 |
+
check(svc._progress_retry_at > time.monotonic(), "已排下一次试探时刻")
|
| 77 |
+
check(len(svc.calls) == 1, "本轮只发了 1 次请求(遇 404 立刻返回)")
|
| 78 |
+
check(svc.calls[0][1] == "{}:task-aaa:0".format(
|
| 79 |
+
getattr(ts.settings, "DEVICE_NAME", "EGO_001")),
|
| 80 |
+
"幂等键仍是 设备:任务:水位")
|
| 81 |
+
|
| 82 |
+
n = len(svc.calls)
|
| 83 |
+
svc._flush_progress()
|
| 84 |
+
svc._flush_progress()
|
| 85 |
+
check(len(svc.calls) == n, "冷却期内再 flush 两次都不发请求")
|
| 86 |
+
|
| 87 |
+
# ── 2. 冷却期结束 + 后端已实现 → 自动恢复 ─────────
|
| 88 |
+
print("[2] 冷却期后试探成功 → 恢复上报")
|
| 89 |
+
svc.results.append((12, "")) # 后端这次答 200
|
| 90 |
+
svc._progress_retry_at = time.monotonic() - 1 # 模拟冷却期已过
|
| 91 |
+
SYNCED.clear()
|
| 92 |
+
svc._flush_progress()
|
| 93 |
+
check(len(svc.calls) == n + 1, "冷却期过后试探了一次")
|
| 94 |
+
check(svc._progress_supported is True, "试探成功后恢复上报")
|
| 95 |
+
check(SYNCED == [("task-aaa", 12, 12)], "试探成功即回写 (水位, 后端权威数)")
|
| 96 |
+
|
| 97 |
+
svc.results.append((13, ""))
|
| 98 |
+
svc._progress_retry_at = 0.0
|
| 99 |
+
svc._flush_progress()
|
| 100 |
+
check(len(svc.calls) == n + 2, "恢复后按正常节奏继续上报")
|
| 101 |
+
check(SYNCED[-1] == ("task-aaa", 12, 13), "后续增量照常回写")
|
| 102 |
+
|
| 103 |
+
# ── 3. 冷却期结束但仍 404 → 继续降级、冷却期推后 ──
|
| 104 |
+
print("[3] 仍 404 → 冷却期推后")
|
| 105 |
+
svc2 = _service([(None, "404"), (None, "404")])
|
| 106 |
+
svc2._flush_progress()
|
| 107 |
+
at1 = svc2._progress_retry_at
|
| 108 |
+
svc2._progress_retry_at = time.monotonic() - 1
|
| 109 |
+
svc2._flush_progress()
|
| 110 |
+
check(svc2._progress_supported is False, "仍然保持降级")
|
| 111 |
+
check(svc2._progress_retry_at > time.monotonic(),
|
| 112 |
+
"冷却期被重新推后(不会每个 tick 都探)")
|
| 113 |
+
check(svc2._progress_retry_at != at1, "试探时刻确实变了")
|
| 114 |
+
check(len(svc2.calls) == 2, "两次试探各发 1 次请求")
|
| 115 |
+
|
| 116 |
+
# ── 4. 正常成功路径 ──────────────────────────────
|
| 117 |
+
print("[4] 正常路径不受影响")
|
| 118 |
+
svc3 = _service([(5, "")])
|
| 119 |
+
SYNCED.clear()
|
| 120 |
+
svc3._flush_progress()
|
| 121 |
+
check(svc3._progress_supported is True, "成功不上锁")
|
| 122 |
+
check(svc3._progress_retry_at == 0.0, "成功不排冷却期")
|
| 123 |
+
check(SYNCED == [("task-aaa", 12, 5)], "后端权威数 5 被采纳")
|
| 124 |
+
|
| 125 |
+
# ── 5. set_server_url 立刻解除降级 ───���───────────
|
| 126 |
+
print("[5] 换服务器地址立刻解除降级")
|
| 127 |
+
svc._progress_supported = False
|
| 128 |
+
svc._progress_retry_at = time.monotonic() + 999
|
| 129 |
+
svc.set_server_url("http://127.0.0.1:8")
|
| 130 |
+
check(svc._progress_supported is True and svc._progress_retry_at == 0.0,
|
| 131 |
+
"换地址后立即允许上报(不等冷却期)")
|
| 132 |
+
|
| 133 |
+
print("FAIL" if FAILS else "PASS: 进度上报降级/恢复 全部通过")
|
| 134 |
+
return 1 if FAILS else 0
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
app = QApplication(sys.argv)
|
| 139 |
+
sys.exit(main())
|
collector/ui/main_window.py
CHANGED
|
@@ -115,25 +115,76 @@ except ImportError:
|
|
| 115 |
_GLOVE_AVAILABLE = False
|
| 116 |
|
| 117 |
|
| 118 |
-
def encode_gripper_force_matrix(m: np.ndarray) -> list:
|
| 119 |
-
"""触觉力矩阵
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
"""
|
|
|
|
|
|
|
| 127 |
arr = np.asarray(m, dtype=np.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
rows = int(arr.shape[0])
|
| 129 |
flat = arr.reshape(rows, -1)
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
d = np.empty_like(q)
|
| 132 |
d[:, 0] = q[:, 0]
|
| 133 |
d[:, 1:] = q[:, 1:] - q[:, :-1] # int16 mod 2^16 回绕
|
| 134 |
return np.frombuffer(d.tobytes(), dtype=np.int16).tolist()
|
| 135 |
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
class MainWindow(QMainWindow):
|
| 138 |
"""应用程序主窗口。"""
|
| 139 |
|
|
@@ -510,6 +561,33 @@ class MainWindow(QMainWindow):
|
|
| 510 |
tb.addAction(self._upload_delete_action)
|
| 511 |
self._style_toolbar_toggle(self._upload_delete_action)
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
self.addToolBar(tb)
|
| 514 |
|
| 515 |
# ── 第二排工具栏:手部追踪 ───────────────────
|
|
@@ -1599,8 +1677,8 @@ class MainWindow(QMainWindow):
|
|
| 1599 |
entry["_stereo_display_seq"] = 0 # 每 2 帧显示 1 帧的计数
|
| 1600 |
entry["gripper_index"] = index
|
| 1601 |
entry["slot_map"] = slot_map
|
| 1602 |
-
# 双夹爪数据列命名空间:rig1 空串(旧键
|
| 1603 |
-
# gripper_{side}_force…不变),rig2 "gripper_2_" 前缀
|
| 1604 |
entry["snapshot_prefix"] = ("" if index == 1
|
| 1605 |
else f"gripper_{index}_")
|
| 1606 |
self._workers[dev.key] = entry
|
|
@@ -1710,8 +1788,9 @@ class MainWindow(QMainWindow):
|
|
| 1710 |
def _on_gripper_pose(self, dev_key: str, position, quat, trajectory=(),
|
| 1711 |
timestamp=None):
|
| 1712 |
"""SLAM 位姿(pos3, quat4, traj, t):quat→3x3 驱动 PoseViewQt
|
| 1713 |
-
(含轨迹) + 落盘
|
| 1714 |
-
slam_trajectory 列(轨迹并入 episode parquet,无 txt 侧车)。
|
|
|
|
| 1715 |
entry = self._gripper_entry(dev_key)
|
| 1716 |
if entry is None:
|
| 1717 |
return
|
|
@@ -1731,7 +1810,7 @@ class MainWindow(QMainWindow):
|
|
| 1731 |
pose_view = entry.get("pose_view")
|
| 1732 |
if pose_view is not None:
|
| 1733 |
pose_view.update_pose(position, rotation, trajectory)
|
| 1734 |
-
self._pipeline.
|
| 1735 |
[float(position[0]), float(position[1]), float(position[2]),
|
| 1736 |
qx, qy, qz, qw],
|
| 1737 |
prefix=entry["snapshot_prefix"], timestamp=timestamp)
|
|
@@ -1791,6 +1870,18 @@ class MainWindow(QMainWindow):
|
|
| 1791 |
stop = threading.Event()
|
| 1792 |
entry["matrix_pump_stop"] = stop
|
| 1793 |
entry["matrix_wrote"] = {"left": 0, "right": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1794 |
thread = threading.Thread(
|
| 1795 |
target=self._matrix_pump_loop,
|
| 1796 |
args=(bridge, stop, entry),
|
|
@@ -1805,10 +1896,11 @@ class MainWindow(QMainWindow):
|
|
| 1805 |
self._log(tr("[夹爪] 力矩阵泵未启动:无夹爪设备条目"))
|
| 1806 |
|
| 1807 |
def _matrix_pump_loop(self, bridge, stop, entry):
|
| 1808 |
-
"""泵线程体:仅在有新矩阵时编码(
|
| 1809 |
last_seq = {"left": 0, "right": 0}
|
| 1810 |
first_logged = {"left": False, "right": False}
|
| 1811 |
wrote = entry["matrix_wrote"]
|
|
|
|
| 1812 |
started = time.monotonic()
|
| 1813 |
self._log(tr("[夹爪] 力矩阵泵已启动 (L seq={} R seq={})",
|
| 1814 |
bridge.matrix_seq("left"),
|
|
@@ -1823,7 +1915,7 @@ class MainWindow(QMainWindow):
|
|
| 1823 |
if matrix is None:
|
| 1824 |
continue
|
| 1825 |
try:
|
| 1826 |
-
encoded = encode_gripper_force_matrix(matrix)
|
| 1827 |
except Exception as exc:
|
| 1828 |
self._log(tr("[夹爪] 力矩阵编码失败 ({}): {}",
|
| 1829 |
side, exc))
|
|
@@ -2753,6 +2845,13 @@ class MainWindow(QMainWindow):
|
|
| 2753 |
" font-weight:bold; border-color:#2E7D32; }"
|
| 2754 |
)
|
| 2755 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2756 |
def _on_upload_auto_toggled(self, on: bool):
|
| 2757 |
""""自动上传"开关——持久化,重启后保持;按钮文字同步开/关状态。"""
|
| 2758 |
settings.save_upload_auto_sync(bool(on))
|
|
@@ -2767,6 +2866,30 @@ class MainWindow(QMainWindow):
|
|
| 2767 |
self._upload_delete_action.setText(
|
| 2768 |
tr("🗑 上传后自动删除: {}", tr("开") if on else tr("关")))
|
| 2769 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2770 |
def _on_upload_task_failed(self, task_id: str, error: str):
|
| 2771 |
"""自动上传失败——记录日志(重试 3 次后仍失败才触发)。"""
|
| 2772 |
self._upload_log_ts.pop(task_id, None)
|
|
|
|
| 115 |
_GLOVE_AVAILABLE = False
|
| 116 |
|
| 117 |
|
| 118 |
+
def encode_gripper_force_matrix(m: np.ndarray, spec: str = "int16") -> list:
|
| 119 |
+
"""触觉力矩阵编码(P4 泵线程,返回扁平数值列表)。
|
| 120 |
+
|
| 121 |
+
spec 取 settings.GRIPPER_FORCE_MATRIX_SPECS 之一。
|
| 122 |
+
|
| 123 |
+
**注意**:省略 spec 时走的是函数签名默认 "int16"(兼容历史调用的冻结
|
| 124 |
+
契约),**不跟随工具栏的默认档**;生产路径(P4 泵)一律显式传入录制
|
| 125 |
+
开始时锁定的 spec,绝不省略。
|
| 126 |
+
|
| 127 |
+
"int16"(既有契约):不缩放,与
|
| 128 |
+
online/recording/lerobot_v3.quantize_force_matrix 一致的有符号补码行
|
| 129 |
+
差分(mod 2^16 可逆),扩展到 (250,250,3) 三力平面:每行 250×3 个
|
| 130 |
+
元素横向差分;超出 ±32767 mN 饱和截断。**逐点 astype(int16) 是向零
|
| 131 |
+
截断,小数部分全部丢失**——实测真实录制里逐点值只剩 -3…8 的整数电平,
|
| 132 |
+
亚毫牛梯度(接触形状)不可恢复。保留向零截断是为了与历史录制逐位一致。
|
| 133 |
+
|
| 134 |
+
"int16xN"(N=10/100/1000,定标量化):先 ×N 再四舍五入到整数存 int16,
|
| 135 |
+
解码端除以 N 还原,分辨率 1/N mN。饱和上限相应变为 ±32767/N mN
|
| 136 |
+
(×1000 即 ±32.767 mN)。定标档用 rint 而非截断:没有历史包袱,且
|
| 137 |
+
四舍五入把最大误差减半、不留系统性偏零。行差分与 int16 档完全相同,
|
| 138 |
+
所以仍然压得很小(×10 实测 0.122 字节/点,float32 的 1/6.5)。
|
| 139 |
+
|
| 140 |
+
"float32"(原值直存):不做任何量化,把 (250,250,3) 按行展平成 250×750
|
| 141 |
+
的 float32 列表。无截断、无饱和,误差为 float32 本身的 ~1e-7 相对精度。
|
| 142 |
+
体积换精度:实测 0.797 字节/点(本段数据约为 int16 档的 119 倍)。
|
| 143 |
+
|
| 144 |
+
反解:整数档 reshape(-1,750) → cumsum(axis=1) → reshape(250,250,3)
|
| 145 |
+
(cumsum 走 int32 再截断回 int16 恢复 mod 2^16 回绕),
|
| 146 |
+
再按倍率 ÷N;float32 档 reshape(-1,750) → (250,250,3)。
|
| 147 |
+
|
| 148 |
+
★ 返回的 Python 元素类型只区分「家族」:int = int16 系(**倍率无法从
|
| 149 |
+
元素类型看出**,×10 和 ×1000 都是 int),float = float32。
|
| 150 |
+
倍率必须由 info.json features.scale 携带,writer 与 demo 都按
|
| 151 |
+
scale + 列类型共同判别,不要只看元素类型。
|
| 152 |
"""
|
| 153 |
+
if spec not in settings.GRIPPER_FORCE_MATRIX_SPECS:
|
| 154 |
+
raise ValueError(f"未知力矩阵规格 {spec!r}")
|
| 155 |
arr = np.asarray(m, dtype=np.float32)
|
| 156 |
+
if spec == "float32":
|
| 157 |
+
# 与整数档同为「扁平 250×750 列表」,只有元素类型不同:
|
| 158 |
+
# 读取端统一 reshape(-1,750) 后再按 dtype 决定是否 cumsum
|
| 159 |
+
return arr.reshape(-1).tolist()
|
| 160 |
+
scale = settings.GRIPPER_FORCE_MATRIX_SCALES[spec]
|
| 161 |
rows = int(arr.shape[0])
|
| 162 |
flat = arr.reshape(rows, -1)
|
| 163 |
+
if scale == 1:
|
| 164 |
+
q = np.clip(flat, -32767.0, 32767.0).astype(np.int16)
|
| 165 |
+
else:
|
| 166 |
+
# rint 后已是整数值,astype 的向零截断不再丢任何东西
|
| 167 |
+
q = np.clip(np.rint(flat * np.float32(scale)),
|
| 168 |
+
-32767.0, 32767.0).astype(np.int16)
|
| 169 |
d = np.empty_like(q)
|
| 170 |
d[:, 0] = q[:, 0]
|
| 171 |
d[:, 1:] = q[:, 1:] - q[:, :-1] # int16 mod 2^16 回绕
|
| 172 |
return np.frombuffer(d.tobytes(), dtype=np.int16).tolist()
|
| 173 |
|
| 174 |
|
| 175 |
+
def describe_gripper_matrix_spec(spec: str) -> str:
|
| 176 |
+
"""规格 → 人话(工具栏提示与日志共用,别在两处各写一份)。"""
|
| 177 |
+
if spec not in settings.GRIPPER_FORCE_MATRIX_SPECS:
|
| 178 |
+
return tr("未知规格 {}", spec)
|
| 179 |
+
scale = settings.GRIPPER_FORCE_MATRIX_SCALES.get(spec)
|
| 180 |
+
if scale is None:
|
| 181 |
+
return tr("float32 原值直存(无截断无饱和,体积最大)")
|
| 182 |
+
if scale == 1:
|
| 183 |
+
return tr("int16 行差分量化(1 mN 台阶、向零截断,体积最小)")
|
| 184 |
+
return tr("int16 定标 ×{}(分辨率 {} mN,饱和上限 ±{} mN)",
|
| 185 |
+
scale, 1.0 / scale, 32767.0 / scale)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
class MainWindow(QMainWindow):
|
| 189 |
"""应用程序主窗口。"""
|
| 190 |
|
|
|
|
| 561 |
tb.addAction(self._upload_delete_action)
|
| 562 |
self._style_toolbar_toggle(self._upload_delete_action)
|
| 563 |
|
| 564 |
+
# 力矩阵保存规格(5 档下拉;持久化到 server_config.json)。
|
| 565 |
+
# 档位只决定落盘,实时显示一直走 float32 原值。
|
| 566 |
+
# 倍率无法从列类型看出���×10 与 ×1000 都是 int16),所以 info.json
|
| 567 |
+
# features.scale 是对外契约的一部分,改名等于改数据格式。
|
| 568 |
+
tb.addWidget(QLabel(tr(" 🎚 力矩阵精度: ")))
|
| 569 |
+
self._matrix_fmt_combo = QComboBox(self)
|
| 570 |
+
for spec in settings.GRIPPER_FORCE_MATRIX_SPECS:
|
| 571 |
+
self._matrix_fmt_combo.addItem(spec, spec)
|
| 572 |
+
cur = settings.GRIPPER_FORCE_MATRIX_SPEC
|
| 573 |
+
self._matrix_fmt_combo.setCurrentIndex(
|
| 574 |
+
settings.GRIPPER_FORCE_MATRIX_SPECS.index(cur)
|
| 575 |
+
if cur in settings.GRIPPER_FORCE_MATRIX_SPECS else 0)
|
| 576 |
+
self._matrix_fmt_combo.setToolTip(tr(
|
| 577 |
+
"力矩阵落盘规格(与实时显示无关),改动在下次开始录制时锁定生效:\n"
|
| 578 |
+
" int16 1 mN 台阶、向零截断,体积最小(0.007 字节/点)\n"
|
| 579 |
+
" int16×10 0.1 mN,13.95MB/段 —— 量程 ±3276.7 mN,重压场景用\n"
|
| 580 |
+
" int16×100 0.01 mN,34.78MB/段 —— 默认档;量程 ±327.67 mN\n"
|
| 581 |
+
" int16×1000 0.001 mN,53.84MB/段\n"
|
| 582 |
+
" float32 原值直存,91.26MB/段\n"
|
| 583 |
+
"(体积为 episode-016 左列 611 帧单列实测,ZSTD 后)\n"
|
| 584 |
+
"训练侧按 meta/info.json 的 features.scale 还原,×10 与 ×1000 "
|
| 585 |
+
"的列类型相同、只能靠 scale 区分"))
|
| 586 |
+
self._matrix_fmt_combo.currentIndexChanged.connect(
|
| 587 |
+
self._on_matrix_fmt_changed)
|
| 588 |
+
tb.addWidget(self._matrix_fmt_combo)
|
| 589 |
+
self._style_toolbar_combo(self._matrix_fmt_combo)
|
| 590 |
+
|
| 591 |
self.addToolBar(tb)
|
| 592 |
|
| 593 |
# ── 第二排工具栏:手部追踪 ───────────────────
|
|
|
|
| 1677 |
entry["_stereo_display_seq"] = 0 # 每 2 帧显示 1 帧的计数
|
| 1678 |
entry["gripper_index"] = index
|
| 1679 |
entry["slot_map"] = slot_map
|
| 1680 |
+
# 双夹爪数据列命名空间:rig1 空串(旧键 slam_trajectory/
|
| 1681 |
+
# gripper_state/gripper_{side}_force…不变),rig2 "gripper_2_" 前缀
|
| 1682 |
entry["snapshot_prefix"] = ("" if index == 1
|
| 1683 |
else f"gripper_{index}_")
|
| 1684 |
self._workers[dev.key] = entry
|
|
|
|
| 1788 |
def _on_gripper_pose(self, dev_key: str, position, quat, trajectory=(),
|
| 1789 |
timestamp=None):
|
| 1790 |
"""SLAM 位姿(pos3, quat4, traj, t):quat→3x3 驱动 PoseViewQt
|
| 1791 |
+
(含轨迹) + 轨迹点落盘(rig2 加前缀);t 随位姿进入
|
| 1792 |
+
slam_trajectory 列(轨迹并入 episode parquet,无 txt 侧车)。
|
| 1793 |
+
位姿本身不再落 slam_pose 列(2026-09-10 定案)。"""
|
| 1794 |
entry = self._gripper_entry(dev_key)
|
| 1795 |
if entry is None:
|
| 1796 |
return
|
|
|
|
| 1810 |
pose_view = entry.get("pose_view")
|
| 1811 |
if pose_view is not None:
|
| 1812 |
pose_view.update_pose(position, rotation, trajectory)
|
| 1813 |
+
self._pipeline.write_slam_trajectory(
|
| 1814 |
[float(position[0]), float(position[1]), float(position[2]),
|
| 1815 |
qx, qy, qz, qw],
|
| 1816 |
prefix=entry["snapshot_prefix"], timestamp=timestamp)
|
|
|
|
| 1870 |
stop = threading.Event()
|
| 1871 |
entry["matrix_pump_stop"] = stop
|
| 1872 |
entry["matrix_wrote"] = {"left": 0, "right": 0}
|
| 1873 |
+
# 规格在录制开始锁定:parquet 一列只有一种类型,录制中切换会
|
| 1874 |
+
# 让同一列出现 int/float 混型(write 侧直接报错,整段录制废掉)。
|
| 1875 |
+
# 工具栏档位只在录制开始/结束之间生效,录制中改动留到下一次。
|
| 1876 |
+
spec = settings.GRIPPER_FORCE_MATRIX_SPEC
|
| 1877 |
+
entry["matrix_spec"] = spec
|
| 1878 |
+
# 倍率登记到 writer:×10/×100/×1000 落盘类型都是 int16,元素
|
| 1879 |
+
# 类型分辨不出倍率,info.json features.scale 是唯一的对外凭据。
|
| 1880 |
+
# 此处 writer 已 start_episode 完毕(recording_started 在
|
| 1881 |
+
# start_episode 之后 emit),登记不会被清掉。
|
| 1882 |
+
self._pipeline.set_force_matrix_spec(
|
| 1883 |
+
entry["snapshot_prefix"], spec)
|
| 1884 |
+
self._log(tr("[夹爪] 力矩阵保存规格:{}", describe_gripper_matrix_spec(spec)))
|
| 1885 |
thread = threading.Thread(
|
| 1886 |
target=self._matrix_pump_loop,
|
| 1887 |
args=(bridge, stop, entry),
|
|
|
|
| 1896 |
self._log(tr("[夹爪] 力矩阵泵未启动:无夹爪设备条目"))
|
| 1897 |
|
| 1898 |
def _matrix_pump_loop(self, bridge, stop, entry):
|
| 1899 |
+
"""泵线程体:仅在有新矩阵时编码(按本次录制锁定的规格)+ 快照写入。"""
|
| 1900 |
last_seq = {"left": 0, "right": 0}
|
| 1901 |
first_logged = {"left": False, "right": False}
|
| 1902 |
wrote = entry["matrix_wrote"]
|
| 1903 |
+
spec = entry.get("matrix_spec", settings.GRIPPER_FORCE_MATRIX_SPEC_DEFAULT)
|
| 1904 |
started = time.monotonic()
|
| 1905 |
self._log(tr("[夹爪] 力矩阵泵已启动 (L seq={} R seq={})",
|
| 1906 |
bridge.matrix_seq("left"),
|
|
|
|
| 1915 |
if matrix is None:
|
| 1916 |
continue
|
| 1917 |
try:
|
| 1918 |
+
encoded = encode_gripper_force_matrix(matrix, spec)
|
| 1919 |
except Exception as exc:
|
| 1920 |
self._log(tr("[夹爪] 力矩阵编码失败 ({}): {}",
|
| 1921 |
side, exc))
|
|
|
|
| 2845 |
" font-weight:bold; border-color:#2E7D32; }"
|
| 2846 |
)
|
| 2847 |
|
| 2848 |
+
def _style_toolbar_combo(self, combo: QComboBox):
|
| 2849 |
+
"""工具栏下拉样式:与 _style_toolbar_toggle 的按钮同一边框/圆角。"""
|
| 2850 |
+
combo.setStyleSheet(
|
| 2851 |
+
"QComboBox { border:1px solid #555; border-radius:3px;"
|
| 2852 |
+
" padding:2px 6px; }"
|
| 2853 |
+
)
|
| 2854 |
+
|
| 2855 |
def _on_upload_auto_toggled(self, on: bool):
|
| 2856 |
""""自动上传"开关——持久化,重启后保持;按钮文字同步开/关状态。"""
|
| 2857 |
settings.save_upload_auto_sync(bool(on))
|
|
|
|
| 2866 |
self._upload_delete_action.setText(
|
| 2867 |
tr("🗑 上传后自动删除: {}", tr("开") if on else tr("关")))
|
| 2868 |
|
| 2869 |
+
def _on_matrix_fmt_changed(self, index: int):
|
| 2870 |
+
""""力矩阵精度"档位——持久化,重启后保持;录制开始时锁定生效。"""
|
| 2871 |
+
spec = self._matrix_fmt_combo.itemData(index)
|
| 2872 |
+
if not spec or spec == settings.GRIPPER_FORCE_MATRIX_SPEC:
|
| 2873 |
+
return
|
| 2874 |
+
try:
|
| 2875 |
+
settings.save_gripper_force_matrix_spec(spec)
|
| 2876 |
+
except ValueError as exc:
|
| 2877 |
+
self._log(tr("[夹爪] 力矩阵规格保存失败:{}", exc))
|
| 2878 |
+
return
|
| 2879 |
+
settings.GRIPPER_FORCE_MATRIX_SPEC = spec
|
| 2880 |
+
# 泵在跑 = 正在录制,其规格已在 _start_matrix_pump 锁进 entry。
|
| 2881 |
+
# 报实际在用的那个(而不是切换前的设置值),否则用户看到的
|
| 2882 |
+
# 「当前录制已在用 X」可能是上一段甚至更早的档位。
|
| 2883 |
+
running = sorted({e.get("matrix_spec") for e in self._gripper_entries()
|
| 2884 |
+
if e.get("matrix_pump_stop") is not None
|
| 2885 |
+
and e.get("matrix_spec")})
|
| 2886 |
+
if running:
|
| 2887 |
+
self._log(tr("[夹爪] 力矩阵规格已切到 {},但当前录制已在用 {},"
|
| 2888 |
+
"下次录制生效", spec, "/".join(running)))
|
| 2889 |
+
else:
|
| 2890 |
+
self._log(tr("[夹爪] 力矩阵保存规格:{}(下次录制生效)",
|
| 2891 |
+
describe_gripper_matrix_spec(spec)))
|
| 2892 |
+
|
| 2893 |
def _on_upload_task_failed(self, task_id: str, error: str):
|
| 2894 |
"""自动上传失败——记录日志(重试 3 次后仍失败才触发)。"""
|
| 2895 |
self._upload_log_ts.pop(task_id, None)
|